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/examples/directives/src/lib.rs | examples/directives/src/lib.rs | use leptos::{ev::click, prelude::*};
use web_sys::Element;
// no extra parameter
pub fn highlight(el: Element) {
let mut highlighted = false;
let handle = el.clone().on(click, move |_| {
highlighted = !highlighted;
if highlighted {
el.style(("background-color", "yellow"));
} else {
el.style(("background-color", "transparent"));
}
});
on_cleanup(move || drop(handle));
}
// one extra parameter
pub fn copy_to_clipboard(el: Element, content: &str) {
let content = content.to_owned();
let handle = el.clone().on(click, move |evt| {
evt.prevent_default();
evt.stop_propagation();
let _ = window().navigator().clipboard().write_text(&content);
el.set_inner_html(&format!("Copied \"{}\"", &content));
});
on_cleanup(move || drop(handle));
}
// custom parameter
#[derive(Clone)]
pub struct Amount(usize);
impl From<usize> for Amount {
fn from(value: usize) -> Self {
Self(value)
}
}
// a 'default' value if no value is passed in
impl From<()> for Amount {
fn from(_: ()) -> Self {
Self(1)
}
}
pub fn add_dot(el: Element, amount: Amount) {
use leptos::wasm_bindgen::JsCast;
let el = el.unchecked_into::<web_sys::HtmlElement>();
let handle = el.clone().on(click, move |_| {
el.set_inner_text(&format!(
"{}{}",
el.inner_text(),
".".repeat(amount.0)
))
});
on_cleanup(move || drop(handle));
}
#[component]
pub fn SomeComponent() -> impl IntoView {
view! {
<p>Some paragraphs</p>
<p>that can be clicked</p>
<p>in order to highlight them</p>
}
}
#[component]
pub fn App() -> impl IntoView {
let data = "Hello World!";
view! {
<a href="#" use:copy_to_clipboard=data>
"Copy \""
{data}
"\" to clipboard"
</a>
// automatically applies the directive to every root element in `SomeComponent`
<SomeComponent use:highlight/>
// no value will default to `().into()`
<button use:add_dot>"Add a dot"</button>
// can manually call `.into()` to convert to the correct type
// (automatically calling `.into()` prevents using generics in directive functions)
<button use:add_dot=5.into()>"Add 5 dots"</button>
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/directives/src/main.rs | examples/directives/src/main.rs | use directives::App;
use leptos::prelude::*;
fn main() {
_ = console_log::init_with_level(log::Level::Debug);
console_error_panic_hook::set_once();
mount_to_body(|| view! { <App/> })
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/directives/tests/web.rs | examples/directives/tests/web.rs | #![allow(dead_code)]
use directives::App;
use leptos::{prelude::*, task::tick};
use wasm_bindgen::JsCast;
use wasm_bindgen_test::*;
use web_sys::HtmlElement;
wasm_bindgen_test_configure!(run_in_browser);
#[wasm_bindgen_test]
async fn test_directives() {
leptos::mount::mount_to_body(App);
tick().await;
let document = document();
let paragraphs = document.query_selector_all("p").unwrap();
assert_eq!(paragraphs.length(), 3);
for i in 0..paragraphs.length() {
println!("i: {}", i);
let p = paragraphs
.item(i)
.unwrap()
.dyn_into::<HtmlElement>()
.unwrap();
assert_eq!(
p.style().get_property_value("background-color").unwrap(),
""
);
p.click();
assert_eq!(
p.style().get_property_value("background-color").unwrap(),
"yellow"
);
p.click();
assert_eq!(
p.style().get_property_value("background-color").unwrap(),
"transparent"
);
}
let a = document
.query_selector("a")
.unwrap()
.unwrap()
.dyn_into::<HtmlElement>()
.unwrap();
assert_eq!(a.inner_html(), "Copy \"Hello World!\" to clipboard");
a.click();
assert_eq!(a.inner_html(), "Copied \"Hello World!\"");
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/axum_js_ssr/src/app.rs | examples/axum_js_ssr/src/app.rs | use crate::{
api::fetch_code,
consts::{CH03_05A, LEPTOS_HYDRATED},
};
use leptos::prelude::*;
use leptos_meta::{MetaTags, *};
use leptos_router::{
components::{FlatRoutes, Route, Router, A},
path, SsrMode,
};
pub fn shell(options: LeptosOptions) -> impl IntoView {
view! {
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<AutoReload options=options.clone()/>
<HydrationScripts options/>
<MetaTags/>
</head>
<body>
<App/>
</body>
</html>
}
}
#[component]
pub fn App() -> impl IntoView {
// Provides context that manages stylesheets, titles, meta tags, etc.
provide_meta_context();
let fallback = || view! { "Page not found." }.into_view();
view! {
<Stylesheet id="leptos" href="/pkg/axum_js_ssr.css"/>
<Title text="Leptos JavaScript Integration Demo with SSR in Axum"/>
<Meta name="color-scheme" content="dark light"/>
<Router>
<nav>
<A attr:class="section" href="/">"Introduction (home)"</A>
<A attr:class="example" href="/naive">"Naive "<code>"<script>"</code>
<small>"truly naive to start off"</small></A>
<A attr:class="example" href="/naive-alt">"Leptos "<code>"<Script>"</code>
<small>"naively using load event"</small></A>
<A attr:class="example" href="/naive-hook">"Leptos "<code>"<Script>"</code>
<small>"... correcting placement"</small></A>
<A attr:class="example" href="/naive-fallback">"Leptos "<code>"<Script>"</code>
<small>"... with fallback"</small></A>
<A attr:class="example" href="/signal-effect-script">"Leptos Signal + Effect"
<small>"an idiomatic Leptos solution"</small></A>
<A attr:class="subexample section" href="/custom-event">"Hydrated Event"
<small>"using "<code>"js_sys"</code>"/"<code>"web_sys"</code></small></A>
<A attr:class="example" href="/wasm-bindgen-naive">"Using "<code>"wasm-bindgen"</code>
<small>"naively to start with"</small></A>
<A attr:class="example" href="/wasm-bindgen-event">"Using "<code>"wasm-bindgen"</code>
<small>"overcomplication with events"</small></A>
<A attr:class="example" href="/wasm-bindgen-effect">"Using "<code>"wasm-bindgen"</code>
<small>"lazily delay DOM manipulation"</small></A>
<A attr:class="example" href="/wasm-bindgen-direct">"Using "<code>"wasm-bindgen"</code>
<small>"without DOM manipulation"</small></A>
<A attr:class="example section" href="/wasm-bindgen-direct-fixed">
"Using "<code>"wasm-bindgen"</code>
<small>"corrected with signal + effect"</small>
</A>
<a id="reset" href="/" target="_self">"Restart/Rehydrate"
<small>"to make things work again"</small></a>
</nav>
<main>
<div id="notice">
"The WASM application has panicked during hydration. "
<a href="/" target="_self">
"Restart the application by going home"
</a>"."
</div>
<article>
<h1>"Leptos JavaScript Integration Demo with SSR in Axum"</h1>
<FlatRoutes fallback>
<Route path=path!("") view=HomePage/>
<Route path=path!("naive") view=Naive ssr=SsrMode::Async/>
<Route path=path!("naive-alt") view=|| view! { <NaiveEvent/> } ssr=SsrMode::Async/>
<Route path=path!("naive-hook") view=|| view! { <NaiveEvent hook=true/> } ssr=SsrMode::Async/>
<Route path=path!("naive-fallback") view=|| view! {
<NaiveEvent hook=true fallback=true/>
} ssr=SsrMode::Async/>
<Route path=path!("signal-effect-script") view=CodeDemoSignalEffect ssr=SsrMode::Async/>
<Route path=path!("custom-event") view=CustomEvent ssr=SsrMode::Async/>
<Route path=path!("wasm-bindgen-naive") view=WasmBindgenNaive ssr=SsrMode::Async/>
<Route path=path!("wasm-bindgen-event") view=WasmBindgenJSHookReadyEvent ssr=SsrMode::Async/>
<Route path=path!("wasm-bindgen-effect") view=WasmBindgenEffect ssr=SsrMode::Async/>
<Route path=path!("wasm-bindgen-direct") view=WasmBindgenDirect ssr=SsrMode::Async/>
<Route path=path!("wasm-bindgen-direct-fixed") view=WasmBindgenDirectFixed ssr=SsrMode::Async/>
</FlatRoutes>
</article>
</main>
</Router>
}
}
#[component]
fn HomePage() -> impl IntoView {
view! {
<p>"
This example application demonstrates a number of ways that JavaScript may be included and used
with Leptos naively, describing and showing the shortcomings and failures associated with each of
them for both SSR (Server-Side Rendering) and CSR (Client-Side Rendering) with hydration, before
leading up to the idiomatic solutions where they work as expected.
"</p>
<p>"
For the demonstrations, "<a href="https://github.com/highlightjs/highlight.js"><code>
"highlight.js"</code></a>" will be invoked from within this Leptos application by the examples
linked on the side bar. Since the library to be integrated is a JavaScript library, it must be
enabled to fully appreciate this demo, and having the browser's developer tools/console opened is
recommended as the logs will indicate the effects and issues as they happen.
"</p>
<p>"
Examples 1 to 5 are primarily JavaScript based, where the integration code is included as "<code>
"<script>"</code>" tags, with example 5 (final example of the group) being the idiomatic solution
that runs without errors or panic during hydration, plus an additional example 5.1 showing how to
get hydration to dispatch an event for JavaScript libraries should that be required. Examples 6
to 10 uses "<code>"wasm-bindgen"</code>" to call out to the JavaScript library from Rust, starting
off with naive examples that mimics JavaScript conventions, again with the final example of the
group (example 10) being the fully working version that embraces the use of Rust.
"</p>
}
}
#[derive(Clone, Debug)]
struct CodeDemoHook {
js_hook: String,
}
#[component]
fn CodeDemo() -> impl IntoView {
let code = Resource::new(|| (), |_| fetch_code());
let code_view = move || {
Suspend::new(async move {
let hook = use_context::<CodeDemoHook>().map(|h| {
leptos::logging::log!("use context suspend JS");
view! {
<Script>{h.js_hook}</Script>
}
});
view! {
<pre><code class="language-rust">{code.await}</code></pre>
{hook}
}
})
};
view! {
<p>"Explanation on what is being demonstrated follows after the following code example table."</p>
<div id="code-demo">
<table>
<thead>
<tr>
<th>"Inline code block (part of this component)"</th>
<th>"Dynamic code block (loaded via server fn)"</th>
</tr>
</thead>
<tbody>
<tr>
<td><pre><code class="language-rust">{CH03_05A}</code></pre></td>
<td>
<Suspense fallback=move || view! { <p>"Loading code example..."</p> }>
{code_view}
</Suspense>
</td>
</tr>
</tbody>
</table>
</div>
}
}
#[component]
fn Naive() -> impl IntoView {
let loader = r#"<script src="/highlight.min.js"></script>
<script>hljs.highlightAll();</script>"#;
view! {
<h2>"Showing what happens when script inclusion is done naively"</h2>
<CodeDemo/>
<p>"
This page demonstrates what happens (or doesn't happen) when it is assumed that the "<code>
"highlight.js"</code>" library can just be included from some CDN (well, hosted locally for this
example) as per their instructions for basic usage in the browser, specifically:
"</p>
<div><pre><code class="language-html">{loader}</code></pre></div>
<p>"
The following actions should be taken in order to fully experience the things that do not work as
expected:
"</p>
<ol>
<li>"
You may find that during the initial load of this page when first navigating to here from
\"Introduction\" (do navigate there, reload to reinitiate this application to properly
replicate the behavior, or simply use the Restart link at the bottom), none of the code
examples below are highlighted.
"</li>
<li>"
Go back and then forward again using the browser's navigation system the inline code block
will become highlighted. The cause is due to "<code>"highlight.js"</code>" being loaded in a
standard "<code>"<script>"</code>" tag that is part of this component and initially it wasn't
loaded before the call to "<code>"hljs.highlightAll();"</code>" was made. Later, when the
component gets re-rendered the second time, the code is finally available to ensure one of
them works (while also reloading the script, which probably isn't desirable for this use
case).
"</li>
<li>"
If you have the browser reload this page, you will find that "<strong>"both"</strong>" code
examples now appear to highlight correctly, yay! However you will also find that the browser's
back button appears to do nothing at all (even though the address bar may have changed), and
that most of the links on the side-bar are non-functional. A message should have popped up at
the top indicating that the application has panicked.
"<details>"
"<summary>"Details about the cause of the crash:"</summary>
<p>"
The cause here is because the hydration system found a node where text was expected, a
simple violation of the application's invariant. Specifically, the code block
originally contained plain text, but with highlighting that got changed to some HTML
markup "<em>"before"</em>" hydration happened, completely ouside of expectations.
Generally speaking, a panic is the worst kind of error, as it is a hard crash which
stops the application from working, and in this case the reactive system is in a
completely non-functional state.
"</p>
<p>"
Fortunately for this application, some internal links within this application have
been specifically excluded from the reactive system (specifically the restart links,
so they remain usable as they are just standard links which include the bottommost one
of the side bar and the one that should become visible as a notification as the panic
happened at the top - both may be used to navigate non-reactively back to the
homepage.
"</p>
<p>"
Navigating back after using the non-reactive links will also restart the application,
so using that immediately after to return to this page will once again trigger the
same condition that will result the hydration to panic. If you wish to maintain the
push state within the history, simply use the browser navigation to navigate through
those pushed addresses and find one that may be reloaded without causing the crash,
and then go the opposite direction the same number of steps to get back to here.
"</p>"
"</details>"
"</li>
<li>"
In the working CSR state, if you continue to use the browser's navigation system to go back to
home and forward back to this page, you will find that the the browser's console log is
spammed with the different delays added to the loading of the standard highlight.js file. The
cause is because the script is unloaded/reloaded every time its "<code>"<script>"</code>" tag
is re-created by this component. This may or may not be a desirable behavior, so where
exactly these tags are situated will matter - if the goal is to load the script once, the tag
should be provided above the Router.
"</li>
<li>"
Simply use the restart links to get back home and move onto the next example - or come back
here, if you wish - while all the examples can be used out of order, the intended broken
behaviors being demonstrated are best experienced by going home using the reactive link at the
top, and go back to the target example. Going between different examples demonstrating the
subtly broken behavior(s) in arbitrary order can and will amplify into further unexpected and
potentially hard to reproduce behaviors. What they are and why they happen are left as
exercise for the users and readers of this demo application.
"</li>
</ol>
<script src="/highlight.min.js"></script>
<script>"hljs.highlightAll();"</script>
}
}
#[component]
fn NaiveEvent(
#[prop(optional)] hook: bool,
#[prop(optional)] fallback: bool,
) -> impl IntoView {
let render_hook = "\
document.querySelector('#hljs-src')
.addEventListener('load', (e) => { hljs.highlightAll() }, false);";
let render_call = "\
if (window.hljs) {
hljs.highlightAll();
} else {
document.querySelector('#hljs-src')
.addEventListener('load', (e) => { hljs.highlightAll() }, false);
}";
let js_hook = if fallback { render_call } else { render_hook };
let explanation = if hook {
provide_context(CodeDemoHook {
js_hook: js_hook.to_string(),
});
if fallback {
view! {
<ol>
<li>"
In this iteration, the following load hook is set in a "<code>"<Script>"</code>"
component after the dynamically loaded code example."
<pre><code class="language-javascript">{js_hook}</code></pre>
</li>
<li><strong>CSR</strong>"
This works much better now under CSR due to the fallback that checks whether the
library is already loaded or not. Using the library directly if it's already loaded
and only register the event otherwise solves the rendering issue under CSR.
"</li>
<li><strong>SSR</strong>"
Much like the second example, hydration will still panic some of the time as per the
race condition that was described.
"</li>
</ol>
<p>"
All that being said, all these naive examples still result in hydration being
non-functional in varying degrees of (non-)reproducibility due to race conditions. Is
there any way to fix this? Is "<code>"wasm-bindgen"</code>" the only answer? What if the
goal is to incorporate external scripts that change often and thus can't easily have
bindings built? Follow onto the next examples to solve some of this, at the very least
prevent the panic during hydration.
"</p>
}.into_any()
} else {
view! {
<ol>
<li>"
In this iteration, the following load hook is set in a "<code>"<Script>"</code>"
component after the dynamically loaded code example."
<pre><code class="language-javascript">{js_hook}</code></pre>
</li>
<li><strong>CSR</strong>"
Unfortunately, this still doesn't work reliably to highlight both code examples, in
fact, none of the code examples may highlight at all! Placing the JavaScript loader
hook inside a "<code>Suspend</code>" will significantly increase the likelihood that
the event will be fired long before the loader adds the event hook. As a matter of
fact, the highlighting is likely to only work with the largest latencies added for
the loading of "<code>"highlight.js"</code>", but at least both code examples will
highlight when working.
"</li>
<li><strong>SSR</strong>"
Much like the second example, hydration will still panic some of the time as per the
race condition that was described - basically if the timing results in CSR not showing
highlight code, the code will highlight here in SSR but will panic during hydration.
"</li>
</ol>
}.into_any()
}
} else {
view! {
<ol>
<li>"
In this iteration, the following hook is set in a "<code>"<Script>"</code>" component
immediately following the one that loaded "<code>"highlight.js"</code>".
"<pre><code class="language-javascript">{js_hook}</code></pre>
</li>
<li><strong>CSR</strong>"
Unfortunately, the hook is being set directly on this component, rather than inside the
view for the dynamic block. Given the nature of asynchronous loading which results in the
uncertainty of the order of events, it may or may not result in the dynamic code block (or
any) being highlighted under CSR (as there may or may not be a fully formed code block for
highlighting to happen). This is affected by latency, so the loader here emulates a small
number of latency values (they repeat in a cycle). The latency value is logged into the
console and it may be referred to witness its effects on what it does under CSR - look for
the line that might say \"loaded standard highlight.js with a minimum latency of 40 ms\".
Test this by going from home to here and then navigating between them using the browser's
back and forward feature for convenience - do ensure the "<code>"highlight.js" </code>"
isn't being cached by the browser.
"</li>
<li><strong>SSR</strong>"
Moreover, hydration will panic if the highlight script is loaded before hydration is
completed (from the resulting DOM mismatch after code highlighting). Refreshing here
repeatedly may trigger the panic only some of the time when the "<code>"highlight.js"
</code>" script is loaded under the lowest amounts of artificial delay, as even under no
latency the hydration can still succeed due to the non-deterministic nature of this race
condition.
"</li>
</ol>
}.into_any()
};
// FIXME Seems like <Script> require a text node, otherwise hydration error from marker mismatch
view! {
<h2>"Using the Leptos "<code>"<Script>"</code>" component asynchronously instead"</h2>
<CodeDemo/>
<Script id="hljs-src" async_="true" src="/highlight.min.js">""</Script>
// Example 2's <Script> invocation; Example 3 and 4 will be provided via a context to allow the
// inclusion of the `highlightAll()` call in the Suspend
{(!hook).then(|| view! { <Script>{render_hook}</Script>})}
<p>"
What the "<code>"<Script>"</code>" component does is to ensure the "<code>"<script>"</code>" tag
is placed in the document head in the order it is defined in a given component, rather than at
where it was placed into the DOM. Note that it is also a reactive component, much like the first
example, it gets unloaded under CSR when the component is no longer active, In this improved
version, "<code>"highlight.js"</code>" is also loaded asynchronously (using the "<code>"async"
</code>" attribute), to allow an event listener that can delay highlighting to after the library
is loaded. This should all work out fine, right?
"</p>
{explanation}
}
}
#[component]
fn CustomEvent() -> impl IntoView {
let js_hook = format!(
"\
var events = [];
if (!window.hljs) {{
console.log('pushing listener for hljs load');
events.push(new Promise((r) =>
document.querySelector('#hljs-src').addEventListener('load', r, \
false)));
}}
if (!window.{LEPTOS_HYDRATED}) {{
console.log('pushing listener for leptos hydration');
events.push(new Promise((r) => \
document.addEventListener('{LEPTOS_HYDRATED}', r, false)));
}}
Promise.all(events).then(() => {{
console.log(`${{events.length}} events have been dispatched; now calling \
highlightAll()`);
hljs.highlightAll();
}});
"
);
provide_context(CodeDemoHook {
js_hook: js_hook.clone(),
});
// FIXME Seems like <Script> require a text node, otherwise hydration error from marker mismatch
view! {
<h2>"Have Leptos dispatch an event when body is hydrated"</h2>
<CodeDemo/>
<Script id="hljs-src" async_="true" src="/highlight.min.js">""</Script>
<p>"
So if using events fixes problems with timing issues, couldn't Leptos provide an event to signal
that the body is hydrated? Well, this problem is typically solved by having a signal in the
component, and then inside the "<code>"Suspend"</code>" provide an "<code>"Effect"</code>" that
would set the signal to "<code>"Some"</code>" string that will then mount the "<code>"<Script>"
</code>" onto the body. However, if a hydrated event is desired from within JavaScript (e.g.
where some existing JavaScript library/framework is managing event listeners for some particular
reason), given that typical Leptos applications provide the "<code>"fn hydate()"</code>" (usually
in "<code>" lib.rs"</code>"), that can be achieved by providing the following after "<code>
"leptos::mount::hydrate_body(App);"</code>".
"</p>
<div><pre><code class="language-rust">{format!(r#"#[cfg(feature = "hydrate")]
#[wasm_bindgen::prelude::wasm_bindgen]
pub fn hydrate() {{
use app::App;
// ... other calls omitted, as this example is only a rough
// reproduction of what is actually executed.
leptos::mount::hydrate_body(App);
// Now hydrate_body is done, provide ways to inform that
let window = leptos::prelude::window();
// first set a flag to signal that hydration has happened and other
// JavaScript code may just run without waiting for the event that
// is just about to be dispatched, as the event is only a one-time
// deal but this lives on as a variable that can be checked.
js_sys::Reflect::set(
&window,
&wasm_bindgen::JsValue::from_str({LEPTOS_HYDRATED:?}),
&wasm_bindgen::JsValue::TRUE,
).expect("error setting hydrated status");
// Then dispatch the event for all the listeners that were added.
let event = web_sys::Event::new({LEPTOS_HYDRATED:?})
.expect("error creating hydrated event");
let document = leptos::prelude::document();
document.dispatch_event(&event)
.expect("error dispatching hydrated event");
}}"#
)}</code></pre></div>
<p>"
With the notification that hydration is completed, the following JavaScript code may be called
inside "<code>"Suspense"</code>" block (in this live example, it's triggered by providing the
following JavaScript code via a "<code>"provide_context"</code>" which the code rendering
component will then use within a "<code>"Suspend"</code>"):
"</p>
<div><pre><code class="language-javascript">{js_hook}</code></pre></div>
<p>"
For this simple example with a single "<code>"Suspense"</code>", no matter what latency there is,
in whichever order the API calls are completed, the setup ensures that "<code>"highlightAll()"
</code>" is called only after hydration is done and also after the delayed content is properly
rendered onto the DOM. Specifically, only use the event to wait for the required resource if it
is not set to a ready state, and wait for all the events to become ready before actually calling
the function.
"</p>
<p>"
If there are multiple "<code>"Suspense"</code>", it will be a matter of adding all the event
listeners that will respond to the completion of all the "<code>"Suspend"</code>"ed futures, which
will then invoke the code highlighting function.
"</p>
// Leaving this last bit as a bonus page? As an exercise for the readers?
}
}
#[component]
fn CodeDemoSignalEffect() -> impl IntoView {
// Full JS without the use of hydration event
// this version will unset hljs if hljs was available to throw a wrench into
// the works, but it should still just work.
let render_call = r#"
if (window.hljs) {
hljs.highlightAll();
console.log('unloading hljs to try to force the need for addEventListener for next time');
window['hljs'] = undefined;
} else {
document.querySelector('#hljs-src')
.addEventListener('load', (e) => {
hljs.highlightAll();
console.log('using hljs inside addEventListener; leaving hljs loaded');
}, false);
};"#;
let code = Resource::new(|| (), |_| fetch_code());
let (script, set_script) = signal(None::<String>);
let code_view = move || {
Suspend::new(async move {
Effect::new(move |_| {
set_script.set(Some(render_call.to_string()));
});
view! {
<pre><code class="language-rust">{code.await}</code></pre>
<ShowLet some=script let:script>
<Script>{script}</Script>
</ShowLet>
}
})
};
view! {
<Script id="hljs-src" async_="true" src="/highlight.min.js">""</Script>
<h2>"Using signal + effect to dynamically set "<code>"<Script>"</code>" tag as view is mounted"</h2>
<p>"Explanation on what is being demonstrated follows after the following code example table."</p>
<div id="code-demo">
<table>
<thead>
<tr>
<th>"Inline code block (part of this component)"</th>
<th>"Dynamic code block (loaded via server fn)"</th>
</tr>
</thead>
<tbody>
<tr>
<td><pre><code class="language-rust">{CH03_05A}</code></pre></td>
<td>
<Suspense fallback=move || view! { <p>"Loading code example..."</p> }>
{code_view}
</Suspense>
</td>
</tr>
</tbody>
</table>
</div>
<p>"
To properly ensure the "<code>"<Script>"</code>" tag containing the initialization code for the
target JavaScript usage is executed after the "<code>"Suspend"</code>"ed view is fully rendered
and mounted onto the DOM, with the use of an effect that sets a signal to trigger the rendering
inside the suspend will achieve exactly that. That was a mouthful, so let's look at the code
for that then:
"</p>
<div><pre><code class="language-rust">r##"#[component]
fn CodeDemoSignalEffect() -> impl IntoView {
let render_call = r#"
if (window.hljs) {
hljs.highlightAll();
} else {
document.querySelector('#hljs-src')
.addEventListener('load', (e) => { hljs.highlightAll() }, false);
};"#;
let code = Resource::new(|| (), |_| fetch_code());
let (script, set_script) = signal(None::<String>);
let code_view = move || {
Suspend::new(async move {
Effect::new(move |_| {
set_script.set(Some(render_call.to_string()));
});
view! {
<pre><code class="language-rust">{code.await}</code></pre>
<ShowLet some=script let:script>
<Script>{script}</Script>
</ShowLet>
}
})
};
view! {
<Script id="hljs-src" async_="true" src="/highlight.min.js">""</Script>
<Suspense fallback=move || view! { <p>"Loading code example..."</p> }>
{code_view}
</Suspense>
}
}"##</code></pre></div>
<p>"
The "<code>"Suspend"</code>" ensures the asynchronous "<code>"Resource"</code>" will be completed
before the view is returned, which will be mounted onto the DOM, but the initial value of the
signal "<code>"script"</code>" will be "<code>"None"</code>", so no "<code>"<Script>"</code>" tag
will be rendered at that stage. Only after the suspended view is mounted onto the DOM the "<code>
"Effect"</code>" will run, which will call "<code>"set_script"</code>" with "<code>"Some"</code>"
value which will finally populate the "<code>"<Script>"</code>" tag with the desired JavaScript to
be executed, in this case invoke the code highlighting feature if available otherwise wait for it.
"</p>
<p>"
If there are multiple "<code>"Suspense"</code>", it will be a matter of adding the event to be
dispatched to "<code>"set_script.set"</code>" so that it gets dispatched for the component, and
then elsewhere above all those components a JavaScript list will tracking all the events will be
waited on by "<code>"Promise.all"</code>", where its completion will finally invoke the desired
JavaScript function.
"</p>
}
}
enum WasmDemo {
Naive,
ReadyEvent,
RequestAnimationFrame,
}
#[component]
fn CodeDemoWasm(mode: WasmDemo) -> impl IntoView {
let code = Resource::new(|| (), |_| fetch_code());
let suspense_choice = match mode {
WasmDemo::Naive => view! {
<Suspense fallback=move || view! { <p>"Loading code example..."</p> }>{
move || Suspend::new(async move {
view! {
<pre><code class="language-rust">{code.await}</code></pre>
{
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | true |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/axum_js_ssr/src/consts.rs | examples/axum_js_ssr/src/consts.rs | // Example programs from the Rust Programming Language Book
pub const CH03_05A: &str = r#"fn main() {
let number = 3;
if number < 5 {
println!("condition was true");
} else {
println!("condition was false");
}
}
"#;
// For some reason, swapping the code examples "fixes" example 6. It
// might have something to do with the lower complexity of highlighting
// a shorter example. Anyway, including extra newlines for the shorter
// example to match with the longer in order to avoid reflowing the
// table during the async resource loading for CSR.
pub const CH05_02A: &str = r#"fn main() {
let width1 = 30;
let height1 = 50;
println!(
"The area of the rectangle is {} square pixels.",
area(width1, height1)
);
}
fn area(width: u32, height: u32) -> u32 {
width * height
}
"#;
pub const LEPTOS_HYDRATED: &str = "_leptos_hydrated";
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/axum_js_ssr/src/hljs.rs | examples/axum_js_ssr/src/hljs.rs | #[cfg(not(feature = "ssr"))]
mod csr {
use gloo_utils::format::JsValueSerdeExt;
use js_sys::{
Object,
Reflect::{get, set},
};
use wasm_bindgen::{prelude::wasm_bindgen, JsValue};
#[wasm_bindgen(
module = "/node_modules/@highlightjs/cdn-assets/es/highlight.min.js"
)]
extern "C" {
type HighlightOptions;
#[wasm_bindgen(catch, js_namespace = defaultMod, js_name = highlight)]
fn highlight_lang(
code: String,
options: Object,
) -> Result<Object, JsValue>;
#[wasm_bindgen(js_namespace = defaultMod, js_name = highlightAll)]
pub fn highlight_all();
}
// Keeping the `ignoreIllegals` argument out of the default case, and since there is no optional arguments
// in Rust, this will have to be provided in a separate function (e.g. `highlight_ignore_illegals`), much
// like how `web_sys` does it for the browser APIs. For simplicity, only the highlighted HTML code is
// returned on success, and None on error.
pub fn highlight(code: String, lang: String) -> Option<String> {
let options = js_sys::Object::new();
set(&options, &"language".into(), &lang.into())
.expect("failed to assign lang to options");
highlight_lang(code, options)
.map(|result| {
let value = get(&result, &"value".into())
.expect("HighlightResult failed to contain the value key");
value.into_serde().expect("Value should have been a string")
})
.ok()
}
}
#[cfg(feature = "ssr")]
mod ssr {
// noop under ssr
pub fn highlight_all() {}
// TODO see if there is a Rust-based solution that will enable isomorphic rendering for this feature.
// the current (disabled) implementation simply calls html_escape.
// pub fn highlight(code: String, _lang: String) -> Option<String> {
// Some(html_escape::encode_text(&code).into_owned())
// }
}
#[cfg(not(feature = "ssr"))]
pub use csr::*;
#[cfg(feature = "ssr")]
pub use ssr::*;
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/axum_js_ssr/src/lib.rs | examples/axum_js_ssr/src/lib.rs | pub mod api;
pub mod app;
pub mod consts;
pub mod hljs;
#[cfg(feature = "hydrate")]
#[wasm_bindgen::prelude::wasm_bindgen]
pub fn hydrate() {
use app::*;
use consts::LEPTOS_HYDRATED;
use std::panic;
panic::set_hook(Box::new(|info| {
// this custom hook will call out to show the usual error log at
// the console while also attempt to update the UI to indicate
// a restart of the application is required to continue.
console_error_panic_hook::hook(info);
let window = leptos::prelude::window();
if !matches!(
js_sys::Reflect::get(&window, &wasm_bindgen::JsValue::from_str(LEPTOS_HYDRATED)),
Ok(t) if t == true
) {
let document = leptos::prelude::document();
let _ = document.query_selector("#reset").map(|el| {
el.map(|el| {
el.set_class_name("panicked");
})
});
let _ = document.query_selector("#notice").map(|el| {
el.map(|el| {
el.set_class_name("panicked");
})
});
}
}));
leptos::mount::hydrate_body(App);
let window = leptos::prelude::window();
js_sys::Reflect::set(
&window,
&wasm_bindgen::JsValue::from_str(LEPTOS_HYDRATED),
&wasm_bindgen::JsValue::TRUE,
)
.expect("error setting hydrated status");
let event = web_sys::Event::new(LEPTOS_HYDRATED)
.expect("error creating hydrated event");
let document = leptos::prelude::document();
document
.dispatch_event(&event)
.expect("error dispatching hydrated event");
leptos::logging::log!("dispatched hydrated event");
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/axum_js_ssr/src/api.rs | examples/axum_js_ssr/src/api.rs | use leptos::{prelude::ServerFnError, server};
#[server]
pub async fn fetch_code() -> Result<String, ServerFnError> {
// emulate loading of code from a database/version control/etc
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
Ok(crate::consts::CH05_02A.to_string())
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/axum_js_ssr/src/main.rs | examples/axum_js_ssr/src/main.rs | #[cfg(feature = "ssr")]
mod latency {
use std::sync::{Mutex, OnceLock};
pub static LATENCY: OnceLock<
Mutex<std::iter::Cycle<std::slice::Iter<'_, u64>>>,
> = OnceLock::new();
pub static ES_LATENCY: OnceLock<
Mutex<std::iter::Cycle<std::slice::Iter<'_, u64>>>,
> = OnceLock::new();
}
#[cfg(feature = "ssr")]
#[tokio::main]
async fn main() {
use axum::{
body::Body,
extract::Request,
http::{
header::{self, HeaderValue},
StatusCode,
},
middleware::{self, Next},
response::{IntoResponse, Response},
routing::get,
Router,
};
use axum_js_ssr::app::*;
use http_body_util::BodyExt;
use leptos::{logging::log, prelude::*};
use leptos_axum::{generate_route_list, LeptosRoutes};
latency::LATENCY.get_or_init(|| [0, 4, 40, 400].iter().cycle().into());
latency::ES_LATENCY.get_or_init(|| [0].iter().cycle().into());
// Having the ES_LATENCY (a cycle of latency for the loading of the es
// module) in an identical cycle as LATENCY (for the standard version)
// adversely influences the intended demo, as this ultimately delays
// hydration when set too high which can cause panic under every case.
// If you want to test the effects of the delay just modify the list of
// values for the desired cycle of delays.
let conf = get_configuration(None).unwrap();
let addr = conf.leptos_options.site_addr;
let leptos_options = conf.leptos_options;
// Generate the list of routes in your Leptos App
let routes = generate_route_list(App);
async fn highlight_js() -> impl IntoResponse {
(
[(header::CONTENT_TYPE, "text/javascript")],
include_str!(
"../node_modules/@highlightjs/cdn-assets/highlight.min.js"
),
)
}
async fn latency_for_highlight_js(
req: Request,
next: Next,
) -> Result<impl IntoResponse, (StatusCode, String)> {
let uri_parts = &mut req.uri().path().rsplit('/');
let is_highlightjs = uri_parts.next() == Some("highlight.min.js");
let es = uri_parts.next() == Some("es");
let module_type = if es { "es module " } else { "standard " };
let res = next.run(req).await;
if is_highlightjs {
// additional processing if the filename is the test subject
let (mut parts, body) = res.into_parts();
let bytes = body
.collect()
.await
.map_err(|err| {
(
StatusCode::BAD_REQUEST,
format!("error reading body: {err}"),
)
})?
.to_bytes();
let latency = if es {
&latency::ES_LATENCY
} else {
&latency::LATENCY
};
let delay = match latency
.get()
.expect("latency cycle wasn't set up")
.try_lock()
{
Ok(ref mut mutex) => {
*mutex.next().expect("cycle always has next")
}
Err(_) => 0,
};
// inject the logging of the delay used into the target script
log!(
"loading {module_type}highlight.min.js with latency of \
{delay} ms"
);
let js_log = format!(
"\nconsole.log('loaded {module_type}highlight.js with a \
minimum latency of {delay} ms');"
);
tokio::time::sleep(std::time::Duration::from_millis(delay)).await;
let bytes = [bytes, js_log.into()].concat();
let length = bytes.len();
let body = Body::from(bytes);
// Provide the bare minimum set of headers to avoid browser cache.
parts.headers = header::HeaderMap::from_iter(
[
(
header::CONTENT_TYPE,
HeaderValue::from_static("text/javascript"),
),
(header::CONTENT_LENGTH, HeaderValue::from(length)),
]
.into_iter(),
);
Ok(Response::from_parts(parts, body))
} else {
Ok(res)
}
}
let app = Router::new()
.route("/highlight.min.js", get(highlight_js))
.leptos_routes(&leptos_options, routes, {
let leptos_options = leptos_options.clone();
move || shell(leptos_options.clone())
})
.fallback(leptos_axum::file_and_error_handler(shell))
.layer(middleware::from_fn(latency_for_highlight_js))
.with_state(leptos_options);
// run our app with hyper
// `axum::Server` is a re-export of `hyper::Server`
log!("listening on http://{}", &addr);
let listener = tokio::net::TcpListener::bind(&addr).await.unwrap();
axum::serve(listener, app.into_make_service())
.await
.unwrap();
}
#[cfg(not(feature = "ssr"))]
pub fn main() {
// no client-side main function
// unless we want this to work with e.g., Trunk for pure client-side testing
// see lib.rs for hydration function instead
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/todo_app_sqlite/src/lib.rs | examples/todo_app_sqlite/src/lib.rs | pub mod todo;
#[cfg(feature = "hydrate")]
#[wasm_bindgen::prelude::wasm_bindgen]
pub fn hydrate() {
use crate::todo::*;
console_error_panic_hook::set_once();
_ = console_log::init_with_level(log::Level::Debug);
leptos::mount::hydrate_body(TodoApp);
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/todo_app_sqlite/src/todo.rs | examples/todo_app_sqlite/src/todo.rs | use leptos::{either::Either, prelude::*};
use serde::{Deserialize, Serialize};
use server_fn::ServerFnError;
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ssr", derive(sqlx::FromRow))]
pub struct Todo {
id: u16,
title: String,
completed: bool,
}
#[cfg(feature = "ssr")]
pub mod ssr {
// use http::{header::SET_COOKIE, HeaderMap, HeaderValue, StatusCode};
use leptos::server_fn::ServerFnError;
use sqlx::{Connection, SqliteConnection};
pub async fn db() -> Result<SqliteConnection, ServerFnError> {
Ok(SqliteConnection::connect("sqlite:Todos.db").await?)
}
}
#[server]
pub async fn get_todos() -> Result<Vec<Todo>, ServerFnError> {
use self::ssr::*;
// this is just an example of how to access server context injected in the handlers
let req_parts = use_context::<leptos_actix::Request>();
if let Some(req_parts) = req_parts {
println!("Path = {:?}", req_parts.path());
}
use futures::TryStreamExt;
let mut conn = db().await?;
let mut todos = Vec::new();
let mut rows =
sqlx::query_as::<_, Todo>("SELECT * FROM todos").fetch(&mut conn);
while let Some(row) = rows.try_next().await? {
todos.push(row);
}
// Lines below show how to set status code and headers on the response
// let resp = expect_context::<ResponseOptions>();
// resp.set_status(StatusCode::IM_A_TEAPOT);
// resp.insert_header(SET_COOKIE, HeaderValue::from_str("fizz=buzz").unwrap());
Ok(todos)
}
#[server]
pub async fn add_todo(title: String) -> Result<(), ServerFnError> {
use self::ssr::*;
let mut conn = db().await?;
// fake API delay
std::thread::sleep(std::time::Duration::from_millis(250));
match sqlx::query("INSERT INTO todos (title, completed) VALUES ($1, false)")
.bind(title)
.execute(&mut conn)
.await
{
Ok(_row) => Ok(()),
Err(e) => Err(ServerFnError::ServerError(e.to_string())),
}
}
#[server]
pub async fn delete_todo(id: u16) -> Result<(), ServerFnError> {
use self::ssr::*;
let mut conn = db().await?;
Ok(sqlx::query("DELETE FROM todos WHERE id = $1")
.bind(id)
.execute(&mut conn)
.await
.map(|_| ())?)
}
#[component]
pub fn TodoApp() -> impl IntoView {
view! {
<header>
<h1>"My Tasks"</h1>
</header>
<main>
<Todos/>
</main>
}
}
#[component]
pub fn Todos() -> impl IntoView {
let add_todo = ServerMultiAction::<AddTodo>::new();
let submissions = add_todo.submissions();
let delete_todo = ServerAction::<DeleteTodo>::new();
// list of todos is loaded from the server in reaction to changes
let todos = Resource::new(
move || {
(
delete_todo.version().get(),
add_todo.version().get(),
delete_todo.version().get(),
)
},
move |_| get_todos(),
);
let existing_todos = move || {
Suspend::new(async move {
todos
.await
.map(|todos| {
if todos.is_empty() {
Either::Left(view! { <p>"No tasks were found."</p> })
} else {
Either::Right(
todos
.iter()
.map(move |todo| {
let id = todo.id;
view! {
<li>
{todo.title.clone()} <ActionForm action=delete_todo>
<input type="hidden" name="id" value=id/>
<input type="submit" value="X"/>
</ActionForm>
</li>
}
})
.collect::<Vec<_>>(),
)
}
})
})
};
view! {
<MultiActionForm action=add_todo>
<label>"Add a Todo" <input type="text" name="title"/></label>
<input type="submit" value="Add"/>
</MultiActionForm>
<div>
<Transition fallback=move || view! { <p>"Loading..."</p> }>
// TODO: ErrorBoundary here seems to break Suspense in Actix
// <ErrorBoundary fallback=|errors| view! { <p>"Error: " {move || format!("{:?}", errors.get())}</p> }>
<ul>
{existing_todos}
{move || {
submissions
.get()
.into_iter()
.filter(|submission| submission.pending().get())
.map(|submission| {
view! {
<li class="pending">
{move || submission.input().get().map(|data| data.title)}
</li>
}
})
.collect::<Vec<_>>()
}}
</ul>
// </ErrorBoundary>
</Transition>
</div>
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/todo_app_sqlite/src/main.rs | examples/todo_app_sqlite/src/main.rs | mod todo;
#[cfg(feature = "ssr")]
mod ssr {
pub use crate::todo::*;
pub use actix_files::Files;
pub use actix_web::*;
pub use leptos::prelude::*;
pub use leptos_actix::{generate_route_list, LeptosRoutes};
#[get("/style.css")]
pub async fn css() -> impl Responder {
actix_files::NamedFile::open_async("./style.css").await
}
}
#[cfg(feature = "ssr")]
#[actix_web::main]
async fn main() -> std::io::Result<()> {
use self::{ssr::*, todo::ssr::*};
let mut conn = db().await.expect("couldn't connect to DB");
sqlx::migrate!()
.run(&mut conn)
.await
.expect("could not run SQLx migrations");
let conf = get_configuration(None).unwrap();
let addr = conf.leptos_options.site_addr;
println!("listening on http://{}", &addr);
HttpServer::new(move || {
// Generate the list of routes in your Leptos App
let routes = generate_route_list(TodoApp);
let leptos_options = &conf.leptos_options;
let site_root = &leptos_options.site_root;
App::new()
.leptos_routes(routes, {
let leptos_options = leptos_options.clone();
move || {
use leptos::prelude::*;
view! {
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta
name="viewport"
content="width=device-width, initial-scale=1"
/>
<AutoReload options=leptos_options.clone()/>
<HydrationScripts options=leptos_options.clone()/>
</head>
<body>
<TodoApp/>
</body>
</html>
}
}})
.service(Files::new("/", site_root.as_ref()))
//.wrap(middleware::Compress::default())
})
.bind(&addr)?
.run()
.await
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/todo_app_sqlite/e2e/tests/app_suite.rs | examples/todo_app_sqlite/e2e/tests/app_suite.rs | mod fixtures;
use anyhow::Result;
use cucumber::World;
use fixtures::world::AppWorld;
#[tokio::main]
async fn main() -> Result<()> {
AppWorld::cucumber()
.fail_on_skipped()
.run_and_exit("./features")
.await;
Ok(())
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/todo_app_sqlite/e2e/tests/fixtures/check.rs | examples/todo_app_sqlite/e2e/tests/fixtures/check.rs | use super::find;
use anyhow::{Ok, Result};
use fantoccini::{Client, Locator};
use pretty_assertions::assert_eq;
pub async fn text_on_element(
client: &Client,
selector: &str,
expected_text: &str,
) -> Result<()> {
let element = client
.wait()
.for_element(Locator::Css(selector))
.await
.expect(
format!("Element not found by Css selector `{}`", selector)
.as_str(),
);
let actual = element.text().await?;
assert_eq!(&actual, expected_text);
Ok(())
}
pub async fn todo_present(
client: &Client,
text: &str,
expected: bool,
) -> Result<()> {
let todo_present = is_todo_present(client, text).await;
assert_eq!(todo_present, expected);
Ok(())
}
async fn is_todo_present(client: &Client, text: &str) -> bool {
let todos = find::todos(client).await;
for todo in todos {
let todo_title = todo.text().await.expect("Todo title not found");
if todo_title == text {
return true;
}
}
false
}
pub async fn todo_is_pending(client: &Client) -> Result<()> {
if let None = find::pending_todo(client).await {
assert!(false, "Pending todo not found");
}
Ok(())
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/todo_app_sqlite/e2e/tests/fixtures/find.rs | examples/todo_app_sqlite/e2e/tests/fixtures/find.rs | use fantoccini::{elements::Element, Client, Locator};
pub async fn todo_input(client: &Client) -> Element {
let textbox = client
.wait()
.for_element(Locator::Css("input[name='title"))
.await
.expect("Todo textbox not found");
textbox
}
pub async fn add_button(client: &Client) -> Element {
let button = client
.wait()
.for_element(Locator::Css("input[value='Add']"))
.await
.expect("");
button
}
pub async fn first_delete_button(client: &Client) -> Option<Element> {
if let Ok(element) = client
.wait()
.for_element(Locator::Css("li:first-child input[value='X']"))
.await
{
return Some(element);
}
None
}
pub async fn delete_button(client: &Client, text: &str) -> Option<Element> {
let selector = format!("//*[text()='{text}']//input[@value='X']");
if let Ok(element) =
client.wait().for_element(Locator::XPath(&selector)).await
{
return Some(element);
}
None
}
pub async fn pending_todo(client: &Client) -> Option<Element> {
if let Ok(element) =
client.wait().for_element(Locator::Css(".pending")).await
{
return Some(element);
}
None
}
pub async fn todos(client: &Client) -> Vec<Element> {
let todos = client
.find_all(Locator::Css("li"))
.await
.expect("Todo List not found");
todos
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/todo_app_sqlite/e2e/tests/fixtures/mod.rs | examples/todo_app_sqlite/e2e/tests/fixtures/mod.rs | pub mod action;
pub mod check;
pub mod find;
pub mod world;
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/todo_app_sqlite/e2e/tests/fixtures/action.rs | examples/todo_app_sqlite/e2e/tests/fixtures/action.rs | use super::{find, world::HOST};
use anyhow::Result;
use fantoccini::Client;
use std::result::Result::Ok;
use tokio::{self, time};
pub async fn goto_path(client: &Client, path: &str) -> Result<()> {
let url = format!("{}{}", HOST, path);
client.goto(&url).await?;
Ok(())
}
pub async fn add_todo(client: &Client, text: &str) -> Result<()> {
fill_todo(client, text).await?;
click_add_button(client).await?;
Ok(())
}
pub async fn fill_todo(client: &Client, text: &str) -> Result<()> {
let textbox = find::todo_input(client).await;
textbox.send_keys(text).await?;
Ok(())
}
pub async fn click_add_button(client: &Client) -> Result<()> {
let add_button = find::add_button(client).await;
add_button.click().await?;
Ok(())
}
pub async fn empty_todo_list(client: &Client) -> Result<()> {
let todos = find::todos(client).await;
for _todo in todos {
let _ = delete_first_todo(client).await?;
}
Ok(())
}
pub async fn delete_first_todo(client: &Client) -> Result<()> {
if let Some(element) = find::first_delete_button(client).await {
element.click().await.expect("Failed to delete todo");
time::sleep(time::Duration::from_millis(250)).await;
}
Ok(())
}
pub async fn delete_todo(client: &Client, text: &str) -> Result<()> {
if let Some(element) = find::delete_button(client, text).await {
element.click().await?;
time::sleep(time::Duration::from_millis(250)).await;
}
Ok(())
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/todo_app_sqlite/e2e/tests/fixtures/world/check_steps.rs | examples/todo_app_sqlite/e2e/tests/fixtures/world/check_steps.rs | use crate::fixtures::{check, world::AppWorld};
use anyhow::{Ok, Result};
use cucumber::then;
#[then(regex = "^I see the page title is (.*)$")]
async fn i_see_the_page_title_is(
world: &mut AppWorld,
text: String,
) -> Result<()> {
let client = &world.client;
check::text_on_element(client, "h1", &text).await?;
Ok(())
}
#[then(regex = "^I see the label of the input is (.*)$")]
async fn i_see_the_label_of_the_input_is(
world: &mut AppWorld,
text: String,
) -> Result<()> {
let client = &world.client;
check::text_on_element(client, "label", &text).await?;
Ok(())
}
#[then(regex = "^I see the todo named (.*)$")]
async fn i_see_the_todo_is_present(
world: &mut AppWorld,
text: String,
) -> Result<()> {
let client = &world.client;
check::todo_present(client, text.as_str(), true).await?;
Ok(())
}
#[then("I see the pending todo")]
async fn i_see_the_pending_todo(world: &mut AppWorld) -> Result<()> {
let client = &world.client;
check::todo_is_pending(client).await?;
Ok(())
}
#[then(regex = "^I see the empty list message is (.*)$")]
async fn i_see_the_empty_list_message_is(
world: &mut AppWorld,
text: String,
) -> Result<()> {
let client = &world.client;
check::text_on_element(client, "ul p", &text).await?;
Ok(())
}
#[then(regex = "^I do not see the todo named (.*)$")]
async fn i_do_not_see_the_todo_is_present(
world: &mut AppWorld,
text: String,
) -> Result<()> {
let client = &world.client;
check::todo_present(client, text.as_str(), false).await?;
Ok(())
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/todo_app_sqlite/e2e/tests/fixtures/world/action_steps.rs | examples/todo_app_sqlite/e2e/tests/fixtures/world/action_steps.rs | use crate::fixtures::{action, world::AppWorld};
use anyhow::{Ok, Result};
use cucumber::{given, when};
#[given("I see the app")]
#[when("I open the app")]
async fn i_open_the_app(world: &mut AppWorld) -> Result<()> {
let client = &world.client;
action::goto_path(client, "").await?;
Ok(())
}
#[given(regex = "^I add a todo as (.*)$")]
#[when(regex = "^I add a todo as (.*)$")]
async fn i_add_a_todo_titled(world: &mut AppWorld, text: String) -> Result<()> {
let client = &world.client;
action::add_todo(client, text.as_str()).await?;
Ok(())
}
#[given(regex = "^I set the todo as (.*)$")]
async fn i_set_the_todo_as(world: &mut AppWorld, text: String) -> Result<()> {
let client = &world.client;
action::fill_todo(client, &text).await?;
Ok(())
}
#[when(regex = "I click the Add button$")]
async fn i_click_the_button(world: &mut AppWorld) -> Result<()> {
let client = &world.client;
action::click_add_button(client).await?;
Ok(())
}
#[when(regex = "^I delete the todo named (.*)$")]
async fn i_delete_the_todo_named(
world: &mut AppWorld,
text: String,
) -> Result<()> {
let client = &world.client;
action::delete_todo(client, text.as_str()).await?;
Ok(())
}
#[given("the todo list is empty")]
#[when("I empty the todo list")]
async fn i_empty_the_todo_list(world: &mut AppWorld) -> Result<()> {
let client = &world.client;
action::empty_todo_list(client).await?;
Ok(())
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/todo_app_sqlite/e2e/tests/fixtures/world/mod.rs | examples/todo_app_sqlite/e2e/tests/fixtures/world/mod.rs | pub mod action_steps;
pub mod check_steps;
use anyhow::Result;
use cucumber::World;
use fantoccini::{
error::NewSessionError, wd::Capabilities, Client, ClientBuilder,
};
pub const HOST: &str = "http://127.0.0.1:3000";
#[derive(Debug, World)]
#[world(init = Self::new)]
pub struct AppWorld {
pub client: Client,
}
impl AppWorld {
async fn new() -> Result<Self, anyhow::Error> {
let webdriver_client = build_client().await?;
Ok(Self {
client: webdriver_client,
})
}
}
async fn build_client() -> Result<Client, NewSessionError> {
let mut cap = Capabilities::new();
let arg = serde_json::from_str("{\"args\": [\"-headless\"]}").unwrap();
cap.insert("goog:chromeOptions".to_string(), arg);
let client = ClientBuilder::native()
.capabilities(cap)
.connect("http://localhost:4444")
.await?;
Ok(client)
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/fetch/src/lib.rs | examples/fetch/src/lib.rs | use leptos::prelude::*;
use serde::{Deserialize, Serialize};
use thiserror::Error;
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Cat {
url: String,
}
#[derive(Error, Clone, Debug)]
pub enum CatError {
#[error("Please request more than zero cats.")]
NonZeroCats,
}
type CatCount = usize;
async fn fetch_cats(count: CatCount) -> Result<Vec<String>, Error> {
if count > 0 {
gloo_timers::future::TimeoutFuture::new(1000).await;
// make the request
let res = reqwasm::http::Request::get(&format!(
"https://api.thecatapi.com/v1/images/search?limit={count}",
))
.send()
.await?
// convert it to JSON
.json::<Vec<Cat>>()
.await?
// extract the URL field for each cat
.into_iter()
.take(count)
.map(|cat| cat.url)
.collect::<Vec<_>>();
Ok(res)
} else {
Err(CatError::NonZeroCats)?
}
}
pub fn fetch_example() -> impl IntoView {
let (cat_count, set_cat_count) = signal::<CatCount>(1);
let cats = LocalResource::new(move || fetch_cats(cat_count.get()));
let fallback = move |errors: ArcRwSignal<Errors>| {
let error_list = move || {
errors.with(|errors| {
errors
.iter()
.map(|(_, e)| view! { <li>{e.to_string()}</li> })
.collect::<Vec<_>>()
})
};
view! {
<div class="error">
<h2>"Error"</h2>
<ul>{error_list}</ul>
</div>
}
};
view! {
<div>
<label>
"How many cats would you like?"
<input
type="number"
prop:value=move || cat_count.get().to_string()
on:input:target=move |ev| {
let val = ev.target().value().parse::<CatCount>().unwrap_or(0);
set_cat_count.set(val);
}
/>
</label>
<Transition fallback=|| view! { <div>"Loading..."</div> }>
<ErrorBoundary fallback>
<ul>
{move || Suspend::new(async move {
cats.await
.map(|cats| {
cats.iter()
.map(|s| {
view! {
<li>
<img src=s.clone() />
</li>
}
})
.collect::<Vec<_>>()
})
})}
</ul>
</ErrorBoundary>
</Transition>
</div>
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/fetch/src/main.rs | examples/fetch/src/main.rs | use fetch::fetch_example;
use leptos::prelude::*;
pub fn main() {
use tracing_subscriber::fmt;
use tracing_subscriber_wasm::MakeConsoleWriter;
fmt()
.with_writer(
// To avoid trace events in the browser from showing their
// JS backtrace, which is very annoying, in my opinion
MakeConsoleWriter::default()
.map_trace_level_to(tracing::Level::DEBUG),
)
// For some reason, if we don't do this in the browser, we get
// a runtime error.
.without_time()
.init();
console_error_panic_hook::set_once();
mount_to_body(fetch_example)
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/ssr_modes/src/app.rs | examples/ssr_modes/src/app.rs | use leptos::prelude::*;
use leptos_meta::*;
use leptos_router::{
components::{FlatRoutes, Route, Router},
hooks::use_params,
params::Params,
ParamSegment, SsrMode, StaticSegment,
};
use serde::{Deserialize, Serialize};
use std::sync::LazyLock;
use thiserror::Error;
#[component]
pub fn App() -> impl IntoView {
// Provides context that manages stylesheets, titles, meta tags, etc.
provide_meta_context();
let fallback = || view! { "Page not found." }.into_view();
view! {
<Stylesheet id="leptos" href="/pkg/ssr_modes.css" />
<Title text="Welcome to Leptos" />
<Meta name="color-scheme" content="dark light" />
<Router>
<main>
<FlatRoutes fallback>
// We’ll load the home page with out-of-order streaming and <Suspense/>
<Route path=StaticSegment("") view=HomePage />
// We'll load the posts with async rendering, so they can set
// the title and metadata *after* loading the data
<Route
path=(StaticSegment("post"), ParamSegment("id"))
view=Post
ssr=SsrMode::Async
/>
<Route
path=(StaticSegment("post_in_order"), ParamSegment("id"))
view=Post
ssr=SsrMode::InOrder
/>
</FlatRoutes>
</main>
</Router>
}
}
#[component]
fn HomePage() -> impl IntoView {
// load the posts
let posts = Resource::new(|| (), |_| list_post_metadata());
let posts = move || {
posts
.get()
.map(|n| n.unwrap_or_default())
.unwrap_or_default()
};
let posts2 = Resource::new(|| (), |_| list_post_metadata());
let posts2 = Resource::new(
|| (),
move |_| async move { posts2.await.as_ref().map(Vec::len).unwrap_or(0) },
);
view! {
<h1>"My Great Blog"</h1>
<Suspense fallback=move || view! { <p>"Loading posts..."</p> }>
<p>"number of posts: " {Suspend::new(async move { posts2.await })}</p>
</Suspense>
<Suspense fallback=move || view! { <p>"Loading posts..."</p> }>
<ul>
<For each=posts key=|post| post.id let:post>
<li>
<a href=format!("/post/{}", post.id)>{post.title.clone()}</a>
"|"
<a href=format!("/post_in_order/{}", post.id)>{post.title} "(in order)"</a>
</li>
</For>
</ul>
</Suspense>
}
}
#[derive(Params, Copy, Clone, Debug, PartialEq, Eq)]
pub struct PostParams {
id: Option<usize>,
}
#[component]
fn Post() -> impl IntoView {
let query = use_params::<PostParams>();
let id = move || {
query.with(|q| {
q.as_ref()
.map(|q| q.id.unwrap_or_default())
.map_err(|_| PostError::InvalidId)
})
};
let post_resource = Resource::new(id, |id| async move {
match id {
Err(e) => Err(e),
Ok(id) => get_post(id)
.await
.map(|data| data.ok_or(PostError::PostNotFound))
.map_err(|_| PostError::ServerError),
}
});
let post_view = Suspend::new(async move {
match post_resource.await.to_owned() {
Ok(Ok(post)) => Ok(view! {
<h1>{post.title.clone()}</h1>
<p>{post.content.clone()}</p>
// since we're using async rendering for this page,
// this metadata should be included in the actual HTML <head>
// when it's first served
<Title text=post.title />
<Meta name="description" content=post.content />
}),
_ => Err(PostError::ServerError),
}
});
view! {
<em>"The world's best content."</em>
<Suspense fallback=move || view! { <p>"Loading post..."</p> }>
<ErrorBoundary fallback=|errors| {
view! {
<div class="error">
<h1>"Something went wrong."</h1>
<ul>
{move || {
errors
.get()
.into_iter()
.map(|(_, error)| view! { <li>{error.to_string()}</li> })
.collect::<Vec<_>>()
}}
</ul>
</div>
}
}>{post_view}</ErrorBoundary>
</Suspense>
}
}
// Dummy API
static POSTS: LazyLock<[Post; 3]> = LazyLock::new(|| {
[
Post {
id: 0,
title: "My first post".to_string(),
content: "This is my first post".to_string(),
},
Post {
id: 1,
title: "My second post".to_string(),
content: "This is my second post".to_string(),
},
Post {
id: 2,
title: "My third post".to_string(),
content: "This is my third post".to_string(),
},
]
});
#[derive(Error, Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum PostError {
#[error("Invalid post ID.")]
InvalidId,
#[error("Post not found.")]
PostNotFound,
#[error("Server error.")]
ServerError,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Post {
id: usize,
title: String,
content: String,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct PostMetadata {
id: usize,
title: String,
}
#[server]
pub async fn list_post_metadata() -> Result<Vec<PostMetadata>, ServerFnError> {
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
Ok(POSTS
.iter()
.map(|data| PostMetadata {
id: data.id,
title: data.title.clone(),
})
.collect())
}
#[server]
pub async fn get_post(id: usize) -> Result<Option<Post>, ServerFnError> {
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
Ok(POSTS.iter().find(|post| post.id == id).cloned())
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/ssr_modes/src/lib.rs | examples/ssr_modes/src/lib.rs | pub mod app;
#[cfg(feature = "hydrate")]
#[wasm_bindgen::prelude::wasm_bindgen]
pub fn hydrate() {
use app::*;
// initializes logging using the `log` crate
_ = console_log::init_with_level(log::Level::Debug);
console_error_panic_hook::set_once();
leptos::mount::hydrate_body(App);
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/ssr_modes/src/main.rs | examples/ssr_modes/src/main.rs | #[cfg(feature = "ssr")]
#[actix_web::main]
async fn main() -> std::io::Result<()> {
use actix_files::Files;
use actix_web::*;
use leptos::prelude::*;
use leptos_actix::{generate_route_list, LeptosRoutes};
use leptos_meta::MetaTags;
use ssr_modes::app::*;
let conf = get_configuration(None).unwrap();
let addr = conf.leptos_options.site_addr;
HttpServer::new(move || {
// Generate the list of routes in your Leptos App
let routes = generate_route_list(App);
let leptos_options = &conf.leptos_options;
let site_root = &leptos_options.site_root;
App::new()
.leptos_routes(routes, {
let leptos_options = leptos_options.clone();
move || {
use leptos::prelude::*;
view! {
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<AutoReload options=leptos_options.clone() />
<HydrationScripts options=leptos_options.clone()/>
<MetaTags/>
</head>
<body>
<App/>
</body>
</html>
}
}})
.service(Files::new("/", site_root.as_ref()))
//.wrap(middleware::Compress::default())
})
.bind(&addr)?
.run()
.await
}
#[cfg(not(feature = "ssr"))]
pub fn main() {
// no client-side main function
// unless we want this to work with e.g., Trunk for pure client-side testing
// see lib.rs for hydration function instead
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/spread/src/lib.rs | examples/spread/src/lib.rs | use leptos::prelude::*;
/// Demonstrates how attributes and event handlers can be spread onto elements.
#[component]
pub fn SpreadingExample() -> impl IntoView {
fn alert(msg: impl AsRef<str>) {
let _ = window().alert_with_message(msg.as_ref());
}
// you can easily create sets of spreadable attributes by using the <{..} ___/> syntax
// this is expanded to a tuple of attributes; it has no meaning on its own, but can be spread
// onto an HTML element or component
let attrs_only = view! { <{..} class="foo"/> };
let event_handlers_only = view! { <{..} on:click=move |_| {
alert("event_handlers_only clicked");
}/> };
let combined = view! { <{..} class="bar" on:click=move |_| alert("combined clicked") /> };
let partial_attrs =
view! { <{..} id="snood" class="baz" data-foo="bar" /> };
let partial_event_handlers = view! { <{..} on:click=move |_| alert("partial_event_handlers clicked") /> };
let spread_onto_component = view! {
<{..} aria-label="a component with attribute spreading"/>
};
/* with the correct imports, you can use a tuple/builder syntax as well
let attrs_only = class("foo");
let event_handlers_only = on(ev::click, move |_e: ev::MouseEvent| {
alert("event_handlers_only clicked");
});
let combined = (
class("bar"),
on(ev::click, move |_e: ev::MouseEvent| {
alert("combined clicked");
}),
);
let partial_attrs = (id("snood"), class("baz"));
let partial_event_handlers = on(ev::click, move |_e: ev::MouseEvent| {
alert("partial_event_handlers clicked");
});
*/
view! {
<p>
"You can spread any valid attribute, including a tuple of attributes, with the {..attr} syntax"
</p>
<div {..attrs_only.clone()}>"<div {..attrs_only} />"</div>
<div {..event_handlers_only.clone()}>"<div {..event_handlers_only} />"</div>
<div {..combined.clone()}>"<div {..combined} />"</div>
<div {..partial_attrs.clone()} {..partial_event_handlers.clone()}>
"<div {..partial_attrs} {..partial_event_handlers} />"
</div>
<hr/>
<p>
"The .. is not required to spread; you can pass any valid attribute in a block by itself."
</p>
<div {attrs_only}>"<div {attrs_only} />"</div>
<div {event_handlers_only}>"<div {event_handlers_only} />"</div>
<div {combined}>"<div {combined} />"</div>
<div {partial_attrs} {partial_event_handlers}>
"<div {partial_attrs} {partial_event_handlers} />"
</div>
<hr/>
// attributes that are spread onto a component will be applied to *all* elements returned as part of
// the component's view. to apply attributes to a subset of the component, pass them via a component prop
<ComponentThatTakesSpread
// the class:, style:, prop:, on: syntaxes work just as they do on elements
class:foo=true
style:font-weight="bold"
prop:cool=42
on:click=move |_| alert("clicked ComponentThatTakesSpread")
// props are passed as they usually are on components
some_prop=13
// to pass a plain HTML attribute, prefix it with attr:
attr:id="foo"
// or, if you want to include multiple attributes, rather than prefixing each with
// attr:, you can separate them from component props with the spread {..}
{..} // everything after this is treated as an HTML attribute
title="ooh, a title!"
{..spread_onto_component}
/>
}
// TODO check below
// Overwriting an event handler, here on:click, will result in a panic in debug builds. In release builds, the initial handler is kept.
// If spreading is used, prefer manually merging event handlers in the binding list instead.
//<div {..mixed} on:click=|_e| { alert("I will never be seen..."); }>
// "with overwritten click handler"
//</div>
}
#[component]
pub fn ComponentThatTakesSpread(some_prop: i32) -> impl IntoView {
leptos::logging::log!("some_prop = {some_prop}");
view! {
<button>"<ComponentThatTakesSpread/>"</button>
<p>
"Attributes applied to a component apply to all top-level elements returned by a component."
</p>
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/spread/src/main.rs | examples/spread/src/main.rs | use spread::SpreadingExample;
pub fn main() {
console_error_panic_hook::set_once();
leptos::mount::mount_to_body(SpreadingExample)
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/hackernews_js_fetch/src/lib.rs | examples/hackernews_js_fetch/src/lib.rs | use leptos::prelude::*;
mod api;
mod routes;
use leptos_meta::{provide_meta_context, Link, Meta, MetaTags, Stylesheet};
use leptos_router::{
components::{FlatRoutes, Route, Router, RoutingProgress},
OptionalParamSegment, ParamSegment, StaticSegment,
};
use routes::{nav::*, stories::*, story::*, users::*};
use std::time::Duration;
pub fn shell(options: LeptosOptions) -> impl IntoView {
view! {
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<AutoReload options=options.clone()/>
<HydrationScripts options/>
<MetaTags/>
</head>
<body>
<App/>
</body>
</html>
}
}
#[component]
pub fn App() -> impl IntoView {
provide_meta_context();
let (is_routing, set_is_routing) = signal(false);
view! {
<Stylesheet id="leptos" href="/public/style.css"/>
<Link rel="shortcut icon" type_="image/ico" href="/public/favicon.ico"/>
<Meta name="description" content="Leptos implementation of a HackerNews demo."/>
<Router set_is_routing>
// shows a progress bar while async data are loading
<div class="routing-progress">
<RoutingProgress is_routing max_time=Duration::from_millis(250)/>
</div>
<Nav/>
<main>
<FlatRoutes fallback=|| "Not found.">
<Route path=(StaticSegment("users"), ParamSegment("id")) view=User/>
<Route path=(StaticSegment("stories"), ParamSegment("id")) view=Story/>
<Route path=OptionalParamSegment("stories") view=Stories/>
</FlatRoutes>
</main>
</Router>
}
}
#[cfg(feature = "hydrate")]
#[wasm_bindgen::prelude::wasm_bindgen]
pub fn hydrate() {
console_error_panic_hook::set_once();
leptos::mount::hydrate_body(App);
}
#[cfg(feature = "ssr")]
mod ssr_imports {
use crate::{shell, App};
use axum::Router;
use leptos::prelude::*;
use leptos_axum::{generate_route_list, LeptosRoutes};
use log::{info, Level};
use wasm_bindgen::prelude::wasm_bindgen;
#[wasm_bindgen]
pub struct Handler(axum_js_fetch::App);
#[wasm_bindgen]
impl Handler {
pub async fn new() -> Self {
_ = console_log::init_with_level(Level::Debug);
console_error_panic_hook::set_once();
let leptos_options = LeptosOptions::builder()
.output_name("client")
.site_pkg_dir("pkg")
.build();
let routes = generate_route_list(App);
// build our application with a route
let app = Router::new()
.leptos_routes(&leptos_options, routes, {
let leptos_options = leptos_options.clone();
move || shell(leptos_options.clone())
})
.with_state(leptos_options);
info!("creating handler instance");
Self(axum_js_fetch::App::new(app))
}
pub async fn serve(&self, req: web_sys::Request) -> web_sys::Response {
self.0.oneshot(req).await
}
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/hackernews_js_fetch/src/api.rs | examples/hackernews_js_fetch/src/api.rs | use leptos::logging;
use serde::{de::DeserializeOwned, Deserialize, Serialize};
pub fn story(path: &str) -> String {
format!("https://node-hnapi.herokuapp.com/{path}")
}
pub fn user(path: &str) -> String {
format!("https://hacker-news.firebaseio.com/v0/user/{path}.json")
}
#[cfg(not(feature = "ssr"))]
pub fn fetch_api<T>(
path: &str,
) -> impl std::future::Future<Output = Option<T>> + Send + '_
where
T: Serialize + DeserializeOwned,
{
use leptos::prelude::on_cleanup;
use send_wrapper::SendWrapper;
SendWrapper::new(async move {
let abort_controller =
SendWrapper::new(web_sys::AbortController::new().ok());
let abort_signal = abort_controller.as_ref().map(|a| a.signal());
// abort in-flight requests if, e.g., we've navigated away from this page
on_cleanup(move || {
if let Some(abort_controller) = abort_controller.take() {
abort_controller.abort()
}
});
gloo_net::http::Request::get(path)
.abort_signal(abort_signal.as_ref())
.send()
.await
.map_err(|e| logging::error!("{e}"))
.ok()?
.json()
.await
.ok()
})
}
#[cfg(feature = "ssr")]
pub async fn fetch_api<T>(path: &str) -> Option<T>
where
T: Serialize + DeserializeOwned,
{
reqwest::get(path)
.await
.map_err(|e| logging::error!("{e}"))
.ok()?
.json()
.await
.ok()
}
#[derive(Debug, Deserialize, Serialize, PartialEq, Eq, Clone)]
pub struct Story {
pub id: usize,
pub title: String,
pub points: Option<i32>,
pub user: Option<String>,
pub time: usize,
pub time_ago: String,
#[serde(alias = "type")]
pub story_type: String,
pub url: String,
#[serde(default)]
pub domain: String,
#[serde(default)]
pub comments: Option<Vec<Comment>>,
pub comments_count: Option<usize>,
}
#[derive(Debug, Deserialize, Serialize, PartialEq, Eq, Clone)]
pub struct Comment {
pub id: usize,
pub level: usize,
pub user: Option<String>,
pub time: usize,
pub time_ago: String,
pub content: Option<String>,
pub comments: Vec<Comment>,
}
#[derive(Debug, Deserialize, Serialize, PartialEq, Eq, Clone)]
pub struct User {
pub created: usize,
pub id: String,
pub karma: i32,
pub about: Option<String>,
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/hackernews_js_fetch/src/routes.rs | examples/hackernews_js_fetch/src/routes.rs | pub mod nav;
pub mod stories;
pub mod story;
pub mod users;
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/hackernews_js_fetch/src/routes/users.rs | examples/hackernews_js_fetch/src/routes/users.rs | use crate::api::{self, User};
use leptos::{either::Either, prelude::*, server::Resource};
use leptos_router::hooks::use_params_map;
use send_wrapper::SendWrapper;
#[component]
pub fn User() -> impl IntoView {
let params = use_params_map();
let user = Resource::new(
move || params.read().get("id").unwrap_or_default(),
move |id| {
SendWrapper::new(async move {
if id.is_empty() {
None
} else {
api::fetch_api::<User>(&api::user(&id)).await
}
})
},
);
view! {
<div class="user-view">
<Suspense fallback=|| {
view! { "Loading..." }
}>
{move || Suspend::new(async move {
match user.await.clone() {
None => Either::Left(view! { <h1>"User not found."</h1> }),
Some(user) => {
Either::Right(
view! {
<div>
<h1>"User: " {user.id.clone()}</h1>
<ul class="meta">
<li>
<span class="label">"Created: "</span>
{user.created}
</li>
<li>
<span class="label">"Karma: "</span>
{user.karma}
</li>
<li inner_html=user.about class="about"></li>
</ul>
<p class="links">
<a href=format!(
"https://news.ycombinator.com/submitted?id={}",
user.id,
)>"submissions"</a>
" | "
<a href=format!(
"https://news.ycombinator.com/threads?id={}",
user.id,
)>"comments"</a>
</p>
</div>
},
)
}
}
})}
</Suspense>
</div>
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/hackernews_js_fetch/src/routes/story.rs | examples/hackernews_js_fetch/src/routes/story.rs | use crate::api;
use leptos::{either::Either, prelude::*};
use leptos_meta::Meta;
use leptos_router::{components::A, hooks::use_params_map};
use send_wrapper::SendWrapper;
#[component]
pub fn Story() -> impl IntoView {
let params = use_params_map();
let story = Resource::new_blocking(
move || params.read().get("id").unwrap_or_default(),
move |id| {
SendWrapper::new(async move {
if id.is_empty() {
None
} else {
api::fetch_api::<api::Story>(&api::story(&format!(
"item/{id}"
)))
.await
}
})
},
);
Suspense(SuspenseProps::builder().fallback(|| "Loading...").children(ToChildren::to_children(move || Suspend::new(async move {
match story.await.clone() {
None => Either::Left("Story not found."),
Some(story) => {
Either::Right(view! {
<Meta name="description" content=story.title.clone()/>
<div class="item-view">
<div class="item-view-header">
<a href=story.url target="_blank">
<h1>{story.title}</h1>
</a>
<span class="host">"("{story.domain}")"</span>
<ShowLet some=story.user let:user>
<p class="meta">
{story.points} " points | by "
<A href=format!("/users/{user}")>{user.clone()}</A>
{format!(" {}", story.time_ago)}
</p>
</ShowLet>
</div>
<div class="item-view-comments">
<p class="item-view-comments-header">
{if story.comments_count.unwrap_or_default() > 0 {
format!("{} comments", story.comments_count.unwrap_or_default())
} else {
"No comments yet.".into()
}}
</p>
<ul class="comment-children">
<For
each=move || story.comments.clone().unwrap_or_default()
key=|comment| comment.id
let:comment
>
<Comment comment/>
</For>
</ul>
</div>
</div>
})
}
}
}))).build())
}
#[component]
pub fn Comment(comment: api::Comment) -> impl IntoView {
let (open, set_open) = signal(true);
view! {
<li class="comment">
<div class="by">
<A href=format!(
"/users/{}",
comment.user.clone().unwrap_or_default(),
)>{comment.user.clone()}</A>
{format!(" {}", comment.time_ago)}
</div>
<div class="text" inner_html=comment.content></div>
{(!comment.comments.is_empty())
.then(|| {
view! {
<div>
<div class="toggle" class:open=open>
<a on:click=move |_| {
set_open.update(|n| *n = !*n)
}>
{
let comments_len = comment.comments.len();
move || {
if open.get() {
"[-]".into()
} else {
format!(
"[+] {}{} collapsed",
comments_len,
pluralize(comments_len),
)
}
}
}
</a>
</div>
{move || {
open.get()
.then({
let comments = comment.comments.clone();
move || {
view! {
<ul class="comment-children">
<For
each=move || comments.clone()
key=|comment| comment.id
let:comment
>
<Comment comment/>
</For>
</ul>
}
}
})
}}
</div>
}
})}
</li>
}.into_any()
}
fn pluralize(n: usize) -> &'static str {
if n == 1 {
" reply"
} else {
" replies"
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/hackernews_js_fetch/src/routes/nav.rs | examples/hackernews_js_fetch/src/routes/nav.rs | use leptos::prelude::*;
use leptos_router::components::A;
#[component]
pub fn Nav() -> impl IntoView {
view! {
<header class="header">
<nav class="inner">
<A href="/home">
<strong>"HN"</strong>
</A>
<A href="/new">
<strong>"New"</strong>
</A>
<A href="/show">
<strong>"Show"</strong>
</A>
<A href="/ask">
<strong>"Ask"</strong>
</A>
<A href="/job">
<strong>"Jobs"</strong>
</A>
<a
class="github"
href="http://github.com/leptos-rs/leptos"
target="_blank"
rel="noreferrer"
>
"Built with Leptos"
</a>
</nav>
</header>
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/hackernews_js_fetch/src/routes/stories.rs | examples/hackernews_js_fetch/src/routes/stories.rs | use crate::api;
use leptos::{either::Either, prelude::*};
use leptos_router::{
components::A,
hooks::{use_params_map, use_query_map},
};
use send_wrapper::SendWrapper;
fn category(from: &str) -> &'static str {
match from {
"new" => "newest",
"show" => "show",
"ask" => "ask",
"job" => "jobs",
_ => "news",
}
}
#[component]
pub fn Stories() -> impl IntoView {
let query = use_query_map();
let params = use_params_map();
let page = move || {
query
.read()
.get("page")
.and_then(|page| page.parse::<usize>().ok())
.unwrap_or(1)
};
let story_type = move || {
params
.read()
.get("stories")
.unwrap_or_else(|| "top".to_string())
};
let stories = Resource::new(
move || (page(), story_type()),
move |(page, story_type)| {
SendWrapper::new(async move {
let path = format!("{}?page={}", category(&story_type), page);
api::fetch_api::<Vec<api::Story>>(&api::story(&path)).await
})
},
);
let (pending, set_pending) = signal(false);
let hide_more_link = move || match &*stories.read() {
Some(Some(stories)) => stories.len() < 28,
_ => true
} || pending.get();
view! {
<div class="news-view">
<div class="news-list-nav">
<span>
{move || {
if page() > 1 {
Either::Left(
view! {
<a
class="page-link"
href=move || {
format!("/{}?page={}", story_type(), page() - 1)
}
aria-label="Previous Page"
>
"< prev"
</a>
},
)
} else {
Either::Right(
view! {
<span class="page-link disabled" aria-hidden="true">
"< prev"
</span>
},
)
}
}}
</span>
<span>"page " {page}</span>
<span class="page-link" class:disabled=hide_more_link aria-hidden=hide_more_link>
<a
href=move || format!("/{}?page={}", story_type(), page() + 1)
aria-label="Next Page"
>
"more >"
</a>
</span>
</div>
<main class="news-list">
<div>
<Transition fallback=move || view! { <p>"Loading..."</p> } set_pending>
<Show when=move || {
stories.read().as_ref().map(Option::is_none).unwrap_or(false)
}>> <p>"Error loading stories."</p></Show>
<ul>
<For
each=move || stories.get().unwrap_or_default().unwrap_or_default()
key=|story| story.id
let:story
>
<Story story/>
</For>
</ul>
</Transition>
</div>
</main>
</div>
}
}
#[component]
fn Story(story: api::Story) -> impl IntoView {
view! {
<li class="news-item">
<span class="score">{story.points}</span>
<span class="title">
{if !story.url.starts_with("item?id=") {
Either::Left(
view! {
<span>
<a href=story.url target="_blank" rel="noreferrer">
{story.title.clone()}
</a>
<span class="host">"("{story.domain}")"</span>
</span>
},
)
} else {
let title = story.title.clone();
Either::Right(view! { <A href=format!("/stories/{}", story.id)>{title}</A> })
}}
</span>
<br/>
<span class="meta">
{if story.story_type != "job" {
Either::Left(
view! {
<span>
"by "
<ShowLet some=story.user let:user>
<A href=format!("/users/{user}")>{user.clone()}</A>
</ShowLet>
{format!(" {} | ", story.time_ago)}
<A href=format!(
"/stories/{}",
story.id,
)>
{if story.comments_count.unwrap_or_default() > 0 {
format!(
"{} comments",
story.comments_count.unwrap_or_default(),
)
} else {
"discuss".into()
}}
</A>
</span>
},
)
} else {
let title = story.title.clone();
Either::Right(view! { <A href=format!("/item/{}", story.id)>{title}</A> })
}}
</span>
{(story.story_type != "link")
.then(|| {
view! {
" "
<span class="label">{story.story_type}</span>
}
})}
</li>
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/websocket/src/lib.rs | examples/websocket/src/lib.rs | pub mod websocket;
#[cfg(feature = "hydrate")]
#[wasm_bindgen::prelude::wasm_bindgen]
pub fn hydrate() {
use crate::websocket::App;
console_error_panic_hook::set_once();
leptos::mount::hydrate_body(App);
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/websocket/src/websocket.rs | examples/websocket/src/websocket.rs | use leptos::{prelude::*, task::spawn_local};
use server_fn::{codec::JsonEncoding, BoxedStream, ServerFnError, Websocket};
pub fn shell(options: LeptosOptions) -> impl IntoView {
view! {
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<AutoReload options=options.clone() />
<HydrationScripts options />
<link rel="shortcut icon" type="image/ico" href="/favicon.ico" />
</head>
<body>
<App />
</body>
</html>
}
}
// 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<String, ServerFnError>,
) -> Result<BoxedStream<String, ServerFnError>, ServerFnError> {
use futures::{channel::mpsc, SinkExt, StreamExt};
let mut input = input; // FIXME :-) server fn fields should pass mut through to destructure
// create a channel of outgoing websocket messages
// we'll return rx, so sending a message to tx will send a message to the client via the websocket
let (mut tx, rx) = mpsc::channel(1);
// spawn a task to listen to the input stream of messages coming in over the websocket
tokio::spawn(async move {
let mut x = 0;
while let Some(msg) = input.next().await {
// do some work on each message, and then send our responses
x += 1;
println!("In server: {} {:?}", x, msg);
if x % 3 == 0 {
let _ = tx
.send(Err(ServerFnError::Registration(
"Error generated from server".to_string(),
)))
.await;
} else {
let _ = tx.send(msg.map(|msg| msg.to_ascii_uppercase())).await;
}
}
});
Ok(rx.into())
}
#[component]
pub fn App() -> impl IntoView {
use futures::{channel::mpsc, StreamExt};
let (mut tx, rx) = mpsc::channel(1);
let latest = RwSignal::new(Ok("".into()));
// we'll only listen for websocket messages on the client
if cfg!(feature = "hydrate") {
spawn_local(async move {
match echo_websocket(rx.into()).await {
Ok(mut messages) => {
while let Some(msg) = messages.next().await {
leptos::logging::log!("{:?}", msg);
latest.set(msg);
}
}
Err(e) => leptos::logging::warn!("{e}"),
}
});
}
let mut x = 0;
view! {
<h1>Simple Echo WebSocket Communication</h1>
<input
type="text"
on:input:target=move |ev| {
x += 1;
let msg = ev.target().value();
leptos::logging::log!("In client: {} {:?}", x, msg);
if x % 5 == 0 {
let _ = tx
.try_send(
Err(
ServerFnError::Registration(
"Error generated from client".to_string(),
),
),
);
} else {
let _ = tx.try_send(Ok(msg));
}
}
/>
<div>
<ErrorBoundary fallback=|errors| {
view! {
<p>
{move || {
errors
.get()
.into_iter()
.map(|(_, e)| format!("{e:?}"))
.collect::<Vec<String>>()
.join(" ")
}}
</p>
}
}>
<p>{latest}</p>
</ErrorBoundary>
</div>
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/websocket/src/main.rs | examples/websocket/src/main.rs | #[cfg(feature = "ssr")]
#[tokio::main]
async fn main() {
use axum::Router;
use leptos::prelude::*;
use leptos_axum::{generate_route_list, LeptosRoutes};
use websocket::websocket::{shell, App};
simple_logger::init_with_level(log::Level::Error)
.expect("couldn't initialize logging");
// Setting this to None means we'll be using cargo-leptos and its env vars
let conf = get_configuration(None).unwrap();
let leptos_options = conf.leptos_options;
let addr = leptos_options.site_addr;
let routes = generate_route_list(App);
// build our application with a route
let app = Router::new()
.leptos_routes(&leptos_options, routes, {
let leptos_options = leptos_options.clone();
move || shell(leptos_options.clone())
})
.fallback(leptos_axum::file_and_error_handler(shell))
.with_state(leptos_options);
// run our app with hyper
// `axum::Server` is a re-export of `hyper::Server`
let listener = tokio::net::TcpListener::bind(&addr).await.unwrap();
println!("listening on http://{}", &addr);
axum::serve(listener, app.into_make_service())
.await
.unwrap();
}
#[cfg(not(feature = "ssr"))]
pub fn main() {
use leptos::mount::mount_to_body;
use websocket::websocket::App;
_ = console_log::init_with_level(log::Level::Debug);
console_error_panic_hook::set_once();
mount_to_body(App);
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/websocket/e2e/tests/app_suite.rs | examples/websocket/e2e/tests/app_suite.rs | mod fixtures;
use anyhow::Result;
use cucumber::World;
use fixtures::world::AppWorld;
#[tokio::main]
async fn main() -> Result<()> {
AppWorld::cucumber()
.fail_on_skipped()
.run_and_exit("./features")
.await;
Ok(())
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/websocket/e2e/tests/fixtures/check.rs | examples/websocket/e2e/tests/fixtures/check.rs | use anyhow::{Ok, Result};
use fantoccini::{Client, Locator};
use pretty_assertions::assert_eq;
pub async fn text_on_element(
client: &Client,
selector: &str,
expected_text: &str,
) -> Result<()> {
let element = client
.wait()
.for_element(Locator::Css(selector))
.await
.unwrap_or_else(|_| {
panic!("Element not found by Css selector `{}`", selector)
});
let actual = element.text().await?;
assert_eq!(&actual, expected_text);
Ok(())
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/websocket/e2e/tests/fixtures/find.rs | examples/websocket/e2e/tests/fixtures/find.rs | use fantoccini::{elements::Element, Client, Locator};
pub async fn input(client: &Client) -> Element {
let textbox = client
.wait()
.for_element(Locator::Css("input"))
.await
.expect("websocket textbox not found");
textbox
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/websocket/e2e/tests/fixtures/mod.rs | examples/websocket/e2e/tests/fixtures/mod.rs | pub mod action;
pub mod check;
pub mod find;
pub mod world;
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/websocket/e2e/tests/fixtures/action.rs | examples/websocket/e2e/tests/fixtures/action.rs | use super::{find, world::HOST};
use anyhow::Result;
use fantoccini::Client;
use std::result::Result::Ok;
pub async fn goto_path(client: &Client, path: &str) -> Result<()> {
let url = format!("{}{}", HOST, path);
client.goto(&url).await?;
Ok(())
}
pub async fn fill_input(client: &Client, text: &str) -> Result<()> {
let textbox = find::input(client).await;
textbox.send_keys(text).await?;
Ok(())
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/websocket/e2e/tests/fixtures/world/check_steps.rs | examples/websocket/e2e/tests/fixtures/world/check_steps.rs | use crate::fixtures::{check, world::AppWorld};
use anyhow::{Ok, Result};
use cucumber::then;
use std::time::Duration;
use tokio::time::sleep;
#[then(regex = "^I see the page title is (.*)$")]
async fn i_see_the_page_title_is(
world: &mut AppWorld,
text: String,
) -> Result<()> {
let client = &world.client;
check::text_on_element(client, "h1", &text).await?;
Ok(())
}
#[then(regex = "^I see the label of the input is (.*)$")]
async fn i_see_the_label_of_the_input_is(
world: &mut AppWorld,
text: String,
) -> Result<()> {
sleep(Duration::from_millis(500)).await;
let client = &world.client;
check::text_on_element(client, "p", &text).await?;
Ok(())
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/websocket/e2e/tests/fixtures/world/action_steps.rs | examples/websocket/e2e/tests/fixtures/world/action_steps.rs | use crate::fixtures::{action, world::AppWorld};
use anyhow::{Ok, Result};
use cucumber::{given, when};
#[given("I see the app")]
#[when("I open the app")]
async fn i_open_the_app(world: &mut AppWorld) -> Result<()> {
let client = &world.client;
action::goto_path(client, "").await?;
Ok(())
}
#[given(regex = "^I add a text as (.*)$")]
async fn i_add_a_text(world: &mut AppWorld, text: String) -> Result<()> {
let client = &world.client;
action::fill_input(client, text.as_str()).await?;
Ok(())
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/websocket/e2e/tests/fixtures/world/mod.rs | examples/websocket/e2e/tests/fixtures/world/mod.rs | pub mod action_steps;
pub mod check_steps;
use anyhow::Result;
use cucumber::World;
use fantoccini::{
error::NewSessionError, wd::Capabilities, Client, ClientBuilder,
};
pub const HOST: &str = "http://127.0.0.1:3000";
#[derive(Debug, World)]
#[world(init = Self::new)]
pub struct AppWorld {
pub client: Client,
}
impl AppWorld {
async fn new() -> Result<Self, anyhow::Error> {
let webdriver_client = build_client().await?;
Ok(Self {
client: webdriver_client,
})
}
}
async fn build_client() -> Result<Client, NewSessionError> {
let mut cap = Capabilities::new();
let arg = serde_json::from_str("{\"args\": [\"-headless\"]}").unwrap();
cap.insert("goog:chromeOptions".to_string(), arg);
let client = ClientBuilder::native()
.capabilities(cap)
.connect("http://localhost:4444")
.await?;
Ok(client)
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/oco/src/lib.rs | oco/src/lib.rs | //! which is used to store immutable references to values.
//! This is useful for storing, for example, strings.
//!
//! Imagine this as an alternative to [`Cow`] with an additional, reference-counted
//! branch.
//!
//! ```rust
//! use oco_ref::Oco;
//! use std::sync::Arc;
//!
//! let static_str = "foo";
//! let rc_str: Arc<str> = "bar".into();
//! let owned_str: String = "baz".into();
//!
//! fn uses_oco(value: impl Into<Oco<'static, str>>) {
//! let mut value = value.into();
//!
//! // ensures that the value is either a reference, or reference-counted
//! // O(n) at worst
//! let clone1 = value.clone_inplace();
//!
//! // these subsequent clones are O(1)
//! let clone2 = value.clone();
//! let clone3 = value.clone();
//! }
//!
//! uses_oco(static_str);
//! uses_oco(rc_str);
//! uses_oco(owned_str);
//! ```
#![forbid(unsafe_code)]
#![deny(missing_docs)]
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use std::{
borrow::{Borrow, Cow},
ffi::{CStr, OsStr},
fmt,
hash::Hash,
ops::{Add, Deref},
path::Path,
sync::Arc,
};
/// "Owned Clones Once": a smart pointer that can be either a reference,
/// an owned value, or a reference-counted pointer. This is useful for
/// storing immutable values, such as strings, in a way that is cheap to
/// clone and pass around.
///
/// The cost of the `Clone` implementation depends on the branch. Cloning the [`Oco::Borrowed`]
/// variant simply copies the references (`O(1)`). Cloning the [`Oco::Counted`]
/// variant increments a reference count (`O(1)`). Cloning the [`Oco::Owned`]
/// variant requires an `O(n)` clone of the data.
///
/// For an amortized `O(1)` clone, you can use [`Oco::clone_inplace()`]. Using this method,
/// [`Oco::Borrowed`] and [`Oco::Counted`] are still `O(1)`. [`Oco::Owned`] does a single `O(n)`
/// clone, but converts the object to the [`Oco::Counted`] branch, which means future clones will
/// be `O(1)`.
///
/// In general, you'll either want to call `clone_inplace()` once, before sharing the `Oco` with
/// other parts of your application (so that all future clones are `O(1)`), or simply use this as
/// if it is a [`Cow`] with an additional branch for reference-counted values.
pub enum Oco<'a, T: ?Sized + ToOwned + 'a> {
/// A static reference to a value.
Borrowed(&'a T),
/// A reference counted pointer to a value.
Counted(Arc<T>),
/// An owned value.
Owned(<T as ToOwned>::Owned),
}
impl<T: ?Sized + ToOwned> Oco<'_, T> {
/// Converts the value into an owned value.
pub fn into_owned(self) -> <T as ToOwned>::Owned {
match self {
Oco::Borrowed(v) => v.to_owned(),
Oco::Counted(v) => v.as_ref().to_owned(),
Oco::Owned(v) => v,
}
}
/// Checks if the value is [`Oco::Borrowed`].
/// # Examples
/// ```
/// # use std::sync::Arc;
/// # use oco_ref::Oco;
/// assert!(Oco::<str>::Borrowed("Hello").is_borrowed());
/// assert!(!Oco::<str>::Counted(Arc::from("Hello")).is_borrowed());
/// assert!(!Oco::<str>::Owned("Hello".to_string()).is_borrowed());
/// ```
pub const fn is_borrowed(&self) -> bool {
matches!(self, Oco::Borrowed(_))
}
/// Checks if the value is [`Oco::Counted`].
/// # Examples
/// ```
/// # use std::sync::Arc;
/// # use oco_ref::Oco;
/// assert!(Oco::<str>::Counted(Arc::from("Hello")).is_counted());
/// assert!(!Oco::<str>::Borrowed("Hello").is_counted());
/// assert!(!Oco::<str>::Owned("Hello".to_string()).is_counted());
/// ```
pub const fn is_counted(&self) -> bool {
matches!(self, Oco::Counted(_))
}
/// Checks if the value is [`Oco::Owned`].
/// # Examples
/// ```
/// # use std::sync::Arc;
/// # use oco_ref::Oco;
/// assert!(Oco::<str>::Owned("Hello".to_string()).is_owned());
/// assert!(!Oco::<str>::Borrowed("Hello").is_owned());
/// assert!(!Oco::<str>::Counted(Arc::from("Hello")).is_owned());
/// ```
pub const fn is_owned(&self) -> bool {
matches!(self, Oco::Owned(_))
}
}
impl<T: ?Sized + ToOwned> Deref for Oco<'_, T> {
type Target = T;
fn deref(&self) -> &T {
match self {
Oco::Borrowed(v) => v,
Oco::Owned(v) => v.borrow(),
Oco::Counted(v) => v,
}
}
}
impl<T: ?Sized + ToOwned> Borrow<T> for Oco<'_, T> {
#[inline(always)]
fn borrow(&self) -> &T {
self.deref()
}
}
impl<T: ?Sized + ToOwned> AsRef<T> for Oco<'_, T> {
#[inline(always)]
fn as_ref(&self) -> &T {
self.deref()
}
}
impl AsRef<Path> for Oco<'_, str> {
#[inline(always)]
fn as_ref(&self) -> &Path {
self.as_str().as_ref()
}
}
impl AsRef<Path> for Oco<'_, OsStr> {
#[inline(always)]
fn as_ref(&self) -> &Path {
self.as_os_str().as_ref()
}
}
// --------------------------------------
// pub fn as_{slice}(&self) -> &{slice}
// --------------------------------------
impl Oco<'_, str> {
/// Returns a `&str` slice of this [`Oco`].
/// # Examples
/// ```
/// # use oco_ref::Oco;
/// let oco = Oco::<str>::Borrowed("Hello");
/// let s: &str = oco.as_str();
/// assert_eq!(s, "Hello");
/// ```
#[inline(always)]
pub fn as_str(&self) -> &str {
self
}
}
impl Oco<'_, CStr> {
/// Returns a `&CStr` slice of this [`Oco`].
/// # Examples
/// ```
/// # use oco_ref::Oco;
/// use std::ffi::CStr;
///
/// let oco =
/// Oco::<CStr>::Borrowed(CStr::from_bytes_with_nul(b"Hello\0").unwrap());
/// let s: &CStr = oco.as_c_str();
/// assert_eq!(s, CStr::from_bytes_with_nul(b"Hello\0").unwrap());
/// ```
#[inline(always)]
pub fn as_c_str(&self) -> &CStr {
self
}
}
impl Oco<'_, OsStr> {
/// Returns a `&OsStr` slice of this [`Oco`].
/// # Examples
/// ```
/// # use oco_ref::Oco;
/// use std::ffi::OsStr;
///
/// let oco = Oco::<OsStr>::Borrowed(OsStr::new("Hello"));
/// let s: &OsStr = oco.as_os_str();
/// assert_eq!(s, OsStr::new("Hello"));
/// ```
#[inline(always)]
pub fn as_os_str(&self) -> &OsStr {
self
}
}
impl Oco<'_, Path> {
/// Returns a `&Path` slice of this [`Oco`].
/// # Examples
/// ```
/// # use oco_ref::Oco;
/// use std::path::Path;
///
/// let oco = Oco::<Path>::Borrowed(Path::new("Hello"));
/// let s: &Path = oco.as_path();
/// assert_eq!(s, Path::new("Hello"));
/// ```
#[inline(always)]
pub fn as_path(&self) -> &Path {
self
}
}
impl<T> Oco<'_, [T]>
where
[T]: ToOwned,
{
/// Returns a `&[T]` slice of this [`Oco`].
/// # Examples
/// ```
/// # use oco_ref::Oco;
/// let oco = Oco::<[u8]>::Borrowed(b"Hello");
/// let s: &[u8] = oco.as_slice();
/// assert_eq!(s, b"Hello");
/// ```
#[inline(always)]
pub fn as_slice(&self) -> &[T] {
self
}
}
impl<'a, T> Clone for Oco<'a, T>
where
T: ?Sized + ToOwned + 'a,
for<'b> Arc<T>: From<&'b T>,
{
/// Returns a new [`Oco`] with the same value as this one.
/// If the value is [`Oco::Owned`], this will convert it into
/// [`Oco::Counted`], so that the next clone will be O(1).
/// # Examples
/// [`String`] :
/// ```
/// # use oco_ref::Oco;
/// let oco = Oco::<str>::Owned("Hello".to_string());
/// let oco2 = oco.clone();
/// assert_eq!(oco, oco2);
/// assert!(oco2.is_counted());
/// ```
/// [`Vec`] :
/// ```
/// # use oco_ref::Oco;
/// let oco = Oco::<[u8]>::Owned(b"Hello".to_vec());
/// let oco2 = oco.clone();
/// assert_eq!(oco, oco2);
/// assert!(oco2.is_counted());
/// ```
fn clone(&self) -> Self {
match self {
Self::Borrowed(v) => Self::Borrowed(v),
Self::Counted(v) => Self::Counted(Arc::clone(v)),
Self::Owned(v) => Self::Counted(Arc::from(v.borrow())),
}
}
}
impl<'a, T> Oco<'a, T>
where
T: ?Sized + ToOwned + 'a,
for<'b> Arc<T>: From<&'b T>,
{
/// Upgrades the value in place, by converting into [`Oco::Counted`] if it
/// was previously [`Oco::Owned`].
/// # Examples
/// ```
/// # use oco_ref::Oco;
/// let mut oco1 = Oco::<str>::Owned("Hello".to_string());
/// assert!(oco1.is_owned());
/// oco1.upgrade_inplace();
/// assert!(oco1.is_counted());
/// ```
pub fn upgrade_inplace(&mut self) {
if let Self::Owned(v) = &*self {
let rc = Arc::from(v.borrow());
*self = Self::Counted(rc);
}
}
/// Clones the value with inplace conversion into [`Oco::Counted`] if it
/// was previously [`Oco::Owned`].
/// # Examples
/// ```
/// # use oco_ref::Oco;
/// let mut oco1 = Oco::<str>::Owned("Hello".to_string());
/// let oco2 = oco1.clone_inplace();
/// assert_eq!(oco1, oco2);
/// assert!(oco1.is_counted());
/// assert!(oco2.is_counted());
/// ```
pub fn clone_inplace(&mut self) -> Self {
match &*self {
Self::Borrowed(v) => Self::Borrowed(v),
Self::Counted(v) => Self::Counted(Arc::clone(v)),
Self::Owned(v) => {
let rc = Arc::from(v.borrow());
*self = Self::Counted(rc.clone());
Self::Counted(rc)
}
}
}
}
impl<T: ?Sized> Default for Oco<'_, T>
where
T: ToOwned,
T::Owned: Default,
{
fn default() -> Self {
Oco::Owned(T::Owned::default())
}
}
impl<'b, A: ?Sized, B: ?Sized> PartialEq<Oco<'b, B>> for Oco<'_, A>
where
A: PartialEq<B>,
A: ToOwned,
B: ToOwned,
{
fn eq(&self, other: &Oco<'b, B>) -> bool {
**self == **other
}
}
impl<T: ?Sized + ToOwned + Eq> Eq for Oco<'_, T> {}
impl<'b, A: ?Sized, B: ?Sized> PartialOrd<Oco<'b, B>> for Oco<'_, A>
where
A: PartialOrd<B>,
A: ToOwned,
B: ToOwned,
{
fn partial_cmp(&self, other: &Oco<'b, B>) -> Option<std::cmp::Ordering> {
(**self).partial_cmp(&**other)
}
}
impl<T: ?Sized + Ord> Ord for Oco<'_, T>
where
T: ToOwned,
{
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
(**self).cmp(&**other)
}
}
impl<T: ?Sized + Hash> Hash for Oco<'_, T>
where
T: ToOwned,
{
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
(**self).hash(state)
}
}
impl<T: ?Sized + fmt::Debug> fmt::Debug for Oco<'_, T>
where
T: ToOwned,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
(**self).fmt(f)
}
}
impl<T: ?Sized + fmt::Display> fmt::Display for Oco<'_, T>
where
T: ToOwned,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
(**self).fmt(f)
}
}
impl<'a, T: ?Sized> From<&'a T> for Oco<'a, T>
where
T: ToOwned,
{
fn from(v: &'a T) -> Self {
Oco::Borrowed(v)
}
}
impl<'a, T: ?Sized> From<Cow<'a, T>> for Oco<'a, T>
where
T: ToOwned,
{
fn from(v: Cow<'a, T>) -> Self {
match v {
Cow::Borrowed(v) => Oco::Borrowed(v),
Cow::Owned(v) => Oco::Owned(v),
}
}
}
impl<'a, T: ?Sized> From<Oco<'a, T>> for Cow<'a, T>
where
T: ToOwned,
{
fn from(value: Oco<'a, T>) -> Self {
match value {
Oco::Borrowed(v) => Cow::Borrowed(v),
Oco::Owned(v) => Cow::Owned(v),
Oco::Counted(v) => Cow::Owned(v.as_ref().to_owned()),
}
}
}
impl<T: ?Sized> From<Arc<T>> for Oco<'_, T>
where
T: ToOwned,
{
fn from(v: Arc<T>) -> Self {
Oco::Counted(v)
}
}
impl<T: ?Sized> From<Box<T>> for Oco<'_, T>
where
T: ToOwned,
{
fn from(v: Box<T>) -> Self {
Oco::Counted(v.into())
}
}
impl From<String> for Oco<'_, str> {
fn from(v: String) -> Self {
Oco::Owned(v)
}
}
impl From<Oco<'_, str>> for String {
fn from(v: Oco<'_, str>) -> Self {
match v {
Oco::Borrowed(v) => v.to_owned(),
Oco::Counted(v) => v.as_ref().to_owned(),
Oco::Owned(v) => v,
}
}
}
impl<T> From<Vec<T>> for Oco<'_, [T]>
where
[T]: ToOwned<Owned = Vec<T>>,
{
fn from(v: Vec<T>) -> Self {
Oco::Owned(v)
}
}
impl<'a, T, const N: usize> From<&'a [T; N]> for Oco<'a, [T]>
where
[T]: ToOwned,
{
fn from(v: &'a [T; N]) -> Self {
Oco::Borrowed(v)
}
}
impl<'a> From<Oco<'a, str>> for Oco<'a, [u8]> {
fn from(v: Oco<'a, str>) -> Self {
match v {
Oco::Borrowed(v) => Oco::Borrowed(v.as_bytes()),
Oco::Owned(v) => Oco::Owned(v.into_bytes()),
Oco::Counted(v) => Oco::Counted(v.into()),
}
}
}
/// Error returned from `Oco::try_from` for unsuccessful
/// conversion from `Oco<'_, [u8]>` to `Oco<'_, str>`.
#[derive(Debug, Clone, thiserror::Error)]
#[error("invalid utf-8 sequence: {_0}")]
pub enum FromUtf8Error {
/// Error for conversion of [`Oco::Borrowed`] and [`Oco::Counted`] variants
/// (`&[u8]` to `&str`).
#[error("{_0}")]
StrFromBytes(
#[source]
#[from]
std::str::Utf8Error,
),
/// Error for conversion of [`Oco::Owned`] variant (`Vec<u8>` to `String`).
#[error("{_0}")]
StringFromBytes(
#[source]
#[from]
std::string::FromUtf8Error,
),
}
macro_rules! impl_slice_eq {
([$($g:tt)*] $((where $($w:tt)+))?, $lhs:ty, $rhs: ty) => {
impl<$($g)*> PartialEq<$rhs> for $lhs
$(where
$($w)*)?
{
#[inline]
fn eq(&self, other: &$rhs) -> bool {
PartialEq::eq(&self[..], &other[..])
}
}
impl<$($g)*> PartialEq<$lhs> for $rhs
$(where
$($w)*)?
{
#[inline]
fn eq(&self, other: &$lhs) -> bool {
PartialEq::eq(&self[..], &other[..])
}
}
};
}
impl_slice_eq!([], Oco<'_, str>, str);
impl_slice_eq!(['a, 'b], Oco<'a, str>, &'b str);
impl_slice_eq!([], Oco<'_, str>, String);
impl_slice_eq!(['a, 'b], Oco<'a, str>, Cow<'b, str>);
impl_slice_eq!([T: PartialEq] (where [T]: ToOwned), Oco<'_, [T]>, [T]);
impl_slice_eq!(['a, 'b, T: PartialEq] (where [T]: ToOwned), Oco<'a, [T]>, &'b [T]);
impl_slice_eq!([T: PartialEq] (where [T]: ToOwned), Oco<'_, [T]>, Vec<T>);
impl_slice_eq!(['a, 'b, T: PartialEq] (where [T]: ToOwned), Oco<'a, [T]>, Cow<'b, [T]>);
impl<'b> Add<&'b str> for Oco<'_, str> {
type Output = Oco<'static, str>;
fn add(self, rhs: &'b str) -> Self::Output {
Oco::Owned(String::from(self) + rhs)
}
}
impl<'b> Add<Cow<'b, str>> for Oco<'_, str> {
type Output = Oco<'static, str>;
fn add(self, rhs: Cow<'b, str>) -> Self::Output {
Oco::Owned(String::from(self) + rhs.as_ref())
}
}
impl<'b> Add<Oco<'b, str>> for Oco<'_, str> {
type Output = Oco<'static, str>;
fn add(self, rhs: Oco<'b, str>) -> Self::Output {
Oco::Owned(String::from(self) + rhs.as_ref())
}
}
impl<'a> FromIterator<Oco<'a, str>> for String {
fn from_iter<T: IntoIterator<Item = Oco<'a, str>>>(iter: T) -> Self {
iter.into_iter().fold(String::new(), |mut acc, item| {
acc.push_str(item.as_ref());
acc
})
}
}
impl<'a, T> Deserialize<'a> for Oco<'static, T>
where
T: ?Sized + ToOwned + 'a,
T::Owned: DeserializeOwned,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'a>,
{
<T::Owned>::deserialize(deserializer).map(Oco::Owned)
}
}
impl<'a, T> Serialize for Oco<'a, T>
where
T: ?Sized + ToOwned + 'a,
for<'b> &'b T: Serialize,
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
self.as_ref().serialize(serializer)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn debug_fmt_should_display_quotes_for_strings() {
let s: Oco<str> = Oco::Borrowed("hello");
assert_eq!(format!("{s:?}"), "\"hello\"");
let s: Oco<str> = Oco::Counted(Arc::from("hello"));
assert_eq!(format!("{s:?}"), "\"hello\"");
}
#[test]
fn partial_eq_should_compare_str_to_str() {
let s: Oco<str> = Oco::Borrowed("hello");
assert_eq!(s, "hello");
assert_eq!("hello", s);
assert_eq!(s, String::from("hello"));
assert_eq!(String::from("hello"), s);
assert_eq!(s, Cow::from("hello"));
assert_eq!(Cow::from("hello"), s);
}
#[test]
fn partial_eq_should_compare_slice_to_slice() {
let s: Oco<[i32]> = Oco::Borrowed([1, 2, 3].as_slice());
assert_eq!(s, [1, 2, 3].as_slice());
assert_eq!([1, 2, 3].as_slice(), s);
assert_eq!(s, vec![1, 2, 3]);
assert_eq!(vec![1, 2, 3], s);
assert_eq!(s, Cow::<'_, [i32]>::Borrowed(&[1, 2, 3]));
assert_eq!(Cow::<'_, [i32]>::Borrowed(&[1, 2, 3]), s);
}
#[test]
fn add_should_concatenate_strings() {
let s: Oco<str> = Oco::Borrowed("hello");
assert_eq!(s.clone() + " world", "hello world");
assert_eq!(s.clone() + Cow::from(" world"), "hello world");
assert_eq!(s + Oco::from(" world"), "hello world");
}
#[test]
fn as_str_should_return_a_str() {
let s: Oco<str> = Oco::Borrowed("hello");
assert_eq!(s.as_str(), "hello");
let s: Oco<str> = Oco::Counted(Arc::from("hello"));
assert_eq!(s.as_str(), "hello");
}
#[test]
fn as_slice_should_return_a_slice() {
let s: Oco<[i32]> = Oco::Borrowed([1, 2, 3].as_slice());
assert_eq!(s.as_slice(), [1, 2, 3].as_slice());
let s: Oco<[i32]> = Oco::Counted(Arc::from([1, 2, 3]));
assert_eq!(s.as_slice(), [1, 2, 3].as_slice());
}
#[test]
fn default_for_str_should_return_an_empty_string() {
let s: Oco<str> = Default::default();
assert!(s.is_empty());
}
#[test]
fn default_for_slice_should_return_an_empty_slice() {
let s: Oco<[i32]> = Default::default();
assert!(s.is_empty());
}
#[test]
fn default_for_any_option_should_return_none() {
let s: Oco<Option<i32>> = Default::default();
assert!(s.is_none());
}
#[test]
fn cloned_owned_string_should_make_counted_str() {
let s: Oco<str> = Oco::Owned(String::from("hello"));
assert!(s.clone().is_counted());
}
#[test]
fn cloned_borrowed_str_should_make_borrowed_str() {
let s: Oco<str> = Oco::Borrowed("hello");
assert!(s.clone().is_borrowed());
}
#[test]
fn cloned_counted_str_should_make_counted_str() {
let s: Oco<str> = Oco::Counted(Arc::from("hello"));
assert!(s.clone().is_counted());
}
#[test]
fn cloned_inplace_owned_string_should_make_counted_str_and_become_counted()
{
let mut s: Oco<str> = Oco::Owned(String::from("hello"));
assert!(s.clone_inplace().is_counted());
assert!(s.is_counted());
}
#[test]
fn cloned_inplace_borrowed_str_should_make_borrowed_str_and_remain_borrowed(
) {
let mut s: Oco<str> = Oco::Borrowed("hello");
assert!(s.clone_inplace().is_borrowed());
assert!(s.is_borrowed());
}
#[test]
fn cloned_inplace_counted_str_should_make_counted_str_and_remain_counted() {
let mut s: Oco<str> = Oco::Counted(Arc::from("hello"));
assert!(s.clone_inplace().is_counted());
assert!(s.is_counted());
}
#[test]
fn serialization_works() {
let s = serde_json::to_string(&Oco::Borrowed("foo"))
.expect("should serialize string");
assert_eq!(s, "\"foo\"");
}
#[test]
fn deserialization_works() {
let s: Oco<str> = serde_json::from_str("\"bar\"")
.expect("should deserialize from string");
assert_eq!(s, Oco::from(String::from("bar")));
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/router/build.rs | router/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/router/src/link.rs | router/src/link.rs | use crate::{components::RouterContext, hooks::use_resolved_path};
use leptos::{children::Children, oco::Oco, prelude::*};
use reactive_graph::{computed::ArcMemo, owner::use_context};
use std::{borrow::Cow, rc::Rc};
/// Describes a value that is either a static or a reactive URL, i.e.,
/// a [`String`], a [`&str`], or a reactive `Fn() -> String`.
pub trait ToHref {
/// Converts the (static or reactive) URL into a function that can be called to
/// return the URL.
fn to_href(&self) -> Box<dyn Fn() -> String + '_>;
}
impl ToHref for &str {
fn to_href(&self) -> Box<dyn Fn() -> String> {
let s = self.to_string();
Box::new(move || s.clone())
}
}
impl ToHref for String {
fn to_href(&self) -> Box<dyn Fn() -> String> {
let s = self.clone();
Box::new(move || s.clone())
}
}
impl ToHref for Cow<'_, str> {
fn to_href(&self) -> Box<dyn Fn() -> String + '_> {
let s = self.to_string();
Box::new(move || s.clone())
}
}
impl ToHref for Oco<'_, str> {
fn to_href(&self) -> Box<dyn Fn() -> String + '_> {
let s = self.to_string();
Box::new(move || s.clone())
}
}
impl ToHref for Rc<str> {
fn to_href(&self) -> Box<dyn Fn() -> String + '_> {
let s = self.to_string();
Box::new(move || s.clone())
}
}
impl<F> ToHref for F
where
F: Fn() -> String + 'static,
{
fn to_href(&self) -> Box<dyn Fn() -> String + '_> {
Box::new(self)
}
}
/// An HTML [`a`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a)
/// progressively enhanced to use client-side routing.
///
/// Client-side routing also works with ordinary HTML `<a>` tags, but `<A>` does two additional things:
/// 1) Correctly resolves relative nested routes. Relative routing with ordinary `<a>` tags can be tricky.
/// For example, if you have a route like `/post/:id`, `<A href="1">` will generate the correct relative
/// route, but `<a href="1">` likely will not (depending on where it appears in your view.)
/// 2) Sets the `aria-current` attribute if this link is the active link (i.e., it’s a link to the page you’re on).
/// This is helpful for accessibility and for styling. For example, maybe you want to set the link a
/// different color if it’s a link to the page you’re currently on.
///
/// ### Additional Attributes
///
/// You can add additional HTML attributes to the `<a>` element created by this component using the attribute
/// spreading syntax for components. For example, to add a class, you can use `attr:class="my-link"`.
/// Alternately, you can add any number of HTML attributes (include `class`) after a `{..}` marker.
///
/// ```rust
/// # use leptos::prelude::*; use leptos_router::components::A;
/// # fn spread_example() -> impl IntoView {
/// view! {
/// <A href="/about" attr:class="my-link" {..} id="foo">"Some link"</A>
/// <A href="/about" {..} class="my-link" id="bar">"Another link"</A>
/// <A href="/about" {..} class:my-link=true id="baz">"One more"</A>
/// }
/// # }
/// ```
///
/// For more information on this attribute spreading syntax, [see here](https://book.leptos.dev/view/03_components.html#spreading-attributes-onto-components).
///
/// ### DOM Properties
///
/// `<a>` elements can take several additional DOM properties with special meanings.
/// - **`prop:state`**: An object of any type that will be pushed to router state.
/// - **`prop:replace`**: If `true`, the link will not add to the browser's history (so, pressing `Back`
/// will skip this page.)
///
/// Previously, this component took these as component props. Now, they can be added using the
/// `prop:` syntax, and will be added directly to the DOM. They can work with either `<a>` elements
/// or the `<A/>` component.
#[component]
pub fn A<H>(
/// Used to calculate the link's `href` attribute. Will be resolved relative
/// to the current route.
href: H,
/// Where to display the linked URL, as the name for a browsing context (a tab, window, or `<iframe>`).
#[prop(optional, into)]
target: Option<Oco<'static, str>>,
/// If `true`, the link is marked active when the location matches exactly;
/// if false, link is marked active if the current route starts with it.
#[prop(optional)]
exact: bool,
/// If `true`, and when `href` has a trailing slash, `aria-current` be only be set if `current_url` also has
/// a trailing slash.
#[prop(optional)]
strict_trailing_slash: bool,
/// If `true`, the router will scroll to the top of the window at the end of navigation. Defaults to `true`.
#[prop(default = true)]
scroll: bool,
/// The nodes or elements to be shown inside the link.
children: Children,
) -> impl IntoView
where
H: ToHref + Send + Sync + 'static,
{
fn inner(
href: ArcMemo<String>,
target: Option<Oco<'static, str>>,
exact: bool,
children: Children,
strict_trailing_slash: bool,
scroll: bool,
) -> impl IntoView {
let RouterContext { current_url, .. } =
use_context().expect("tried to use <A/> outside a <Router/>.");
let is_active = {
let href = href.clone();
move || {
let path = normalize_path(&href.read());
current_url.with(|loc| {
let loc = loc.path();
if exact {
loc == path
} else {
is_active_for(&path, loc, strict_trailing_slash)
}
})
}
};
view! {
<a
href=move || href.get()
target=target
aria-current=move || if is_active() { Some("page") } else { None }
data-noscroll=!scroll
>
{children()}
</a>
}
}
let href = use_resolved_path(move || href.to_href()());
inner(href, target, exact, children, strict_trailing_slash, scroll)
}
// Test if `href` is active for `location`. Assumes _both_ `href` and `location` begin with a `'/'`.
fn is_active_for(
href: &str,
location: &str,
strict_trailing_slash: bool,
) -> bool {
let mut href_f = href.split('/');
// location _must_ be consumed first to avoid draining href_f early
// also using enumerate to special case _the first two_ so that the allowance for ignoring the comparison
// with the loc fragment on an emtpy href fragment for non root related parts.
std::iter::zip(location.split('/'), href_f.by_ref())
.enumerate()
.all(|(c, (loc_p, href_p))| {
loc_p == href_p || href_p.is_empty() && c > 1
})
&& match href_f.next() {
// when no href fragments remain, location is definitely somewhere nested inside href
None => true,
// when an outstanding href fragment is an empty string, default `strict_trailing_slash` setting will
// have the typical expected case where href="/item/" is active for location="/item", but when toggled
// to true it becomes inactive; please refer to test case comments for explanation.
Some("") => !strict_trailing_slash,
// inactive when href fragments remain (otherwise false postive for href="/item/one", location="/item")
_ => false,
}
}
// Resolve `".."` segments in the path. Assume path is either empty or starts with a `'/'``.
fn normalize_path(path: &str) -> String {
// Return only on the only condition where leading slash
// is allowed to be missing.
if path.is_empty() {
return String::new();
}
let mut del = 0;
let mut it = path
.split(['?', '#'])
.next()
.unwrap_or_default()
.split(['/'])
.rev()
.peekable();
let init = if it.peek() == Some(&"..") {
String::from("/")
} else {
String::new()
};
let mut path = it
.filter(|v| {
if *v == ".." {
del += 1;
false
} else if *v == "." {
false
} else if del > 0 {
del -= 1;
false
} else {
true
}
})
// We cannot reverse before the fold again bc the filter
// would be forwards again.
.fold(init, |mut p, v| {
p.reserve(v.len() + 1);
p.insert(0, '/');
p.insert_str(0, v);
p
});
path.truncate(path.len().saturating_sub(1));
// Path starts with '/' giving it an extra empty segment after the split
// Which should not be removed.
if !path.starts_with('/') {
path.insert(0, '/');
}
path
}
#[cfg(test)]
mod tests {
use super::{is_active_for, normalize_path};
#[test]
fn is_active_for_matched() {
[false, true].into_iter().for_each(|f| {
// root
assert!(is_active_for("/", "/", f));
// both at one level for all combinations of trailing slashes
assert!(is_active_for("/item", "/item", f));
// assert!(is_active_for("/item/", "/item", f));
assert!(is_active_for("/item", "/item/", f));
assert!(is_active_for("/item/", "/item/", f));
// plus sub one level for all combinations of trailing slashes
assert!(is_active_for("/item", "/item/one", f));
assert!(is_active_for("/item", "/item/one/", f));
assert!(is_active_for("/item/", "/item/one", f));
assert!(is_active_for("/item/", "/item/one/", f));
// both at two levels for all combinations of trailing slashes
assert!(is_active_for("/item/1", "/item/1", f));
// assert!(is_active_for("/item/1/", "/item/1", f));
assert!(is_active_for("/item/1", "/item/1/", f));
assert!(is_active_for("/item/1/", "/item/1/", f));
// plus sub various levels for all combinations of trailing slashes
assert!(is_active_for("/item/1", "/item/1/two", f));
assert!(is_active_for("/item/1", "/item/1/three/four/", f));
assert!(is_active_for("/item/1/", "/item/1/three/four", f));
assert!(is_active_for("/item/1/", "/item/1/two/", f));
// both at various levels for various trailing slashes
assert!(is_active_for("/item/1/two/three", "/item/1/two/three", f));
assert!(is_active_for(
"/item/1/two/three/444",
"/item/1/two/three/444/",
f
));
// assert!(is_active_for(
// "/item/1/two/three/444/FIVE/",
// "/item/1/two/three/444/FIVE",
// f
// ));
assert!(is_active_for(
"/item/1/two/three/444/FIVE/final/",
"/item/1/two/three/444/FIVE/final/",
f
));
// sub various levels for various trailing slashes
assert!(is_active_for(
"/item/1/two/three",
"/item/1/two/three/three/two/1/item",
f
));
assert!(is_active_for(
"/item/1/two/three/444",
"/item/1/two/three/444/just_one_more/",
f
));
assert!(is_active_for(
"/item/1/two/three/444/final/",
"/item/1/two/three/444/final/just/kidding",
f
));
// edge/weird/unexpected cases?
// since empty fragments are not checked, these all highlight
assert!(is_active_for(
"/item/////",
"/item/one/two/three/four/",
f
));
assert!(is_active_for(
"/item/////",
"/item/1/two/three/three/two/1/item",
f
));
assert!(is_active_for(
"/item/1///three//1",
"/item/1/two/three/three/two/1/item",
f
));
// artifact of the checking algorithm, as it assumes empty segments denote termination of sort, so
// omission acts like a wildcard that isn't checked.
assert!(is_active_for(
"/item//foo",
"/item/this_is_not_empty/foo/bar/baz",
f
));
});
// Refer to comment on the similar scenario on the next test case for explanation, as this assumes the
// "typical" case where the strict trailing slash flag is unset or false.
assert!(is_active_for("/item/", "/item", false));
assert!(is_active_for("/item/1/", "/item/1", false));
assert!(is_active_for(
"/item/1/two/three/444/FIVE/",
"/item/1/two/three/444/FIVE",
false
));
}
#[test]
fn is_active_for_mismatched() {
[false, true].into_iter().for_each(|f| {
// href="/"
assert!(!is_active_for("/", "/item", f));
assert!(!is_active_for("/", "/somewhere/", f));
assert!(!is_active_for("/", "/else/where", f));
assert!(!is_active_for("/", "/no/where/", f));
// non root href but location at root
assert!(!is_active_for("/somewhere", "/", f));
assert!(!is_active_for("/somewhere/", "/", f));
assert!(!is_active_for("/else/where", "/", f));
assert!(!is_active_for("/no/where/", "/", f));
// mismatch either side all combinations of trailing slashes
assert!(!is_active_for("/level", "/item", f));
assert!(!is_active_for("/level", "/item/", f));
assert!(!is_active_for("/level/", "/item", f));
assert!(!is_active_for("/level/", "/item/", f));
// one level parent for all combinations of trailing slashes
assert!(!is_active_for("/item/one", "/item", f));
assert!(!is_active_for("/item/one/", "/item", f));
assert!(!is_active_for("/item/one", "/item/", f));
assert!(!is_active_for("/item/one/", "/item/", f));
// various parent levels for all combinations of trailing slashes
assert!(!is_active_for("/item/1/two", "/item/1", f));
assert!(!is_active_for("/item/1/three/four/", "/item/1", f));
assert!(!is_active_for("/item/1/three/four", "/item/", f));
assert!(!is_active_for("/item/1/two/", "/item/", f));
// sub various levels for various trailing slashes
assert!(!is_active_for(
"/item/1/two/three/three/two/1/item",
"/item/1/two/three",
f
));
assert!(!is_active_for(
"/item/1/two/three/444/just_one_more/",
"/item/1/two/three/444",
f
));
assert!(!is_active_for(
"/item/1/two/three/444/final/just/kidding",
"/item/1/two/three/444/final/",
f
));
// edge/weird/unexpected cases?
// default trailing slash has the expected behavior of non-matching of any non-root location
// this checks as if `href="/"`
assert!(!is_active_for(
"//////",
"/item/1/two/three/three/two/1/item",
f
));
// some weird root location?
assert!(!is_active_for(
"/item/1/two/three/three/two/1/item",
"//////",
f
));
assert!(!is_active_for(
"/item/one/two/three/four/",
"/item/////",
f
));
assert!(!is_active_for(
"/item/one/two/three/four/",
"/item////four/",
f
));
});
// The following tests enables the `strict_trailing_slash` flag, which allows the less common
// interpretation of `/item/` being a resource with proper subitems while `/item` just simply browsing
// the flat `item` while still currently at `/`, as the user hasn't "initiate the descent" into it
// (e.g. a certain filesystem tried to implement a feature where a directory can be opened as a file),
// it may be argued that when user is simply checking what `/item` is by going to that location, they
// are still active at `/` - only by actually going into `/item/` that they are truly active there.
//
// In any case, the algorithm currently assumes the more "typical" case where the non-slash version is
// an "alias" of the trailing-slash version (so aria-current is set), as "ordinarily" this is the case
// expected by "ordinary" end-users who almost never encounter this particular scenario.
assert!(!is_active_for("/item/", "/item", true));
assert!(!is_active_for("/item/1/", "/item/1", true));
assert!(!is_active_for(
"/item/1/two/three/444/FIVE/",
"/item/1/two/three/444/FIVE",
true
));
// That said, in this particular scenario, the definition above should result the following be asserted
// as true, but then it follows that every scenario may be true as the root was special cased - in
// which case it becomes a bit meaningless?
//
// assert!(is_active_for("/", "/item", true));
//
// Perhaps there needs to be a flag such that aria-curent applies only the _same level_, e.g
// assert!(is_same_level("/", "/"))
// assert!(is_same_level("/", "/anything"))
// assert!(!is_same_level("/", "/some/"))
// assert!(!is_same_level("/", "/some/level"))
// assert!(is_same_level("/some/", "/some/"))
// assert!(is_same_level("/some/", "/some/level"))
// assert!(!is_same_level("/some/", "/some/level/"))
// assert!(!is_same_level("/some/", "/some/level/deeper"))
}
#[test]
fn normalize_path_test() {
// Make sure it doesn't touch already normalized urls.
assert!(normalize_path("") == "".to_string());
assert!(normalize_path("/") == "/".to_string());
assert!(normalize_path("/some") == "/some".to_string());
assert!(normalize_path("/some/") == "/some/".to_string());
// Correctly removes ".." segments.
assert!(normalize_path("/some/../another") == "/another".to_string());
assert!(
normalize_path("/one/two/../three/../../four")
== "/four".to_string()
);
// Correctly sets trailing slash if last segement is "..".
assert!(normalize_path("/one/two/..") == "/one/".to_string());
assert!(normalize_path("/one/two/../") == "/one/".to_string());
// Level outside of the url.
assert!(normalize_path("/..") == "/".to_string());
assert!(normalize_path("/../") == "/".to_string());
// Going into negative levels and coming back into the positives.
assert!(
normalize_path("/one/../../two/three") == "/two/three".to_string()
);
assert!(
normalize_path("/one/../../two/three/")
== "/two/three/".to_string()
);
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/router/src/reactive.rs | router/src/reactive.rs | use crate::{
location::Location,
matching::Params,
route::MatchedRoute,
router::{FallbackOrView, Router},
static_render::StaticDataMap,
PathSegment, RouteList, RouteListing, SsrMode,
};
use reactive_graph::{
memo::Memo,
signal::ArcRwSignal,
traits::{SignalGet, SignalSet, SignalWith, Track},
untrack, Owner,
};
use std::{marker::PhantomData, mem};
use tachydom::{
hydration::Cursor,
log,
renderer::Renderer,
ssr::StreamBuilder,
view::{Mountable, Position, PositionState, Render, RenderHtml},
};
#[allow(non_snake_case)]
pub fn ReactiveRouter<Rndr, Loc, DefFn, Defs, FallbackFn, Fallback>(
mut location: Loc,
routes: DefFn,
fallback: FallbackFn,
) -> impl RenderHtml
where
DefFn: Fn() -> Defs + 'static,
Defs: 'static,
Loc: Location + Clone + 'static,
Rndr: Renderer + 'static,
Rndr::Element: Clone,
Rndr::Node: Clone,
FallbackFn: Fn() -> Fallback + Clone + 'static,
Fallback: Render + 'static,
Router<Rndr, Loc, Defs, FallbackFn>: FallbackOrView,
<Router<Rndr, Loc, Defs, FallbackFn> as FallbackOrView>::Output: RenderHtml,
{
// create a reactive URL signal that will drive the router view
let url = ArcRwSignal::new(location.try_to_url().unwrap_or_default());
// initialize the location service with a router hook that will update
// this URL signal
location.set_navigation_hook({
let url = url.clone();
move |new_url| {
tachydom::log(&format!("setting url to {new_url:?}"));
url.set(new_url)
}
});
location.init();
// return a reactive router that will update if and only if the URL signal changes
let owner = Owner::current().unwrap();
move || {
url.track();
ReactiveRouterInner {
owner: owner.clone(),
inner: Router::new(location.clone(), routes(), fallback.clone()),
fal: PhantomData,
}
}
}
struct ReactiveRouterInner<Rndr, Loc, Defs, FallbackFn, Fallback>
where
Rndr: Renderer,
{
owner: Owner,
inner: Router<Rndr, Loc, Defs, FallbackFn>,
fal: PhantomData<Fallback>,
}
impl<Rndr, Loc, Defs, FallbackFn, Fallback> Render
for ReactiveRouterInner<Rndr, Loc, Defs, FallbackFn, Fallback>
where
Loc: Location,
Rndr: Renderer,
Rndr::Element: Clone,
Rndr::Node: Clone,
FallbackFn: Fn() -> Fallback,
Fallback: Render,
Router<Rndr, Loc, Defs, FallbackFn>: FallbackOrView,
<Router<Rndr, Loc, Defs, FallbackFn> as FallbackOrView>::Output: Render,
{
type State =
ReactiveRouterInnerState<Rndr, Loc, Defs, FallbackFn, Fallback>;
fn build(self) -> Self::State {
let (prev_id, inner) = self.inner.fallback_or_view();
let owner = self.owner.with(Owner::new);
ReactiveRouterInnerState {
inner: owner.with(|| inner.build()),
owner,
prev_id,
fal: PhantomData,
}
}
fn rebuild(self, state: &mut Self::State) {
let (new_id, view) = self.inner.fallback_or_view();
if new_id != state.prev_id {
state.owner = self.owner.with(Owner::new)
// previous root is dropped here -- TODO check if that's correct or should wait
};
state.owner.with(|| view.rebuild(&mut state.inner));
}
}
impl<Rndr, Loc, Defs, FallbackFn, Fallback> RenderHtml
for ReactiveRouterInner<Rndr, Loc, Defs, FallbackFn, Fallback>
where
Loc: Location,
Rndr: Renderer,
Rndr::Element: Clone,
Rndr::Node: Clone,
FallbackFn: Fn() -> Fallback,
Fallback: Render,
Router<Rndr, Loc, Defs, FallbackFn>: FallbackOrView,
<Router<Rndr, Loc, Defs, FallbackFn> as FallbackOrView>::Output: RenderHtml,
{
const MIN_LENGTH: usize = <<Router<Rndr, Loc, Defs, FallbackFn> as FallbackOrView>::Output as RenderHtml>::MIN_LENGTH;
fn to_html_with_buf(
self,
buf: &mut String,
position: &mut Position,
escape: bool,
mark_branches: bool, extra_attrs: Vec<AnyAttribute>) {
// if this is being run on the server for the first time, generating all possible routes
if RouteList::is_generating() {
let mut routes = RouteList::new();
// add routes
self.inner.generate_route_list(&mut routes);
// add fallback
routes.push(RouteListing::from_path([PathSegment::Static(
"".into(),
)]));
RouteList::register(routes);
} else {
let (id, view) = self.inner.fallback_or_view();
view.to_html_with_buf(buf, position, escape)
}
}
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.inner
.fallback_or_view()
.1
.to_html_async_with_buf::<OUT_OF_ORDER>(buf, position, escape)
}
fn hydrate<const FROM_SERVER: bool>(
self,
cursor: &Cursor,
position: &PositionState,
) -> Self::State {
let (prev_id, inner) = self.inner.fallback_or_view();
let owner = self.owner.with(Owner::new);
ReactiveRouterInnerState {
inner: owner
.with(|| inner.hydrate::<FROM_SERVER>(cursor, position)),
owner,
prev_id,
fal: PhantomData,
}
}
}
struct ReactiveRouterInnerState<Rndr, Loc, Defs, FallbackFn, Fallback>
where
Router<Rndr, Loc, Defs, FallbackFn>: FallbackOrView,
<Router<Rndr, Loc, Defs, FallbackFn> as FallbackOrView>::Output: Render,
Rndr: Renderer,
{
owner: Owner,
prev_id: &'static str,
inner: <<Router<Rndr, Loc, Defs, FallbackFn> as FallbackOrView>::Output as Render>::State,
fal: PhantomData<Fallback>,
}
impl<Rndr, Loc, Defs, FallbackFn, Fallback> Mountable
for ReactiveRouterInnerState<Rndr, Loc, Defs, FallbackFn, Fallback>
where
Router<Rndr, Loc, Defs, FallbackFn>: FallbackOrView,
<Router<Rndr, Loc, Defs, FallbackFn> as FallbackOrView>::Output: Render,
Rndr: Renderer,
{
fn unmount(&mut self) {
self.inner.unmount();
}
fn mount(
&mut self,
parent: &leptos::tachys::renderer::types::Element,
marker: Option<&leptos::tachys::renderer::types::Node>,
) {
self.inner.mount(parent, marker);
}
fn insert_before_this(&self, child: &mut dyn Mountable) -> bool {
self.inner.insert_before_this(child)
}
}
pub struct ReactiveMatchedRoute {
pub(crate) search_params: ArcRwSignal<Params<String>>,
pub(crate) params: ArcRwSignal<Params<&'static str>>,
pub(crate) matched: ArcRwSignal<String>,
}
impl ReactiveMatchedRoute {
pub fn param(&self, key: &str) -> Memo<Option<String>> {
let params = self.params.clone();
let key = key.to_owned();
Memo::new(move |_| {
params.with(|p| {
p.iter().find(|n| n.0 == key).map(|(_, v)| v.to_string())
})
})
}
pub fn search(&self, key: &str) -> Memo<Option<String>> {
let params = self.search_params.clone();
let key = key.to_owned();
Memo::new(move |_| {
params.with(|p| {
p.iter().find(|n| n.0 == key).map(|(_, v)| v.to_string())
})
})
}
}
pub fn reactive_route<ViewFn, View>(
view_fn: ViewFn,
) -> impl Fn(MatchedRoute) -> ReactiveRoute<ViewFn, View>
where
ViewFn: Fn(&ReactiveMatchedRoute) -> View + Clone,
View: Render,
Rndr: Renderer,
{
move |matched| ReactiveRoute {
view_fn: view_fn.clone(),
matched,
ty: PhantomData,
}
}
pub struct ReactiveRoute<ViewFn, View>
where
ViewFn: Fn(&ReactiveMatchedRoute) -> View,
View: Render,
Rndr: Renderer,
{
view_fn: ViewFn,
matched: MatchedRoute,
ty: PhantomData,
}
impl<ViewFn, View> Render for ReactiveRoute<ViewFn, View>
where
ViewFn: Fn(&ReactiveMatchedRoute) -> View,
View: Render,
Rndr: Renderer,
{
type State = ReactiveRouteState<View::State>;
fn build(self) -> Self::State {
let MatchedRoute {
search_params,
params,
matched,
} = self.matched;
let matched = ReactiveMatchedRoute {
search_params: ArcRwSignal::new(search_params),
params: ArcRwSignal::new(params),
matched: ArcRwSignal::new(matched),
};
let view_state = untrack(|| (self.view_fn)(&matched).build());
ReactiveRouteState {
matched,
view_state,
}
}
fn rebuild(mut self, state: &mut Self::State) {
let ReactiveRouteState { matched, .. } = state;
matched
.search_params
.set(mem::take(&mut self.matched.search_params));
matched.params.set(mem::take(&mut self.matched.params));
matched.matched.set(mem::take(&mut self.matched.matched));
}
}
impl<ViewFn, View> RenderHtml for ReactiveRoute<ViewFn, View>
where
ViewFn: Fn(&ReactiveMatchedRoute) -> View,
View: RenderHtml,
Rndr: Renderer,
Rndr::Node: Clone,
Rndr::Element: Clone,
{
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>) {
let MatchedRoute {
search_params,
params,
matched,
} = self.matched;
let matched = ReactiveMatchedRoute {
search_params: ArcRwSignal::new(search_params),
params: ArcRwSignal::new(params),
matched: ArcRwSignal::new(matched),
};
untrack(|| {
(self.view_fn)(&matched).to_html_with_buf(buf, position, escape)
});
}
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 MatchedRoute {
search_params,
params,
matched,
} = self.matched;
let matched = ReactiveMatchedRoute {
search_params: ArcRwSignal::new(search_params),
params: ArcRwSignal::new(params),
matched: ArcRwSignal::new(matched),
};
untrack(|| {
(self.view_fn)(&matched)
.to_html_async_with_buf::<OUT_OF_ORDER>(buf, position, escape)
});
}
fn hydrate<const FROM_SERVER: bool>(
self,
cursor: &Cursor,
position: &PositionState,
) -> Self::State {
let MatchedRoute {
search_params,
params,
matched,
} = self.matched;
let matched = ReactiveMatchedRoute {
search_params: ArcRwSignal::new(search_params),
params: ArcRwSignal::new(params),
matched: ArcRwSignal::new(matched),
};
let view_state = untrack(|| {
(self.view_fn)(&matched).hydrate::<FROM_SERVER>(cursor, position)
});
ReactiveRouteState {
matched,
view_state,
}
}
}
pub struct ReactiveRouteState<State> {
view_state: State,
matched: ReactiveMatchedRoute,
}
impl<State> Drop for ReactiveRouteState<State> {
fn drop(&mut self) {
log("dropping ReactiveRouteState");
}
}
impl<T> Mountable for ReactiveRouteState<T>
where
T: Mountable,
{
fn unmount(&mut self) {
self.view_state.unmount();
}
fn mount(
&mut self,
parent: &<R as Renderer>::Element,
marker: Option<&<R as Renderer>::Node>,
) {
self.view_state.mount(parent, marker);
}
fn insert_before_this(&self, child: &mut dyn Mountable) -> bool {
self.view_state.insert_before_this(child)
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/router/src/lib.rs | router/src/lib.rs | //! # Leptos Router
//!
//! Leptos Router is a router and state management tool for web applications
//! written in Rust using the Leptos web framework.
//! It is ”isomorphic”, i.e., it can be used for client-side applications/single-page
//! apps (SPAs), server-side rendering/multi-page apps (MPAs), or to synchronize
//! state between the two.
//!
//! ## Philosophy
//!
//! Leptos Router is built on a few simple principles:
//! 1. **URL drives state.** For web applications, the URL should be the ultimate
//! source of truth for most of your app’s state. (It’s called a **Universal
//! Resource Locator** for a reason!)
//!
//! 2. **Nested routing.** A URL can match multiple routes that exist in a nested tree
//! and are rendered by different components. This means you can navigate between siblings
//! in this tree without re-rendering or triggering any change in the parent routes.
//!
//! 3. **Progressive enhancement.** The [`A`](crate::components::A) and
//! [`Form`](crate::components::Form) components resolve any relative
//! nested routes, render actual `<a>` and `<form>` elements, and (when possible)
//! upgrading them to handle those navigations with client-side routing. If you’re using
//! them with server-side rendering (with or without hydration), they just work,
//! whether JS/WASM have loaded or not.
//!
//! ## Example
//!
//! ```rust
//! use leptos::prelude::*;
//! use leptos_router::components::*;
//! use leptos_router::path;
//! use leptos_router::hooks::use_params_map;
//!
//! #[component]
//! pub fn RouterExample() -> impl IntoView {
//! view! {
//!
//! <div id="root">
//! // we wrap the whole app in a <Router/> to allow client-side navigation
//! // from our nav links below
//! <Router>
//! <main>
//! // <Routes/> both defines our routes and shows them on the page
//! <Routes fallback=|| "Not found.">
//! // our root route: the contact list is always shown
//! <ParentRoute
//! path=path!("")
//! view=ContactList
//! >
//! // users like /gbj or /bob
//! <Route
//! path=path!(":id")
//! view=Contact
//! />
//! // a fallback if the /:id segment is missing from the URL
//! <Route
//! path=path!("")
//! view=move || view! { <p class="contact">"Select a contact."</p> }
//! />
//! </ParentRoute>
//! </Routes>
//! </main>
//! </Router>
//! </div>
//! }
//! }
//!
//! type ContactSummary = (); // TODO!
//! type Contact = (); // TODO!()
//!
//! // contact_data reruns whenever the :id param changes
//! async fn contact_data(id: String) -> Contact {
//! todo!()
//! }
//!
//! // contact_list_data *doesn't* rerun when the :id changes,
//! // because that param is nested lower than the <ContactList/> route
//! async fn contact_list_data() -> Vec<ContactSummary> {
//! todo!()
//! }
//!
//! #[component]
//! fn ContactList() -> impl IntoView {
//! // loads the contact list data once; doesn't reload when nested routes change
//! let contacts = Resource::new(|| (), |_| contact_list_data());
//! view! {
//!
//! <div>
//! // show the contacts
//! <ul>
//! {move || contacts.get().map(|contacts| view! { <li>"todo contact info"</li> } )}
//! </ul>
//!
//! // insert the nested child route here
//! <Outlet/>
//! </div>
//! }
//! }
//!
//! #[component]
//! fn Contact() -> impl IntoView {
//! let params = use_params_map();
//! let data = Resource::new(
//! move || params.read().get("id").unwrap_or_default(),
//! move |id| contact_data(id)
//! );
//! // ... return some view
//! }
//! ```
//!
//! You can find examples of additional APIs in the [`router`] example.
//!
//! # Feature Flags
//! - `ssr` Server-side rendering: Generate an HTML string (typically on the server)
//! - `nightly`: On `nightly` Rust, enables the function-call syntax for signal getters and setters.
//! - `tracing`: Enables support for the `tracing` crate.
//!
//! [`Leptos`]: <https://github.com/leptos-rs/leptos>
//! [`router`]: <https://github.com/leptos-rs/leptos/blob/main/examples/router/src/lib.rs>
#![forbid(unsafe_code)]
#![deny(missing_docs)]
#![cfg_attr(all(feature = "nightly", rustc_nightly), feature(auto_traits))]
#![cfg_attr(all(feature = "nightly", rustc_nightly), feature(negative_impls))]
/// Components for route definition and for enhanced links and forms.
pub mod components;
/// An optimized "flat" router without nested routes.
pub mod flat_router;
mod form;
mod generate_route_list;
/// Hooks that can be used to access router state inside your components.
pub mod hooks;
mod link;
/// Utilities for accessing the current location.
pub mod location;
mod matching;
mod method;
mod navigate;
/// A nested router that supports multiple levels of route definitions.
pub mod nested_router;
/// Support for maps of parameters in the path or in the query.
pub mod params;
mod ssr_mode;
/// Support for static routing.
pub mod static_routes;
pub use generate_route_list::*;
#[doc(inline)]
pub use leptos_router_macro::{lazy_route, path};
pub use matching::*;
pub use method::*;
pub use navigate::*;
pub use ssr_mode::*;
pub(crate) mod view_transition {
use js_sys::{Function, Promise, Reflect};
use leptos::leptos_dom::helpers::document;
use wasm_bindgen::{closure::Closure, intern, JsCast, JsValue};
pub fn start_view_transition(
level: u8,
is_back_navigation: bool,
fun: impl FnOnce() + 'static,
) {
let document = document();
let document_element = document.document_element().unwrap();
let class_list = document_element.class_list();
let svt = Reflect::get(
&document,
&JsValue::from_str(intern("startViewTransition")),
)
.and_then(|svt| svt.dyn_into::<Function>());
_ = class_list.add_1(&format!("router-outlet-{level}"));
if is_back_navigation {
_ = class_list.add_1("router-back");
}
match svt {
Ok(svt) => {
let cb = Closure::once_into_js(Box::new(move || {
fun();
}));
match svt.call1(
document.unchecked_ref(),
cb.as_ref().unchecked_ref(),
) {
Ok(view_transition) => {
let class_list = document_element.class_list();
let finished = Reflect::get(
&view_transition,
&JsValue::from_str("finished"),
)
.expect("no `finished` property on ViewTransition")
.unchecked_into::<Promise>();
let cb = Closure::new(Box::new(move |_| {
if is_back_navigation {
class_list.remove_1("router-back").unwrap();
}
class_list
.remove_1(&format!("router-outlet-{level}"))
.unwrap();
})
as Box<dyn FnMut(JsValue)>);
_ = finished.then(&cb);
cb.into_js_value();
}
Err(e) => {
web_sys::console::log_1(&e);
}
}
}
Err(_) => {
leptos::logging::warn!(
"NOTE: View transitions are not supported in this \
browser; unless you provide a polyfill, view transitions \
will not be applied."
);
fun();
}
}
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/router/src/flat_router.rs | router/src/flat_router.rs | use crate::{
hooks::Matched,
location::{LocationProvider, Url},
matching::{MatchParams, RouteDefs},
params::ParamsMap,
view_transition::start_view_transition,
ChooseView, MatchInterface, MatchNestedRoutes, PathSegment, RouteList,
RouteListing, RouteMatchId,
};
use any_spawner::Executor;
use either_of::Either;
use futures::FutureExt;
use leptos::attr::{any_attribute::AnyAttribute, Attribute};
use reactive_graph::{
computed::{ArcMemo, ScopedFuture},
owner::{provide_context, Owner},
signal::ArcRwSignal,
traits::{GetUntracked, ReadUntracked, Set},
transition::AsyncTransition,
wrappers::write::SignalSetter,
};
use std::{cell::RefCell, iter, mem, rc::Rc};
use tachys::{
hydration::Cursor,
reactive_graph::OwnedView,
ssr::StreamBuilder,
view::{
add_attr::AddAnyAttr,
any_view::{AnyView, AnyViewState, IntoAny},
MarkBranch, Mountable, Position, PositionState, Render, RenderHtml,
},
};
pub(crate) struct FlatRoutesView<Loc, Defs, FalFn> {
pub current_url: ArcRwSignal<Url>,
pub location: Option<Loc>,
pub routes: RouteDefs<Defs>,
pub fallback: FalFn,
pub outer_owner: Owner,
pub set_is_routing: Option<SignalSetter<bool>>,
pub transition: bool,
}
/// Retained view state for the flat router.
pub(crate) struct FlatRoutesViewState {
#[allow(clippy::type_complexity)]
view: AnyViewState,
id: Option<RouteMatchId>,
owner: Owner,
params: ArcRwSignal<ParamsMap>,
path: String,
url: ArcRwSignal<Url>,
matched: ArcRwSignal<String>,
}
impl Mountable for FlatRoutesViewState {
fn unmount(&mut self) {
self.view.unmount();
}
fn mount(
&mut self,
parent: &leptos::tachys::renderer::types::Element,
marker: Option<&leptos::tachys::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<tachys::renderer::types::Element> {
self.view.elements()
}
}
impl<Loc, Defs, FalFn, Fal> Render for FlatRoutesView<Loc, Defs, FalFn>
where
Loc: LocationProvider,
Defs: MatchNestedRoutes + 'static,
FalFn: FnOnce() -> Fal + Send,
Fal: IntoAny,
{
type State = Rc<RefCell<FlatRoutesViewState>>;
fn build(self) -> Self::State {
let FlatRoutesView {
current_url,
routes,
fallback,
outer_owner,
..
} = self;
let current_url = current_url.read_untracked();
// we always need to match the new route
let new_match = routes.match_route(current_url.path());
let id = new_match.as_ref().map(|n| n.as_id());
let matched = ArcRwSignal::new(
new_match
.as_ref()
.map(|n| n.as_matched().to_owned())
.unwrap_or_default(),
);
// create default starting points for owner, url, path, and params
// these will be held in state so that future navigations can update or replace them
let owner = outer_owner.child();
let url = ArcRwSignal::new(current_url.to_owned());
let path = current_url.path().to_string();
let params = ArcRwSignal::new(
new_match
.as_ref()
.map(|n| n.to_params().into_iter().collect())
.unwrap_or_default(),
);
let params_memo = ArcMemo::from(params.clone());
// release URL lock
drop(current_url);
match new_match {
None => Rc::new(RefCell::new(FlatRoutesViewState {
view: fallback().into_any().build(),
id,
owner,
params,
path,
url,
matched,
})),
Some(new_match) => {
let (view, child) = new_match.into_view_and_child();
#[cfg(debug_assertions)]
if child.is_some() {
panic!(
"<FlatRoutes> should not be used with nested routes."
);
}
let mut view = Box::pin(owner.with(|| {
provide_context(params_memo);
provide_context(url.clone());
provide_context(Matched(ArcMemo::from(matched.clone())));
ScopedFuture::new(async move {
OwnedView::new(view.choose().await)
})
}));
match view.as_mut().now_or_never() {
Some(view) => Rc::new(RefCell::new(FlatRoutesViewState {
view: view.into_any().build(),
id,
owner,
params,
path,
url,
matched,
})),
None => {
let state =
Rc::new(RefCell::new(FlatRoutesViewState {
view: ().into_any().build(),
id,
owner,
params,
path,
url,
matched,
}));
Executor::spawn_local({
let state = Rc::clone(&state);
async move {
let view = view.await;
view.into_any()
.rebuild(&mut state.borrow_mut().view);
}
});
state
}
}
}
}
}
fn rebuild(self, state: &mut Self::State) {
let FlatRoutesView {
current_url,
location,
routes,
fallback,
outer_owner,
set_is_routing,
transition,
} = self;
let url_snapshot = current_url.read_untracked();
// if the path is the same, we do not need to re-route
// we can just update the search query and go about our day
let mut initial_state = state.borrow_mut();
if url_snapshot.path() == initial_state.path {
initial_state.url.set(url_snapshot.to_owned());
if let Some(location) = location {
location.ready_to_complete();
}
return;
}
// since the path didn't match, we'll update the retained path for future diffing
initial_state.path.clear();
initial_state.path.push_str(url_snapshot.path());
// otherwise, match the new route
let new_match = routes.match_route(url_snapshot.path());
let new_id = new_match.as_ref().map(|n| n.as_id());
let matched_string = new_match
.as_ref()
.map(|n| n.as_matched().to_owned())
.unwrap_or_default();
let matched_params = new_match
.as_ref()
.map(|n| n.to_params().into_iter().collect())
.unwrap_or_default();
// if it's the same route, we just update the params
if new_id == initial_state.id {
initial_state.params.set(matched_params);
initial_state.matched.set(matched_string);
if let Some(location) = location {
location.ready_to_complete();
}
return;
}
// otherwise, we need to update the retained path for diffing
initial_state.id = new_id;
// otherwise, it's a new route, so we'll need to
// 1) create a new owner, URL signal, and params signal
// 2) render the fallback or new route
let owner = outer_owner.child();
let url = ArcRwSignal::new(url_snapshot.to_owned());
let params = ArcRwSignal::new(matched_params);
let params_memo = ArcMemo::from(params.clone());
let old_owner = mem::replace(&mut initial_state.owner, owner.clone());
let old_url = mem::replace(&mut initial_state.url, url.clone());
let old_params =
mem::replace(&mut initial_state.params, params.clone());
let new_matched = ArcRwSignal::new(matched_string);
let old_matched =
mem::replace(&mut initial_state.matched, new_matched.clone());
// we drop the route state here, in case there is a <Redirect/> or similar that occurs
// while rendering either the fallback or the new route
drop(initial_state);
match new_match {
// render fallback
None => {
owner.with(|| {
provide_context(url);
provide_context(params_memo);
provide_context(Matched(ArcMemo::from(new_matched)));
fallback().into_any().rebuild(&mut state.borrow_mut().view)
});
if let Some(location) = location {
location.ready_to_complete();
}
}
Some(new_match) => {
let (view, child) = new_match.into_view_and_child();
#[cfg(debug_assertions)]
if child.is_some() {
panic!(
"<FlatRoutes> should not be used with nested routes."
);
}
let spawned_path = url_snapshot.path().to_string();
let is_back = location
.as_ref()
.map(|nav| nav.is_back().get_untracked())
.unwrap_or(false);
Executor::spawn_local(owner.with(|| {
provide_context(url);
provide_context(params_memo);
provide_context(Matched(ArcMemo::from(new_matched)));
ScopedFuture::new({
let state = Rc::clone(state);
async move {
let view = OwnedView::new(
if let Some(set_is_routing) = set_is_routing {
set_is_routing.set(true);
let value =
AsyncTransition::run(|| view.choose())
.await;
set_is_routing.set(false);
value
} else {
view.choose().await
},
);
// only update the route if it's still the current path
// i.e., if we've navigated away before this has loaded, do nothing
if current_url.read_untracked().path()
== spawned_path
{
let rebuild = move || {
view.into_any()
.rebuild(&mut state.borrow_mut().view);
};
if transition {
start_view_transition(0, is_back, rebuild);
} else {
rebuild();
}
}
if let Some(location) = location {
location.ready_to_complete();
}
drop(old_owner);
drop(old_params);
drop(old_url);
drop(old_matched);
}
})
}));
}
}
}
}
impl<Loc, Defs, FalFn, Fal> AddAnyAttr for FlatRoutesView<Loc, Defs, FalFn>
where
Loc: LocationProvider + Send,
Defs: MatchNestedRoutes + Send + 'static,
FalFn: FnOnce() -> Fal + Send + 'static,
Fal: RenderHtml + 'static,
{
type Output<SomeNewAttr: leptos::attr::Attribute> =
FlatRoutesView<Loc, Defs, FalFn>;
fn add_any_attr<NewAttr: leptos::attr::Attribute>(
self,
_attr: NewAttr,
) -> Self::Output<NewAttr>
where
Self::Output<NewAttr>: RenderHtml,
{
todo!()
}
}
#[derive(Debug)]
pub(crate) struct MatchedRoute(pub String, pub AnyView);
impl MatchedRoute {
fn branch_name(&self) -> String {
format!("{:?}", self.1.as_type_id())
}
}
impl Render for MatchedRoute {
type State = <AnyView as Render>::State;
fn build(self) -> Self::State {
self.1.build()
}
fn rebuild(self, state: &mut Self::State) {
self.1.rebuild(state);
}
}
impl AddAnyAttr for MatchedRoute {
type Output<SomeNewAttr: Attribute> = Self;
fn add_any_attr<NewAttr: Attribute>(
self,
attr: NewAttr,
) -> Self::Output<NewAttr>
where
Self::Output<NewAttr>: RenderHtml,
{
let MatchedRoute(id, view) = self;
MatchedRoute(id, view.add_any_attr(attr).into_any())
}
}
impl RenderHtml for MatchedRoute {
type AsyncOutput = Self;
type Owned = Self;
const MIN_LENGTH: usize = 0;
fn dry_resolve(&mut self) {
self.1.dry_resolve();
}
async fn resolve(self) -> Self::AsyncOutput {
let MatchedRoute(id, view) = self;
let view = view.resolve().await;
MatchedRoute(id, view)
}
fn to_html_with_buf(
self,
buf: &mut String,
position: &mut Position,
escape: bool,
mark_branches: bool,
extra_attrs: Vec<AnyAttribute>,
) {
let branch_name = (mark_branches && escape).then(|| self.branch_name());
if let Some(bn) = &branch_name {
buf.open_branch(bn);
}
self.1.to_html_with_buf(
buf,
position,
escape,
mark_branches,
extra_attrs,
);
if let Some(bn) = &branch_name {
buf.close_branch(bn);
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,
{
let branch_name = (mark_branches && escape).then(|| self.branch_name());
if let Some(bn) = &branch_name {
buf.open_branch(bn);
}
self.1.to_html_async_with_buf::<OUT_OF_ORDER>(
buf,
position,
escape,
mark_branches,
extra_attrs,
);
if let Some(bn) = &branch_name {
buf.close_branch(bn);
if *position == Position::NextChildAfterText {
*position = Position::NextChild;
}
}
}
fn hydrate<const FROM_SERVER: bool>(
self,
cursor: &Cursor,
position: &PositionState,
) -> Self::State {
self.1.hydrate::<FROM_SERVER>(cursor, position)
}
async fn hydrate_async(
self,
cursor: &Cursor,
position: &PositionState,
) -> Self::State {
self.1.hydrate_async(cursor, position).await
}
fn into_owned(self) -> Self::Owned {
self
}
}
impl<Loc, Defs, FalFn, Fal> FlatRoutesView<Loc, Defs, FalFn>
where
Loc: LocationProvider + Send,
Defs: MatchNestedRoutes + Send + 'static,
FalFn: FnOnce() -> Fal + Send,
Fal: RenderHtml + 'static,
{
fn choose_ssr(self) -> OwnedView<AnyView> {
let current_url = self.current_url.read_untracked();
let new_match = self.routes.match_route(current_url.path());
let owner = self.outer_owner.child();
let url = ArcRwSignal::new(current_url.to_owned());
let params = ArcRwSignal::new(
new_match
.as_ref()
.map(|n| n.to_params().into_iter().collect::<ParamsMap>())
.unwrap_or_default(),
);
let matched = ArcRwSignal::new(
new_match
.as_ref()
.map(|n| n.as_matched().to_owned())
.unwrap_or_default(),
);
let params_memo = ArcMemo::from(params.clone());
// release URL lock
drop(current_url);
let view = match new_match {
None => (self.fallback)().into_any(),
Some(new_match) => {
let id = new_match.as_matched().to_string();
let (view, _) = new_match.into_view_and_child();
let view = owner
.with(|| {
provide_context(url);
provide_context(params_memo);
provide_context(Matched(ArcMemo::from(matched)));
ScopedFuture::new(async move { view.choose().await })
})
.now_or_never()
.expect("async route used in SSR");
let view = MatchedRoute(id, view);
view.into_any()
}
};
OwnedView::new_with_owner(view, owner)
}
}
impl<Loc, Defs, FalFn, Fal> RenderHtml for FlatRoutesView<Loc, Defs, FalFn>
where
Loc: LocationProvider + Send,
Defs: MatchNestedRoutes + Send + 'static,
FalFn: FnOnce() -> Fal + Send + 'static,
Fal: RenderHtml + 'static,
{
type AsyncOutput = Self;
type Owned = Self;
const MIN_LENGTH: usize = <Either<Fal, AnyView> as RenderHtml>::MIN_LENGTH;
fn dry_resolve(&mut self) {}
async fn resolve(self) -> Self::AsyncOutput {
self
}
fn to_html_with_buf(
self,
buf: &mut String,
position: &mut Position,
escape: bool,
mark_branches: bool,
extra_attrs: Vec<AnyAttribute>,
) {
// if this is being run on the server for the first time, generating all possible routes
if RouteList::is_generating() {
// add routes
let (base, routes) = self.routes.generate_routes();
let routes = routes
.into_iter()
.map(|data| {
let path = base
.into_iter()
.flat_map(|base| {
iter::once(PathSegment::Static(
base.to_string().into(),
))
})
.chain(data.segments)
.collect::<Vec<_>>();
RouteListing::new(
path,
data.ssr_mode,
data.methods,
data.regenerate,
)
})
.collect::<Vec<_>>();
// add fallback
// TODO fix: causes overlapping route issues on Axum
/*routes.push(RouteListing::new(
[PathSegment::Static(
base.unwrap_or_default().to_string().into(),
)],
SsrMode::Async,
[
Method::Get,
Method::Post,
Method::Put,
Method::Patch,
Method::Delete,
],
None,
));*/
RouteList::register(RouteList::from(routes));
} else {
let view = self.choose_ssr();
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,
{
let view = self.choose_ssr();
view.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 {
let FlatRoutesView {
current_url,
routes,
fallback,
outer_owner,
..
} = self;
let current_url = current_url.read_untracked();
// we always need to match the new route
let new_match = routes.match_route(current_url.path());
let id = new_match.as_ref().map(|n| n.as_id());
let matched = ArcRwSignal::new(
new_match
.as_ref()
.map(|n| n.as_matched().to_owned())
.unwrap_or_default(),
);
// create default starting points for owner, url, path, and params
// these will be held in state so that future navigations can update or replace them
let owner = outer_owner.child();
let url = ArcRwSignal::new(current_url.to_owned());
let path = current_url.path().to_string();
let params = ArcRwSignal::new(
new_match
.as_ref()
.map(|n| n.to_params().into_iter().collect())
.unwrap_or_default(),
);
let params_memo = ArcMemo::from(params.clone());
// release URL lock
drop(current_url);
match new_match {
None => Rc::new(RefCell::new(FlatRoutesViewState {
view: fallback()
.into_any()
.hydrate::<FROM_SERVER>(cursor, position),
id,
owner,
params,
path,
url,
matched,
})),
Some(new_match) => {
let (view, child) = new_match.into_view_and_child();
#[cfg(debug_assertions)]
if child.is_some() {
panic!(
"<FlatRoutes> should not be used with nested routes."
);
}
let mut view = Box::pin(owner.with(|| {
provide_context(params_memo);
provide_context(url.clone());
provide_context(Matched(ArcMemo::from(matched.clone())));
ScopedFuture::new(async move {
OwnedView::new(view.choose().await)
})
}));
match view.as_mut().now_or_never() {
Some(view) => Rc::new(RefCell::new(FlatRoutesViewState {
view: view
.into_any()
.hydrate::<FROM_SERVER>(cursor, position),
id,
owner,
params,
path,
url,
matched,
})),
None => {
panic!(
"lazy routes should not be used with \
hydrate_body(); use hydrate_lazy() instead"
);
}
}
}
}
}
async fn hydrate_async(
self,
cursor: &Cursor,
position: &PositionState,
) -> Self::State {
let FlatRoutesView {
current_url,
routes,
fallback,
outer_owner,
..
} = self;
let current_url = current_url.read_untracked();
// we always need to match the new route
let new_match = routes.match_route(current_url.path());
let id = new_match.as_ref().map(|n| n.as_id());
let matched = ArcRwSignal::new(
new_match
.as_ref()
.map(|n| n.as_matched().to_owned())
.unwrap_or_default(),
);
// create default starting points for owner, url, path, and params
// these will be held in state so that future navigations can update or replace them
let owner = outer_owner.child();
let url = ArcRwSignal::new(current_url.to_owned());
let path = current_url.path().to_string();
let params = ArcRwSignal::new(
new_match
.as_ref()
.map(|n| n.to_params().into_iter().collect())
.unwrap_or_default(),
);
let params_memo = ArcMemo::from(params.clone());
// release URL lock
drop(current_url);
match new_match {
None => Rc::new(RefCell::new(FlatRoutesViewState {
view: fallback()
.into_any()
.hydrate_async(cursor, position)
.await,
id,
owner,
params,
path,
url,
matched,
})),
Some(new_match) => {
let (view, child) = new_match.into_view_and_child();
#[cfg(debug_assertions)]
if child.is_some() {
panic!(
"<FlatRoutes> should not be used with nested routes."
);
}
let view = Box::pin(owner.with(|| {
provide_context(params_memo);
provide_context(url.clone());
provide_context(Matched(ArcMemo::from(matched.clone())));
ScopedFuture::new(async move {
OwnedView::new(view.choose().await)
})
}));
let view = view.await;
Rc::new(RefCell::new(FlatRoutesViewState {
view: view.into_any().hydrate_async(cursor, position).await,
id,
owner,
params,
path,
url,
matched,
}))
}
}
}
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/src/params.rs | router/src/params.rs | use crate::location::Url;
use std::{borrow::Cow, str::FromStr, sync::Arc};
use thiserror::Error;
type ParamsMapInner = Vec<(Cow<'static, str>, Vec<String>)>;
/// A key-value map of the current named route params and their values.
#[derive(Debug, Default, Clone, PartialEq, Eq, Hash)]
pub struct ParamsMap(ParamsMapInner);
impl ParamsMap {
/// Creates an empty map.
#[inline(always)]
pub fn new() -> Self {
Self::default()
}
/// Creates an empty map with the given capacity.
#[inline(always)]
pub fn with_capacity(capacity: usize) -> Self {
Self(Vec::with_capacity(capacity))
}
/// Inserts a value into the map.
///
/// If a value with that key already exists, the new value will be added to it.
/// To replace the value instead, see [`replace`](Self::replace).
pub fn insert(&mut self, key: impl Into<Cow<'static, str>>, value: String) {
let value = Url::unescape(&value);
let key = key.into();
if let Some(prev) = self.0.iter_mut().find(|(k, _)| k == &key) {
prev.1.push(value);
} else {
self.0.push((key, vec![value]));
}
}
/// Inserts a value into the map, replacing any existing value for that key.
pub fn replace(
&mut self,
key: impl Into<Cow<'static, str>>,
value: String,
) {
let value = Url::unescape(&value);
let key = key.into();
if let Some(prev) = self.0.iter_mut().find(|(k, _)| k == &key) {
prev.1.clear();
prev.1.push(value);
} else {
self.0.push((key, vec![value]));
}
}
/// Gets the most-recently-added value of this param from the map.
pub fn get(&self, key: &str) -> Option<String> {
self.get_str(key).map(ToOwned::to_owned)
}
/// Gets all references to a param of this name from the map.
pub fn get_all(&self, key: &str) -> Option<Vec<String>> {
self.0
.iter()
.find_map(|(k, v)| if k == key { Some(v.clone()) } else { None })
}
/// Gets a reference to the most-recently-added value of this param from the map.
pub fn get_str(&self, key: &str) -> Option<&str> {
self.0.iter().find_map(|(k, v)| {
if k == key {
v.last().map(|i| i.as_str())
} else {
None
}
})
}
/// Removes a value from the map.
#[inline(always)]
pub fn remove(&mut self, key: &str) -> Option<Vec<String>> {
for i in 0..self.0.len() {
if self.0[i].0 == key {
return Some(self.0.swap_remove(i).1);
}
}
None
}
/// Converts the map to a query string.
pub fn to_query_string(&self) -> String {
let mut buf = String::new();
if !self.0.is_empty() {
buf.push('?');
for (k, vs) in &self.0 {
for v in vs {
buf.push_str(&Url::escape(k));
buf.push('=');
buf.push_str(&Url::escape(v));
buf.push('&');
}
}
if buf.len() > 1 {
buf.pop();
}
}
buf
}
}
impl<K, V> FromIterator<(K, V)> for ParamsMap
where
K: Into<Cow<'static, str>>,
V: Into<String>,
{
fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self {
let mut map = Self::new();
for (key, value) in iter {
map.insert(key, value.into());
}
map
}
}
impl IntoIterator for ParamsMap {
type Item = (Cow<'static, str>, String);
type IntoIter = ParamsMapIter;
fn into_iter(self) -> Self::IntoIter {
let inner = self.0.into_iter().fold(vec![], |mut c, (k, vs)| {
for v in vs {
c.push((k.clone(), v));
}
c
});
ParamsMapIter(inner.into_iter())
}
}
/// An iterator over the keys and values of a [`ParamsMap`].
#[derive(Debug)]
pub struct ParamsMapIter(
<Vec<(Cow<'static, str>, String)> as IntoIterator>::IntoIter,
);
impl Iterator for ParamsMapIter {
type Item = (Cow<'static, str>, String);
fn next(&mut self) -> Option<Self::Item> {
self.0.next()
}
}
/// A simple method of deserializing key-value data (like route params or URL search)
/// into a concrete data type. `Self` should typically be a struct in which
/// each field's type implements [`FromStr`].
pub trait Params
where
Self: Sized,
{
/// Attempts to deserialize the map into the given type.
fn from_map(map: &ParamsMap) -> Result<Self, ParamsError>;
}
impl Params for () {
#[inline(always)]
fn from_map(_map: &ParamsMap) -> Result<Self, ParamsError> {
Ok(())
}
}
/// Converts some parameter value from the URL into a typed parameter with the given name.
pub trait IntoParam
where
Self: Sized,
{
/// Converts the param.
fn into_param(value: Option<&str>, name: &str)
-> Result<Self, ParamsError>;
}
impl<T> IntoParam for Option<T>
where
T: FromStr,
<T as FromStr>::Err: std::error::Error + Send + Sync + 'static,
{
fn into_param(
value: Option<&str>,
_name: &str,
) -> Result<Self, ParamsError> {
match value {
None => Ok(None),
Some(value) => match T::from_str(value) {
Ok(value) => Ok(Some(value)),
Err(e) => Err(ParamsError::Params(Arc::new(e))),
},
}
}
}
/// Helpers for the `Params` derive macro to allow specialization without nightly.
pub mod macro_helpers {
use crate::params::{IntoParam, ParamsError};
use std::{str::FromStr, sync::Arc};
/// This struct is never actually created; it just exists so that we can impl associated
/// functions on it.
pub struct Wrapper<T>(T);
impl<T: IntoParam> Wrapper<T> {
/// This is the 'preferred' impl to be used for all `T` that implement `IntoParam`.
/// Because it is directly on the struct, the compiler will pick this over the impl from
/// the `Fallback` trait.
#[inline]
pub fn __into_param(
value: Option<&str>,
name: &str,
) -> Result<T, ParamsError> {
T::into_param(value, name)
}
}
/// If the Fallback trait is in scope, then the compiler has two possible implementations for
/// `__into_params`. It will pick the one from this trait if the inherent one doesn't exist.
/// (which it won't if `T` does not implement `IntoParam`)
pub trait Fallback<T>: Sized
where
T: FromStr,
<T as FromStr>::Err: std::error::Error + Send + Sync + 'static,
{
/// Fallback function in case the inherent impl on the Wrapper struct does not exist for
/// `T`
#[inline]
fn __into_param(
value: Option<&str>,
name: &str,
) -> Result<T, ParamsError> {
let value = value
.ok_or_else(|| ParamsError::MissingParam(name.to_string()))?;
T::from_str(value).map_err(|e| ParamsError::Params(Arc::new(e)))
}
}
impl<T> Fallback<T> for Wrapper<T>
where
T: FromStr,
<T as FromStr>::Err: std::error::Error + Send + Sync + 'static,
{
}
}
/// Errors that can occur while parsing params using [`Params`].
#[derive(Error, Debug, Clone)]
pub enum ParamsError {
/// A field was missing from the route params.
#[error("could not find parameter {0}")]
MissingParam(String),
/// Something went wrong while deserializing a field.
#[error("failed to deserialize parameters")]
Params(Arc<dyn std::error::Error + Send + Sync>),
}
impl PartialEq for ParamsError {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Self::MissingParam(l0), Self::MissingParam(r0)) => l0 == r0,
(Self::Params(_), Self::Params(_)) => false,
_ => false,
}
}
}
#[cfg(all(test, feature = "ssr"))]
mod tests {
use super::*;
#[test]
fn paramsmap_to_query_string() {
let mut map = ParamsMap::new();
let key = "param".to_string();
let value1 = "a".to_string();
let value2 = "b".to_string();
map.insert(key.clone(), value1);
map.insert(key, value2);
let query_string = map.to_query_string();
assert_eq!(&query_string, "?param=a¶m=b")
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/router/src/generate_route_list.rs | router/src/generate_route_list.rs | use crate::{
matching::PathSegment,
static_routes::{
RegenerationFn, ResolvedStaticPath, StaticPath, StaticRoute,
},
Method, SsrMode,
};
use futures::future::join_all;
use reactive_graph::owner::Owner;
use std::{
cell::{Cell, RefCell},
collections::HashSet,
future::Future,
mem,
};
use tachys::view::RenderHtml;
#[derive(Clone, Debug, Default)]
/// A route that this application can serve.
pub struct RouteListing {
path: Vec<PathSegment>,
mode: SsrMode,
methods: HashSet<Method>,
regenerate: Vec<RegenerationFn>,
}
impl RouteListing {
/// Create a route listing from its parts.
pub fn new(
path: impl IntoIterator<Item = PathSegment>,
mode: SsrMode,
methods: impl IntoIterator<Item = Method>,
regenerate: impl IntoIterator<Item = RegenerationFn>,
) -> Self {
Self {
path: path.into_iter().collect(),
mode,
methods: methods.into_iter().collect(),
regenerate: regenerate.into_iter().collect(),
}
}
/// Create a route listing from a path, with the other fields set to default values.
pub fn from_path(path: impl IntoIterator<Item = PathSegment>) -> Self {
Self::new(path, SsrMode::Async, [], [])
}
/// The path this route handles.
pub fn path(&self) -> &[PathSegment] {
&self.path
}
/// The rendering mode for this path.
pub fn mode(&self) -> &SsrMode {
&self.mode
}
/// The HTTP request methods this path can handle.
pub fn methods(&self) -> impl Iterator<Item = Method> + '_ {
self.methods.iter().copied()
}
/// The set of regeneration functions that should be applied to this route, if it is statically
/// generated (either up front or incrementally).
pub fn regenerate(&self) -> &[RegenerationFn] {
&self.regenerate
}
/// Whether this route is statically rendered.
#[inline(always)]
pub fn static_route(&self) -> Option<&StaticRoute> {
match self.mode {
SsrMode::Static(ref route) => Some(route),
_ => None,
}
}
/// Generates the set of static paths for this route listing, depending on prerendered params.
pub async fn into_static_paths(self) -> Option<Vec<ResolvedStaticPath>> {
let params = self.static_route()?.to_prerendered_params().await;
Some(StaticPath::new(self.path).into_paths(params))
}
/// Generates static files for this route listing.
pub async fn generate_static_files<Fut, WriterFut>(
mut self,
render_fn: impl Fn(&ResolvedStaticPath) -> Fut + Send + Clone + 'static,
writer: impl Fn(&ResolvedStaticPath, &Owner, String) -> WriterFut
+ Send
+ Clone
+ 'static,
was_404: impl Fn(&Owner) -> bool + Send + Clone + 'static,
) where
Fut: Future<Output = (Owner, String)> + Send + 'static,
WriterFut: Future<Output = Result<(), std::io::Error>> + Send + 'static,
{
if let SsrMode::Static(_) = self.mode() {
let (all_initial_tx, all_initial_rx) = std::sync::mpsc::channel();
let render_fn = render_fn.clone();
let regenerate = mem::take(&mut self.regenerate);
let paths = self.into_static_paths().await.unwrap_or_default();
for path in paths {
// Err(_) here would just mean they've dropped the rx and are no longer awaiting
// it; we're only using it to notify them it's done so it doesn't matter in that
// case
_ = all_initial_tx.send(path.build(
render_fn.clone(),
writer.clone(),
was_404.clone(),
regenerate.clone(),
));
}
join_all(all_initial_rx.try_iter()).await;
}
}
/*
/// Build a route statically, will return `Ok(true)` on success or `Ok(false)` when the route
/// is not marked as statically rendered. All route parameters to use when resolving all paths
/// to render should be passed in the `params` argument.
pub async fn build_static<IV>(
&self,
options: &LeptosOptions,
app_fn: impl Fn() -> IV + Send + 'static + Clone,
additional_context: impl Fn() + Send + 'static + Clone,
params: &StaticParamsMap,
) -> Result<bool, std::io::Error>
where
IV: IntoView + 'static,
{
match self.mode {
SsrMode::Static(route) => {
let mut path = StaticPath::new(self.path.clone());
for path in path.into_paths(params) {
/*path.write(
options,
app_fn.clone(),
additional_context.clone(),
)
.await?;*/ println!()
}
Ok(true)
}
_ => Ok(false),
}
}
*/
}
/// A set of routes generated from the route definitions.
#[derive(Debug, Default, Clone)]
pub struct RouteList(Vec<RouteListing>);
impl From<Vec<RouteListing>> for RouteList {
fn from(value: Vec<RouteListing>) -> Self {
Self(value)
}
}
impl RouteList {
/// Adds a route listing.
pub fn push(&mut self, data: RouteListing) {
self.0.push(data);
}
}
impl RouteList {
/// Creates an empty list of routes.
pub fn new() -> Self {
Self(Vec::new())
}
/// Returns the list of routes.
pub fn into_inner(self) -> Vec<RouteListing> {
self.0
}
/// Returns and iterator over the list of routes.
pub fn iter(&self) -> impl Iterator<Item = &RouteListing> {
self.0.iter()
}
/// Generates a list of resolved static paths based on the inner list of route listings.
pub async fn into_static_paths(self) -> Vec<ResolvedStaticPath> {
futures::future::join_all(
self.into_inner()
.into_iter()
.map(|route_listing| route_listing.into_static_paths()),
)
.await
.into_iter()
.flatten()
.flatten()
.collect::<Vec<_>>()
}
/// Generates static files for the inner list of route listings.
pub async fn generate_static_files<Fut, WriterFut>(
self,
render_fn: impl Fn(&ResolvedStaticPath) -> Fut + Send + Clone + 'static,
writer: impl Fn(&ResolvedStaticPath, &Owner, String) -> WriterFut
+ Send
+ Clone
+ 'static,
was_404: impl Fn(&Owner) -> bool + Send + Clone + 'static,
) where
Fut: Future<Output = (Owner, String)> + Send + 'static,
WriterFut: Future<Output = Result<(), std::io::Error>> + Send + 'static,
{
join_all(self.into_inner().into_iter().map(|route| {
route.generate_static_files(
render_fn.clone(),
writer.clone(),
was_404.clone(),
)
}))
.await;
}
}
impl RouteList {
// this is used to indicate to the Router that we are generating
// a RouteList for server path generation
thread_local! {
static IS_GENERATING: Cell<bool> = const { Cell::new(false) };
static GENERATED: RefCell<Option<RouteList>> = const { RefCell::new(None) };
}
/// Creates a list of routes, based on route definitions in the given app.
pub fn generate<T>(app: impl FnOnce() -> T) -> Option<Self>
where
T: RenderHtml,
{
let _resource_guard = leptos::server::SuppressResourceLoad::new();
Self::IS_GENERATING.set(true);
// run the app once, but throw away the HTML
// the router won't actually route, but will fill the listing
_ = app().to_html();
Self::IS_GENERATING.set(false);
Self::GENERATED.take()
}
/// Returns `true` if we are currently in a [`RouteList::generate`] call.
pub fn is_generating() -> bool {
Self::IS_GENERATING.get()
}
/// Sets the given routes as the list of generated routes.
pub fn register(routes: RouteList) {
Self::GENERATED.with(|inner| {
*inner.borrow_mut() = Some(routes);
});
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/router/src/form.rs | router/src/form.rs | use crate::{
components::ToHref,
hooks::{has_router, use_navigate, use_resolved_path},
location::{BrowserUrl, LocationProvider},
NavigateOptions,
};
use leptos::{ev, html::form, logging::*, prelude::*, task::spawn_local};
use std::{error::Error, sync::Arc};
use wasm_bindgen::{JsCast, UnwrapThrowExt};
use web_sys::{FormData, RequestRedirect, Response};
type OnFormData = Arc<dyn Fn(&FormData)>;
type OnResponse = Arc<dyn Fn(&Response)>;
type OnError = Arc<dyn Fn(&gloo_net::Error)>;
/// An HTML [`form`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form) progressively
/// enhanced to use client-side routing.
#[component]
pub fn Form<A>(
/// [`method`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form#attr-method)
/// is the HTTP method to submit the form with (`get` or `post`).
#[prop(optional)]
method: Option<&'static str>,
/// [`action`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form#attr-action)
/// is the URL that processes the form submission. Takes a [`String`], [`&str`], or a reactive
/// function that returns a [`String`].
action: A,
/// [`enctype`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form#attr-enctype)
/// is the MIME type of the form submission if `method` is `post`.
#[prop(optional)]
enctype: Option<String>,
/// A signal that will be incremented whenever the form is submitted with `post`. This can useful
/// for reactively updating a [Resource] or another signal whenever the form has been submitted.
#[prop(optional)]
version: Option<RwSignal<usize>>,
/// A signal that will be set if the form submission ends in an error.
#[prop(optional)]
error: Option<RwSignal<Option<Box<dyn Error + Send + Sync>>>>,
/// A callback will be called with the [`FormData`](web_sys::FormData) when the form is submitted.
#[prop(optional)]
on_form_data: Option<OnFormData>,
/// A callback will be called with the [`Response`](web_sys::Response) the server sends in response
/// to a form submission.
#[prop(optional)]
on_response: Option<OnResponse>,
/// A callback will be called if the attempt to submit the form results in an error.
#[prop(optional)]
on_error: Option<OnError>,
/// Sets whether the page should be scrolled to the top when the form is submitted.
#[prop(optional)]
noscroll: bool,
/// Sets whether the page should replace the current location in the history when the form is submitted.
#[prop(optional)]
replace: bool,
/// Component children; should include the HTML of the form elements.
children: Children,
) -> impl IntoView
where
A: ToHref + Send + Sync + 'static,
{
async fn post_form_data(
action: &str,
form_data: FormData,
) -> Result<gloo_net::http::Response, gloo_net::Error> {
gloo_net::http::Request::post(action)
.header("Accept", "application/json")
.redirect(RequestRedirect::Follow)
.body(form_data)?
.send()
.await
}
async fn post_params(
action: &str,
enctype: &str,
params: web_sys::UrlSearchParams,
) -> Result<gloo_net::http::Response, gloo_net::Error> {
gloo_net::http::Request::post(action)
.header("Accept", "application/json")
.header("Content-Type", enctype)
.redirect(RequestRedirect::Follow)
.body(params)?
.send()
.await
}
fn inner(
has_router: bool,
method: Option<&'static str>,
action: ArcMemo<String>,
enctype: Option<String>,
version: Option<RwSignal<usize>>,
error: Option<RwSignal<Option<Box<dyn Error + Send + Sync>>>>,
on_form_data: Option<OnFormData>,
on_response: Option<OnResponse>,
on_error: Option<OnError>,
children: Children,
noscroll: bool,
replace: bool,
) -> impl IntoView {
let action_version = version;
let navigate = has_router.then(use_navigate);
let on_submit = {
move |ev: web_sys::SubmitEvent| {
let navigate = navigate.clone();
if ev.default_prevented() {
return;
}
let navigate_options = NavigateOptions {
scroll: !noscroll,
replace,
..Default::default()
};
let (form, method, action, enctype) =
extract_form_attributes(&ev);
let form_data =
web_sys::FormData::new_with_form(&form).unwrap_throw();
if let Some(on_form_data) = on_form_data.clone() {
on_form_data(&form_data);
}
let params =
web_sys::UrlSearchParams::new_with_str_sequence_sequence(
&form_data,
)
.unwrap_throw();
// multipart POST (setting Context-Type breaks the request)
if method == "post" && enctype == "multipart/form-data" {
ev.prevent_default();
ev.stop_propagation();
let on_response = on_response.clone();
let on_error = on_error.clone();
spawn_local(async move {
let res = post_form_data(&action, form_data).await;
match res {
Err(e) => {
error!("<Form/> error while POSTing: {e:#?}");
if let Some(on_error) = on_error {
on_error(&e);
}
if let Some(error) = error {
error.try_set(Some(Box::new(e)));
}
}
Ok(resp) => {
let resp = web_sys::Response::from(resp);
if let Some(version) = action_version {
version.update(|n| *n += 1);
}
if let Some(error) = error {
error.try_set(None);
}
if let Some(on_response) = on_response.clone() {
on_response(&resp);
}
// Check all the logical 3xx responses that might
// get returned from a server function
if resp.redirected() {
let resp_url = &resp.url();
match BrowserUrl::parse(resp_url.as_str()) {
Ok(url) => {
if url.origin()
!= current_window_origin()
|| navigate.is_none()
{
_ = window()
.location()
.set_href(
resp_url.as_str(),
);
} else {
#[allow(
clippy::unnecessary_unwrap
)]
let navigate =
navigate.unwrap();
navigate(
&format!(
"{}{}{}",
url.path(),
if url
.search()
.is_empty()
{
""
} else {
"?"
},
url.search(),
),
navigate_options,
)
}
}
Err(e) => warn!("{:?}", e),
}
}
}
}
});
}
// POST
else if method == "post" {
ev.prevent_default();
ev.stop_propagation();
let on_response = on_response.clone();
let on_error = on_error.clone();
spawn_local(async move {
let res = post_params(&action, &enctype, params).await;
match res {
Err(e) => {
error!("<Form/> error while POSTing: {e:#?}");
if let Some(on_error) = on_error {
on_error(&e);
}
if let Some(error) = error {
error.try_set(Some(Box::new(e)));
}
}
Ok(resp) => {
let resp = web_sys::Response::from(resp);
if let Some(version) = action_version {
version.update(|n| *n += 1);
}
if let Some(error) = error {
error.try_set(None);
}
if let Some(on_response) = on_response.clone() {
on_response(&resp);
}
// Check all the logical 3xx responses that might
// get returned from a server function
if resp.redirected() {
let resp_url = &resp.url();
match BrowserUrl::parse(resp_url.as_str()) {
Ok(url) => {
if url.origin()
!= current_window_origin()
|| navigate.is_none()
{
_ = window()
.location()
.set_href(
resp_url.as_str(),
);
} else {
#[allow(
clippy::unnecessary_unwrap
)]
let navigate =
navigate.unwrap();
navigate(
&format!(
"{}{}{}",
url.path(),
if url
.search()
.is_empty()
{
""
} else {
"?"
},
url.search(),
),
navigate_options,
)
}
}
Err(e) => warn!("{:?}", e),
}
}
}
}
});
}
// otherwise, GET
else {
let params =
params.to_string().as_string().unwrap_or_default();
if let Some(navigate) = navigate {
navigate(
&format!("{action}?{params}"),
navigate_options,
);
} else {
_ = window()
.location()
.set_href(&format!("{action}?{params}"));
}
ev.prevent_default();
ev.stop_propagation();
}
}
};
let method = method.unwrap_or("get");
form()
.attr("method", method)
.attr("action", move || action.get())
.attr("enctype", enctype)
.on(ev::submit, on_submit)
.child(children())
}
let has_router = has_router();
let action = if has_router {
use_resolved_path(move || action.to_href()())
} else {
ArcMemo::new(move |_| action.to_href()())
};
inner(
has_router,
method,
action,
enctype,
version,
error,
on_form_data,
on_response,
on_error,
children,
noscroll,
replace,
)
}
fn current_window_origin() -> String {
let location = window().location();
let protocol = location.protocol().unwrap_or_default();
let hostname = location.hostname().unwrap_or_default();
let port = location.port().unwrap_or_default();
format!(
"{}//{}{}{}",
protocol,
hostname,
if port.is_empty() { "" } else { ":" },
port
)
}
fn extract_form_attributes(
ev: &web_sys::Event,
) -> (web_sys::HtmlFormElement, String, String, String) {
let submitter = ev.unchecked_ref::<web_sys::SubmitEvent>().submitter();
match &submitter {
Some(el) => {
if let Some(form) = el.dyn_ref::<web_sys::HtmlFormElement>() {
(
form.clone(),
form.get_attribute("method")
.unwrap_or_else(|| "get".to_string())
.to_lowercase(),
form.get_attribute("action")
.unwrap_or_default()
.to_lowercase(),
form.get_attribute("enctype")
.unwrap_or_else(|| {
"application/x-www-form-urlencoded".to_string()
})
.to_lowercase(),
)
} else if let Some(input) =
el.dyn_ref::<web_sys::HtmlInputElement>()
{
let form = ev
.target()
.unwrap()
.unchecked_into::<web_sys::HtmlFormElement>();
(
form.clone(),
input.get_attribute("method").unwrap_or_else(|| {
form.get_attribute("method")
.unwrap_or_else(|| "get".to_string())
.to_lowercase()
}),
input.get_attribute("action").unwrap_or_else(|| {
form.get_attribute("action")
.unwrap_or_default()
.to_lowercase()
}),
input.get_attribute("enctype").unwrap_or_else(|| {
form.get_attribute("enctype")
.unwrap_or_else(|| {
"application/x-www-form-urlencoded".to_string()
})
.to_lowercase()
}),
)
} else if let Some(button) =
el.dyn_ref::<web_sys::HtmlButtonElement>()
{
let form = ev
.target()
.unwrap()
.unchecked_into::<web_sys::HtmlFormElement>();
(
form.clone(),
button.get_attribute("method").unwrap_or_else(|| {
form.get_attribute("method")
.unwrap_or_else(|| "get".to_string())
.to_lowercase()
}),
button.get_attribute("action").unwrap_or_else(|| {
form.get_attribute("action")
.unwrap_or_default()
.to_lowercase()
}),
button.get_attribute("enctype").unwrap_or_else(|| {
form.get_attribute("enctype")
.unwrap_or_else(|| {
"application/x-www-form-urlencoded".to_string()
})
.to_lowercase()
}),
)
} else {
leptos::logging::debug_warn!(
"<Form/> cannot be submitted from a tag other than \
<form>, <input>, or <button>"
);
panic!()
}
}
None => match ev.target() {
None => {
leptos::logging::debug_warn!(
"<Form/> SubmitEvent fired without a target."
);
panic!()
}
Some(form) => {
let form = form.unchecked_into::<web_sys::HtmlFormElement>();
(
form.clone(),
form.get_attribute("method")
.unwrap_or_else(|| "get".to_string()),
form.get_attribute("action").unwrap_or_default(),
form.get_attribute("enctype").unwrap_or_else(|| {
"application/x-www-form-urlencoded".to_string()
}),
)
}
},
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/router/src/hooks.rs | router/src/hooks.rs | use crate::{
components::RouterContext,
location::{Location, Url},
navigate::NavigateOptions,
params::{Params, ParamsError, ParamsMap},
};
use leptos::{leptos_dom::helpers::request_animation_frame, oco::Oco};
use reactive_graph::{
computed::{ArcMemo, Memo},
owner::{expect_context, use_context},
signal::{ArcRwSignal, ReadSignal},
traits::{Get, GetUntracked, ReadUntracked, With, WriteValue},
wrappers::write::SignalSetter,
};
use std::{
str::FromStr,
sync::atomic::{AtomicBool, Ordering},
};
/// See [`query_signal`].
#[track_caller]
#[deprecated = "This has been renamed to `query_signal` to match Rust naming \
conventions."]
pub fn create_query_signal<T>(
key: impl Into<Oco<'static, str>>,
) -> (Memo<Option<T>>, SignalSetter<Option<T>>)
where
T: FromStr + ToString + PartialEq + Send + Sync,
{
query_signal(key)
}
/// See [`query_signal_with_options`].
#[track_caller]
#[deprecated = "This has been renamed to `query_signal_with_options` to mtch \
Rust naming conventions."]
pub fn create_query_signal_with_options<T>(
key: impl Into<Oco<'static, str>>,
nav_options: NavigateOptions,
) -> (Memo<Option<T>>, SignalSetter<Option<T>>)
where
T: FromStr + ToString + PartialEq + Send + Sync,
{
query_signal_with_options(key, nav_options)
}
/// Constructs a signal synchronized with a specific URL query parameter.
///
/// The function creates a bidirectional sync mechanism between the state encapsulated in a signal and a URL query parameter.
/// This means that any change to the state will update the URL, and vice versa, making the function especially useful
/// for maintaining state consistency across page reloads.
///
/// The `key` argument is the unique identifier for the query parameter to be synced with the state.
/// It is important to note that only one state can be tied to a specific key at any given time.
///
/// The function operates with types that can be parsed from and formatted into strings, denoted by `T`.
/// If the parsing fails for any reason, the function treats the value as `None`.
/// The URL parameter can be cleared by setting the signal to `None`.
///
/// ```rust
/// use leptos::prelude::*;
/// use leptos_router::hooks::query_signal;
///
/// #[component]
/// pub fn SimpleQueryCounter() -> impl IntoView {
/// let (count, set_count) = query_signal::<i32>("count");
/// let clear = move |_| set_count.set(None);
/// let decrement =
/// move |_| set_count.set(Some(count.get().unwrap_or(0) - 1));
/// let increment =
/// move |_| set_count.set(Some(count.get().unwrap_or(0) + 1));
///
/// view! {
/// <div>
/// <button on:click=clear>"Clear"</button>
/// <button on:click=decrement>"-1"</button>
/// <span>"Value: " {move || count.get().unwrap_or(0)} "!"</span>
/// <button on:click=increment>"+1"</button>
/// </div>
/// }
/// }
/// ```
#[track_caller]
pub fn query_signal<T>(
key: impl Into<Oco<'static, str>>,
) -> (Memo<Option<T>>, SignalSetter<Option<T>>)
where
T: FromStr + ToString + PartialEq + Send + Sync,
{
query_signal_with_options::<T>(key, NavigateOptions::default())
}
/// Constructs a signal synchronized with a specific URL query parameter.
///
/// This is the same as [`query_signal`], but allows you to specify additional navigation options.
#[track_caller]
pub fn query_signal_with_options<T>(
key: impl Into<Oco<'static, str>>,
nav_options: NavigateOptions,
) -> (Memo<Option<T>>, SignalSetter<Option<T>>)
where
T: FromStr + ToString + PartialEq + Send + Sync,
{
static IS_NAVIGATING: AtomicBool = AtomicBool::new(false);
let mut key: Oco<'static, str> = key.into();
let query_map = use_query_map();
let navigate = use_navigate();
let location = use_location();
let RouterContext {
query_mutations, ..
} = expect_context();
let get = Memo::new({
let key = key.clone_inplace();
move |_| {
query_map.with(|map| {
map.get_str(&key).and_then(|value| value.parse().ok())
})
}
});
let set = SignalSetter::map(move |value: Option<T>| {
let path = location.pathname.get_untracked();
let hash = location.hash.get_untracked();
let qs = location.query.read_untracked().to_query_string();
let new_url = format!("{path}{qs}{hash}");
query_mutations
.write_value()
.push((key.clone(), value.as_ref().map(ToString::to_string)));
if !IS_NAVIGATING.load(Ordering::Relaxed) {
IS_NAVIGATING.store(true, Ordering::Relaxed);
request_animation_frame({
let navigate = navigate.clone();
let nav_options = nav_options.clone();
move || {
navigate(&new_url, nav_options.clone());
IS_NAVIGATING.store(false, Ordering::Relaxed)
}
})
}
});
(get, set)
}
#[track_caller]
pub(crate) fn has_router() -> bool {
use_context::<RouterContext>().is_some()
}
/*
/// Returns the current [`RouterContext`], containing information about the router's state.
#[track_caller]
pub(crate) fn use_router() -> RouterContext {
if let Some(router) = use_context::<RouterContext>() {
router
} else {
leptos::leptos_dom::debug_warn!(
"You must call use_router() within a <Router/> component {:?}",
std::panic::Location::caller()
);
panic!("You must call use_router() within a <Router/> component");
}
}
*/
/// Returns the current [`Location`], which contains reactive variables
#[track_caller]
pub fn use_location() -> Location {
let RouterContext { location, .. } =
use_context().expect("Tried to access Location outside a <Router>.");
location
}
pub(crate) type RawParamsMap = ArcMemo<ParamsMap>;
#[track_caller]
fn use_params_raw() -> RawParamsMap {
use_context().expect(
"Tried to access params outside the context of a matched <Route>.",
)
}
/// Returns a raw key-value map of route params.
#[track_caller]
pub fn use_params_map() -> Memo<ParamsMap> {
use_params_raw().into()
}
/// Returns the current route params, parsed into the given type, or an error.
#[track_caller]
pub fn use_params<T>() -> Memo<Result<T, ParamsError>>
where
T: Params + PartialEq + Send + Sync + 'static,
{
// TODO this can be optimized in future to map over the signal, rather than cloning
let params = use_params_raw();
Memo::new(move |_| params.with(T::from_map))
}
#[track_caller]
fn use_url_raw() -> ArcRwSignal<Url> {
use_context().unwrap_or_else(|| {
let RouterContext { current_url, .. } = use_context().expect(
"Tried to access reactive URL outside a <Router> component.",
);
current_url
})
}
/// Gives reactive access to the current URL.
#[track_caller]
pub fn use_url() -> ReadSignal<Url> {
use_url_raw().read_only().into()
}
/// Returns a raw key-value map of the URL search query.
#[track_caller]
pub fn use_query_map() -> Memo<ParamsMap> {
let url = use_url_raw();
Memo::new(move |_| url.with(|url| url.search_params().clone()))
}
/// Returns the current URL search query, parsed into the given type, or an error.
#[track_caller]
pub fn use_query<T>() -> Memo<Result<T, ParamsError>>
where
T: Params + PartialEq + Send + Sync + 'static,
{
let url = use_url_raw();
Memo::new(move |_| url.with(|url| T::from_map(url.search_params())))
}
#[derive(Debug, Clone)]
pub(crate) struct Matched(pub ArcMemo<String>);
/// Resolves the given path relative to the current route.
#[track_caller]
pub(crate) fn use_resolved_path(
path: impl Fn() -> String + Send + Sync + 'static,
) -> ArcMemo<String> {
let router = use_context::<RouterContext>()
.expect("called use_resolved_path outside a <Router>");
// TODO make this work with flat routes too?
let matched = use_context::<Matched>().map(|n| n.0);
ArcMemo::new(move |_| {
let path = path();
if path.starts_with('/') {
path
} else {
router
.resolve_path(
&path,
matched.as_ref().map(|n| n.get()).as_deref(),
)
.to_string()
}
})
}
/// Returns a function that can be used to navigate to a new route.
///
/// This should only be called on the client; it does nothing during
/// server rendering.
///
/// ```rust
/// # if false { // can't actually navigate, no <Router/>
/// let navigate = leptos_router::hooks::use_navigate();
/// navigate("/", Default::default());
/// # }
/// ```
#[track_caller]
pub fn use_navigate() -> impl Fn(&str, NavigateOptions) + Clone {
let cx = use_context::<RouterContext>()
.expect("You cannot call `use_navigate` outside a <Router>.");
move |path: &str, options: NavigateOptions| cx.navigate(path, options)
}
/// Returns a reactive string that contains the route that was matched for
/// this [`Route`](crate::components::Route).
#[track_caller]
pub fn use_matched() -> Memo<String> {
use_context::<Matched>()
.expect("use_matched called outside a matched Route")
.0
.into()
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/router/src/nested_router.rs | router/src/nested_router.rs | use crate::{
flat_router::MatchedRoute,
hooks::Matched,
location::{LocationProvider, Url},
matching::RouteDefs,
params::ParamsMap,
view_transition::start_view_transition,
ChooseView, MatchInterface, MatchNestedRoutes, MatchParams, PathSegment,
RouteList, RouteListing, RouteMatchId,
};
use any_spawner::Executor;
use either_of::{Either, EitherOf3};
use futures::{
channel::oneshot,
future::{join_all, AbortHandle, Abortable},
FutureExt,
};
use leptos::{
attr::any_attribute::AnyAttribute,
component,
oco::Oco,
prelude::{ArcStoredValue, WriteValue},
};
use or_poisoned::OrPoisoned;
use reactive_graph::{
computed::{ArcMemo, ScopedFuture},
owner::{provide_context, use_context, Owner},
signal::{ArcRwSignal, ArcTrigger},
traits::{Get, GetUntracked, Notify, ReadUntracked, Set, Track, Write},
transition::AsyncTransition,
wrappers::write::SignalSetter,
};
use send_wrapper::SendWrapper;
use std::{
cell::RefCell,
fmt::Debug,
future::Future,
iter, mem,
pin::Pin,
rc::Rc,
sync::{Arc, Mutex},
};
use tachys::{
hydration::Cursor,
reactive_graph::{OwnedView, Suspend},
ssr::StreamBuilder,
view::{
add_attr::AddAnyAttr,
any_view::{AnyView, IntoAny},
either::EitherOf3State,
Mountable, Position, PositionState, Render, RenderHtml,
},
};
pub(crate) struct NestedRoutesView<Loc, Defs, FalFn> {
pub location: Option<Loc>,
pub routes: RouteDefs<Defs>,
pub outer_owner: Owner,
pub current_url: ArcRwSignal<Url>,
pub base: Option<Oco<'static, str>>,
pub fallback: FalFn,
pub set_is_routing: Option<SignalSetter<bool>>,
pub transition: bool,
}
/// Retained view state for the nested router.
pub(crate) struct NestedRouteViewState<Fal>
where
Fal: Render,
{
path: String,
current_url: ArcRwSignal<Url>,
outlets: Vec<RouteContext>,
// TODO loading fallback
#[allow(clippy::type_complexity)]
view: Rc<RefCell<EitherOf3State<(), Fal, AnyView>>>,
// held to keep the Owner alive until the router is dropped
#[allow(unused)]
outer_owner: Owner,
abort_navigation: ArcStoredValue<Option<AbortHandle>>,
}
impl<Loc, Defs, FalFn, Fal> Render for NestedRoutesView<Loc, Defs, FalFn>
where
Loc: LocationProvider,
Defs: MatchNestedRoutes,
FalFn: FnOnce() -> Fal,
Fal: Render + 'static,
{
// TODO support fallback while loading
type State = NestedRouteViewState<Fal>;
fn build(self) -> Self::State {
let NestedRoutesView {
routes,
outer_owner,
current_url,
fallback,
base,
..
} = self;
let mut loaders = Vec::new();
let mut outlets = Vec::new();
let url = current_url.read_untracked();
let path = url.path().to_string();
// match the route
let new_match = routes.match_route(url.path());
// start with an empty view because we'll be loading routes async
let view = EitherOf3::A(()).build();
let view = Rc::new(RefCell::new(view));
let matched_view = match new_match {
None => EitherOf3::B(fallback()),
Some(route) => {
route.build_nested_route(
&url,
base,
&mut loaders,
&mut outlets,
&outer_owner,
);
drop(url);
EitherOf3::C(top_level_outlet(&outlets, &outer_owner))
}
};
Executor::spawn_local({
let view = Rc::clone(&view);
let loaders = mem::take(&mut loaders);
ScopedFuture::new(async move {
let triggers = join_all(loaders).await;
for trigger in triggers {
trigger.notify();
}
matched_view.rebuild(&mut *view.borrow_mut());
})
});
NestedRouteViewState {
path,
current_url,
outlets,
view,
outer_owner,
abort_navigation: Default::default(),
}
}
fn rebuild(self, state: &mut Self::State) {
let url_snapshot = self.current_url.get_untracked();
// if the path is the same, we do not need to re-route
// we can just update the search query and go about our day
if url_snapshot.path() == state.path {
for outlet in &state.outlets {
outlet.url.set(url_snapshot.to_owned());
}
return;
}
// since the path didn't match, we'll update the retained path for future diffing
state.path.clear();
state.path.push_str(url_snapshot.path());
let new_match = self.routes.match_route(url_snapshot.path());
*state.current_url.write_untracked() = url_snapshot;
match new_match {
None => {
EitherOf3::<(), Fal, AnyView>::B((self.fallback)())
.rebuild(&mut state.view.borrow_mut());
state.outlets.clear();
if let Some(loc) = self.location {
loc.ready_to_complete();
}
}
Some(route) => {
if let Some(set_is_routing) = self.set_is_routing {
set_is_routing.set(true);
}
let mut preloaders = Vec::new();
let mut full_loaders = Vec::new();
let different_level = route.rebuild_nested_route(
&self.current_url.read_untracked(),
self.base,
&mut 0,
&mut preloaders,
&mut full_loaders,
&mut state.outlets,
self.set_is_routing.is_some(),
0,
&self.outer_owner,
);
let (abort_handle, abort_registration) =
AbortHandle::new_pair();
if let Some(prev_handle) =
state.abort_navigation.write_value().replace(abort_handle)
{
prev_handle.abort();
}
let location = self.location.clone();
let is_back = location
.as_ref()
.map(|nav| nav.is_back().get_untracked())
.unwrap_or(false);
Executor::spawn_local(async move {
let triggers = Abortable::new(
join_all(preloaders),
abort_registration,
);
if let Ok(triggers) = triggers.await {
// tell each one of the outlet triggers that it's ready
let notify = move || {
for trigger in triggers {
trigger.notify();
}
};
if self.transition {
start_view_transition(
different_level,
is_back,
notify,
);
} else {
notify();
}
}
});
let abort_navigation = state.abort_navigation.clone();
Executor::spawn_local(async move {
join_all(full_loaders).await;
_ = abort_navigation.write_value().take();
if let Some(set_is_routing) = self.set_is_routing {
set_is_routing.set(false);
}
if let Some(loc) = location {
loc.ready_to_complete();
}
});
// if it was on the fallback, show the view instead
if matches!(state.view.borrow().state, EitherOf3::B(_)) {
EitherOf3::<(), Fal, AnyView>::C(top_level_outlet(
&state.outlets,
&self.outer_owner,
))
.rebuild(&mut *state.view.borrow_mut());
}
}
}
}
}
impl<Loc, Defs, Fal, FalFn> AddAnyAttr for NestedRoutesView<Loc, Defs, FalFn>
where
Loc: LocationProvider + Send,
Defs: MatchNestedRoutes + Send + 'static,
FalFn: FnOnce() -> Fal + Send + 'static,
Fal: RenderHtml + 'static,
{
type Output<SomeNewAttr: leptos::attr::Attribute> =
NestedRoutesView<Loc, Defs, FalFn>;
fn add_any_attr<NewAttr: leptos::attr::Attribute>(
self,
_attr: NewAttr,
) -> Self::Output<NewAttr>
where
Self::Output<NewAttr>: RenderHtml,
{
todo!()
}
}
impl<Loc, Defs, FalFn, Fal> RenderHtml for NestedRoutesView<Loc, Defs, FalFn>
where
Loc: LocationProvider + Send,
Defs: MatchNestedRoutes + Send + 'static,
FalFn: FnOnce() -> Fal + Send + 'static,
Fal: RenderHtml + 'static,
{
type AsyncOutput = Self;
type Owned = Self;
const MIN_LENGTH: usize = 0; // TODO
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>,
) {
// if this is being run on the server for the first time, generating all possible routes
if RouteList::is_generating() {
// add routes
let (base, routes) = self.routes.generate_routes();
let routes = routes
.into_iter()
.map(|data| {
let path = base
.into_iter()
.flat_map(|base| {
iter::once(PathSegment::Static(
base.to_string().into(),
))
})
.chain(data.segments)
.collect::<Vec<_>>();
RouteListing::new(
path,
data.ssr_mode,
data.methods,
data.regenerate,
)
})
.collect::<Vec<_>>();
// add fallback
// TODO fix: causes overlapping route issues on Axum
/*routes.push(RouteListing::new(
[PathSegment::Static(
base.unwrap_or_default().to_string().into(),
)],
SsrMode::Async,
[
Method::Get,
Method::Post,
Method::Put,
Method::Patch,
Method::Delete,
],
None,
));*/
RouteList::register(RouteList::from(routes));
} else {
let NestedRoutesView {
routes,
outer_owner,
current_url,
fallback,
base,
..
} = self;
let current_url = current_url.read_untracked();
let mut outlets = Vec::new();
let new_match = routes.match_route(current_url.path());
let view = match new_match {
None => Either::Left(fallback()),
Some(route) => {
let mut loaders = Vec::new();
route.build_nested_route(
¤t_url,
base,
&mut loaders,
&mut outlets,
&outer_owner,
);
// outlets will not send their views if the loaders are never polled
// the loaders are async so that they can lazy-load routes in the browser,
// but they should always be synchronously available on the server
join_all(mem::take(&mut loaders))
.now_or_never()
.expect("async routes not supported in SSR");
Either::Right(top_level_outlet(&outlets, &outer_owner))
}
};
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,
{
let NestedRoutesView {
routes,
outer_owner,
current_url,
fallback,
base,
..
} = self;
let current_url = current_url.read_untracked();
let mut outlets = Vec::new();
let new_match = routes.match_route(current_url.path());
let view = match new_match {
None => Either::Left(fallback()),
Some(route) => {
let mut loaders = Vec::new();
route.build_nested_route(
¤t_url,
base,
&mut loaders,
&mut outlets,
&outer_owner,
);
let preload_owners = outlets
.iter()
.map(|o| o.preload_owner.clone())
.collect::<Vec<_>>();
outer_owner
.with(|| Owner::on_cleanup(move || drop(preload_owners)));
// outlets will not send their views if the loaders are never polled
// the loaders are async so that they can lazy-load routes in the browser,
// but they should always be synchronously available on the server
join_all(mem::take(&mut loaders))
.now_or_never()
.expect("async routes not supported in SSR");
Either::Right(top_level_outlet(&outlets, &outer_owner))
}
};
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 NestedRoutesView {
routes,
outer_owner,
current_url,
fallback,
base,
..
} = self;
let mut loaders = Vec::new();
let mut outlets = Vec::new();
let url = current_url.read_untracked();
let path = url.path().to_string();
// match the route
let new_match = routes.match_route(url.path());
// start with an empty view because we'll be loading routes async
let view = Rc::new(RefCell::new(
match new_match {
None => EitherOf3::B(fallback()),
Some(route) => {
route.build_nested_route(
&url,
base,
&mut loaders,
&mut outlets,
&outer_owner,
);
drop(url);
join_all(mem::take(&mut loaders)).now_or_never().expect(
"lazy routes not supported with hydrate_body(); use \
hydrate_lazy() instead",
);
EitherOf3::C(top_level_outlet(&outlets, &outer_owner))
}
}
.hydrate::<FROM_SERVER>(cursor, position),
));
NestedRouteViewState {
path,
current_url,
outlets,
view,
outer_owner,
abort_navigation: Default::default(),
}
}
async fn hydrate_async(
self,
cursor: &Cursor,
position: &PositionState,
) -> Self::State {
let NestedRoutesView {
routes,
outer_owner,
current_url,
fallback,
base,
..
} = self;
let mut loaders = Vec::new();
let mut outlets = Vec::new();
let url = current_url.read_untracked();
let path = url.path().to_string();
// match the route
let new_match = routes.match_route(url.path());
// start with an empty view because we'll be loading routes async
let view = Rc::new(RefCell::new(
match new_match {
None => EitherOf3::B(fallback()),
Some(route) => {
route.build_nested_route(
&url,
base,
&mut loaders,
&mut outlets,
&outer_owner,
);
drop(url);
join_all(mem::take(&mut loaders)).await;
EitherOf3::C(top_level_outlet(&outlets, &outer_owner))
}
}
.hydrate::<true>(cursor, position),
));
NestedRouteViewState {
path,
current_url,
outlets,
view,
outer_owner,
abort_navigation: Default::default(),
}
}
fn into_owned(self) -> Self::Owned {
self
}
}
type OutletViewFn = Box<dyn FnMut(Owner) -> Suspend<AnyView> + Send>;
pub(crate) struct RouteContext {
id: RouteMatchId,
trigger: ArcTrigger,
url: ArcRwSignal<Url>,
params: ArcRwSignal<ParamsMap>,
pub matched: ArcRwSignal<String>,
base: Option<Oco<'static, str>>,
view_fn: Arc<Mutex<OutletViewFn>>,
owner: Arc<Mutex<Option<Owner>>>,
preload_owner: Owner,
child: ChildRoute,
}
#[derive(Clone)]
pub(crate) struct ChildRoute(Arc<Mutex<Option<RouteContext>>>);
impl Debug for RouteContext {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RouteContext")
.field("id", &self.id)
.field("trigger", &self.trigger)
.field("url", &self.url)
.field("params", &self.params)
.field("matched", &self.matched)
.field("base", &self.base)
.finish_non_exhaustive()
}
}
impl Clone for RouteContext {
fn clone(&self) -> Self {
Self {
url: self.url.clone(),
id: self.id,
trigger: self.trigger.clone(),
params: self.params.clone(),
matched: self.matched.clone(),
base: self.base.clone(),
view_fn: Arc::clone(&self.view_fn),
owner: Arc::clone(&self.owner),
child: self.child.clone(),
preload_owner: self.preload_owner.clone(),
}
}
}
trait AddNestedRoute {
fn build_nested_route(
self,
url: &Url,
base: Option<Oco<'static, str>>,
loaders: &mut Vec<Pin<Box<dyn Future<Output = ArcTrigger>>>>,
outlets: &mut Vec<RouteContext>,
outer_owner: &Owner,
);
#[allow(clippy::too_many_arguments)]
fn rebuild_nested_route(
self,
url: &Url,
base: Option<Oco<'static, str>>,
items: &mut usize,
loaders: &mut Vec<Pin<Box<dyn Future<Output = ArcTrigger>>>>,
full_loaders: &mut Vec<oneshot::Receiver<Option<Owner>>>,
outlets: &mut Vec<RouteContext>,
set_is_routing: bool,
level: u8,
outer_owner: &Owner,
) -> u8;
}
impl<Match> AddNestedRoute for Match
where
Match: MatchInterface + MatchParams,
{
fn build_nested_route(
self,
url: &Url,
base: Option<Oco<'static, str>>,
loaders: &mut Vec<Pin<Box<dyn Future<Output = ArcTrigger>>>>,
outlets: &mut Vec<RouteContext>,
outer_owner: &Owner,
) {
let orig_url = url;
// the params signal can be updated to allow the same outlet to update to changes in the
// params, even if there's not a route match change
let params = ArcRwSignal::new(self.to_params().into_iter().collect());
// the URL signal is used for access to things like search query
// this is provided per nested route, specifically so that navigating *away* from a route
// does not continuing updating its URL signal, which could do things like triggering
// resources to run again
let url = ArcRwSignal::new(url.to_owned());
// the matched signal will also be updated on every match
// it's used for relative route resolution
let matched = ArcRwSignal::new(self.as_matched().to_string());
let (parent_params, parent_matches): (Vec<_>, Vec<_>) = outlets
.iter()
.map(|route| (route.params.clone(), route.matched.clone()))
.unzip();
let params_including_parents = {
let params = params.clone();
ArcMemo::new({
move |_| {
parent_params
.iter()
.flat_map(|params| params.get().into_iter())
.chain(params.get())
.collect::<ParamsMap>()
}
})
};
let matched_including_parents = {
let matched = matched.clone();
ArcMemo::new({
move |_| {
parent_matches
.iter()
.map(|matched| matched.get())
.chain(iter::once(matched.get()))
.collect::<String>()
}
})
};
// the trigger and channel will be used to send new boxed AnyViews to the Outlet;
// whenever we match a different route, the trigger will be triggered and a new view will
// be sent through the channel to be rendered by the Outlet
//
// combining a trigger and a channel allows us to pass ownership of the view;
// storing a view in a signal would mean we need to keep a copy stored in the signal and
// require that we can clone it out
let trigger = ArcTrigger::new();
// add this outlet to the end of the outlet stack used for diffing
let outlet = RouteContext {
id: self.as_id(),
url,
trigger: trigger.clone(),
params,
matched,
view_fn: Arc::new(Mutex::new(Box::new(|_owner| {
Suspend::new(Box::pin(async { ().into_any() }))
}))),
base: base.clone(),
child: ChildRoute(Arc::new(Mutex::new(None))),
owner: Arc::new(Mutex::new(None)),
preload_owner: outer_owner.child(),
};
if !outlets.is_empty() {
let prev_index = outlets.len().saturating_sub(1);
*outlets[prev_index].child.0.lock().or_poisoned() =
Some(outlet.clone());
}
outlets.push(outlet.clone());
// send the initial view through the channel, and recurse through the children
let (view, child) = self.into_view_and_child();
loaders.push(Box::pin(ScopedFuture::new({
let url = outlet.url.clone();
let matched = Matched(matched_including_parents);
let view_fn = Arc::clone(&outlet.view_fn);
let route_owner = Arc::clone(&outlet.owner);
let outlet = outlet.clone();
let params = params_including_parents.clone();
let url = url.clone();
let matched = matched.clone();
async move {
provide_context(params.clone());
provide_context(url.clone());
provide_context(matched.clone());
outlet
.preload_owner
.with(|| {
provide_context(params.clone());
provide_context(url.clone());
provide_context(matched.clone());
ScopedFuture::new(view.preload())
})
.await;
let child = outlet.child.clone();
*view_fn.lock().or_poisoned() =
Box::new(move |owner_where_used| {
*route_owner.lock().or_poisoned() =
Some(owner_where_used.clone());
let view = view.clone();
let child = child.clone();
let params = params.clone();
let url = url.clone();
let matched = matched.clone();
owner_where_used.with({
let matched = matched.clone();
|| {
let child = child.clone();
Suspend::new(Box::pin(async move {
provide_context(child.clone());
provide_context(params.clone());
provide_context(url.clone());
provide_context(matched.clone());
let view = SendWrapper::new(
ScopedFuture::new(view.choose()),
);
let view = view.await;
let view = MatchedRoute(
matched.0.get_untracked(),
view,
);
OwnedView::new(view).into_any()
})
as Pin<
Box<
dyn Future<Output = AnyView> + Send,
>,
>)
}
})
});
trigger
}
})));
// recursively continue building the tree
// this is important because to build the view, we need access to the outlet
// and the outlet will be returned from building this child
if let Some(child) = child {
child.build_nested_route(
orig_url,
base,
loaders,
outlets,
outer_owner,
);
}
}
#[allow(clippy::too_many_arguments)]
fn rebuild_nested_route(
self,
url: &Url,
base: Option<Oco<'static, str>>,
items: &mut usize,
preloaders: &mut Vec<Pin<Box<dyn Future<Output = ArcTrigger>>>>,
full_loaders: &mut Vec<oneshot::Receiver<Option<Owner>>>,
outlets: &mut Vec<RouteContext>,
set_is_routing: bool,
level: u8,
outer_owner: &Owner,
) -> u8 {
let (parent_params, parent_matches): (Vec<_>, Vec<_>) = outlets
.iter()
.take(*items)
.map(|route| (route.params.clone(), route.matched.clone()))
.unzip();
if outlets.get(*items).is_some() && *items > 0 {
*outlets[*items - 1].child.0.lock().or_poisoned() =
Some(outlets[*items].clone());
}
let current = outlets.get_mut(*items);
match current {
// if there's nothing currently in the routes at this point, build from here
None => {
self.build_nested_route(
url,
base,
preloaders,
outlets,
outer_owner,
);
level
}
Some(current) => {
// a unique ID for each route, which allows us to compare when we get new matches
// if two IDs are the same, we do not rerender, but only update the params
// if the IDs are different, we need to replace the remainder of the tree
let id = self.as_id();
// build new params and matched strings
let new_params =
self.to_params().into_iter().collect::<ParamsMap>();
let new_match = self.as_matched().to_owned();
let (view, child) = self.into_view_and_child();
// if the IDs don't match, everything below in the tree needs to be swapped:
// 1) replace this outlet with the next view, with a new owner and new signals for
// URL/params
// 2) remove other outlets that are lower down in the match tree
// 3) build the rest of the list of matched routes, rather than rebuilding,
// as all lower outlets needs to be replaced
if id != current.id {
// update the ID of the match at this depth, so that futures rebuilds diff
// against the new ID, not the original one
current.id = id;
// create new URL and params signals
let old_url = mem::replace(
&mut current.url,
ArcRwSignal::new(url.to_owned()),
);
let old_params = mem::replace(
&mut current.params,
ArcRwSignal::new(new_params),
);
let old_matched = mem::replace(
&mut current.matched,
ArcRwSignal::new(new_match),
);
let old_preload_owner = mem::replace(
&mut current.preload_owner,
outer_owner.child(),
);
let matched_including_parents = {
ArcMemo::new({
let matched = current.matched.clone();
move |_| {
parent_matches
.iter()
.map(|matched| matched.get())
.chain(iter::once(matched.get()))
.collect::<String>()
}
})
};
let params_including_parents = {
let params = current.params.clone();
ArcMemo::new({
move |_| {
parent_params
.iter()
.flat_map(|params| params.get().into_iter())
.chain(params.get())
.collect::<ParamsMap>()
}
})
};
let (full_tx, full_rx) = oneshot::channel();
let full_tx = Mutex::new(Some(full_tx));
full_loaders.push(full_rx);
let outlet = current.clone();
// send the new view, with the new owner, through the channel to the Outlet,
// and notify the trigger so that the reactive view inside the Outlet tracking
// the trigger runs again
preloaders.push(Box::pin(ScopedFuture::new({
let trigger = current.trigger.clone();
let url = current.url.clone();
let matched = Matched(matched_including_parents);
let view_fn = Arc::clone(¤t.view_fn);
let route_owner = Arc::clone(¤t.owner);
let child = outlet.child.clone();
async move {
let child = child.clone();
outlet
.preload_owner
.with(|| {
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | true |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/router/src/method.rs | router/src/method.rs | /// Represents an HTTP method that can be handled by this route.
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash)]
pub enum Method {
/// The [`GET`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/GET) method
/// requests a representation of the specified resource.
#[default]
Get,
/// The [`POST`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST) method
/// submits an entity to the specified resource, often causing a change in
/// state or side effects on the server.
Post,
/// The [`PUT`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT) method
/// replaces all current representations of the target resource with the request payload.
Put,
/// The [`DELETE`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/DELETE) method
/// deletes the specified resource.
Delete,
/// The [`PATCH`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PATCH) method
/// applies partial modifications to a resource.
Patch,
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/router/src/static_routes.rs | router/src/static_routes.rs | use crate::{hooks::RawParamsMap, params::ParamsMap, PathSegment};
use futures::{channel::oneshot, stream, Stream, StreamExt};
use leptos::task::spawn;
use reactive_graph::{owner::Owner, traits::GetUntracked};
use std::{
fmt::{Debug, Display},
future::Future,
ops::Deref,
pin::Pin,
sync::Arc,
};
type PinnedFuture<T> = Pin<Box<dyn Future<Output = T> + Send>>;
type PinnedStream<T> = Pin<Box<dyn Stream<Item = T> + Send>>;
/// A reference-counted pointer to a function that can generate a set of params for static site
/// generation.
pub type StaticParams = Arc<StaticParamsFn>;
/// A function that generates a set of params for generating a static route.
pub type StaticParamsFn =
dyn Fn() -> PinnedFuture<StaticParamsMap> + Send + Sync + 'static;
/// A function that defines when a statically-generated page should be regenerated.
#[derive(Clone)]
#[allow(clippy::type_complexity)]
pub struct RegenerationFn(
Arc<dyn Fn(&ParamsMap) -> PinnedStream<()> + Send + Sync>,
);
impl Debug for RegenerationFn {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RegenerationFn").finish_non_exhaustive()
}
}
impl Deref for RegenerationFn {
type Target = dyn Fn(&ParamsMap) -> PinnedStream<()> + Send + Sync;
fn deref(&self) -> &Self::Target {
&*self.0
}
}
impl PartialEq for RegenerationFn {
fn eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.0, &other.0)
}
}
/// Defines how a static route should be generated.
#[derive(Clone, Default)]
pub struct StaticRoute {
pub(crate) prerender_params: Option<StaticParams>,
pub(crate) regenerate: Option<RegenerationFn>,
}
impl StaticRoute {
/// Creates a new static route listing.
pub fn new() -> Self {
Self::default()
}
/// Defines a set of params that should be prerendered on server start-up, depending on some
/// asynchronous function that returns their values.
pub fn prerender_params<Fut>(
mut self,
params: impl Fn() -> Fut + Send + Sync + 'static,
) -> Self
where
Fut: Future<Output = StaticParamsMap> + Send + 'static,
{
self.prerender_params = Some(Arc::new(move || Box::pin(params())));
self
}
/// Defines when the route should be regenerated.
pub fn regenerate<St>(
mut self,
invalidate: impl Fn(&ParamsMap) -> St + Send + Sync + 'static,
) -> Self
where
St: Stream<Item = ()> + Send + 'static,
{
self.regenerate = Some(RegenerationFn(Arc::new(move |params| {
Box::pin(invalidate(params))
})));
self
}
/// Returns a set of params that should be prerendered.
pub async fn to_prerendered_params(&self) -> Option<StaticParamsMap> {
match &self.prerender_params {
None => None,
Some(params) => Some(params().await),
}
}
}
impl Debug for StaticRoute {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("StaticRoute").finish_non_exhaustive()
}
}
impl PartialOrd for StaticRoute {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for StaticRoute {
fn cmp(&self, _other: &Self) -> std::cmp::Ordering {
std::cmp::Ordering::Equal
}
}
impl PartialEq for StaticRoute {
fn eq(&self, other: &Self) -> bool {
let prerender = match (&self.prerender_params, &other.prerender_params)
{
(None, None) => true,
(None, Some(_)) | (Some(_), None) => false,
(Some(this), Some(that)) => Arc::ptr_eq(this, that),
};
prerender && (self.regenerate == other.regenerate)
}
}
impl Eq for StaticRoute {}
/// A map of params for static routes.
#[derive(Debug, Clone, Default)]
pub struct StaticParamsMap(pub Vec<(String, Vec<String>)>);
impl StaticParamsMap {
/// Create a new empty `StaticParamsMap`.
#[inline]
pub fn new() -> Self {
Self::default()
}
/// Insert a value into the map.
#[inline]
pub fn insert(&mut self, key: impl ToString, value: Vec<String>) {
let key = key.to_string();
for item in self.0.iter_mut() {
if item.0 == key {
item.1 = value;
return;
}
}
self.0.push((key, value));
}
/// Get a value from the map.
#[inline]
pub fn get(&self, key: &str) -> Option<&Vec<String>> {
self.0
.iter()
.find_map(|entry| (entry.0 == key).then_some(&entry.1))
}
}
impl IntoIterator for StaticParamsMap {
type Item = (String, Vec<String>);
type IntoIter = StaticParamsIter;
fn into_iter(self) -> Self::IntoIter {
StaticParamsIter(self.0.into_iter())
}
}
/// An iterator over a set of (key, value) pairs for statically-routed params.
#[derive(Debug)]
pub struct StaticParamsIter(
<Vec<(String, Vec<String>)> as IntoIterator>::IntoIter,
);
impl Iterator for StaticParamsIter {
type Item = (String, Vec<String>);
fn next(&mut self) -> Option<Self::Item> {
self.0.next()
}
}
impl<A> FromIterator<A> for StaticParamsMap
where
A: Into<(String, Vec<String>)>,
{
fn from_iter<T: IntoIterator<Item = A>>(iter: T) -> Self {
Self(iter.into_iter().map(Into::into).collect())
}
}
#[doc(hidden)]
#[derive(Debug)]
pub struct StaticPath {
segments: Vec<PathSegment>,
}
impl StaticPath {
pub fn new(segments: Vec<PathSegment>) -> StaticPath {
Self { segments }
}
pub fn into_paths(
self,
params: Option<StaticParamsMap>,
) -> Vec<ResolvedStaticPath> {
use PathSegment::*;
let mut paths = vec![ResolvedStaticPath {
path: String::new(),
}];
for segment in &self.segments {
match segment {
Unit => {}
Static(s) => {
paths = paths
.into_iter()
.map(|p| {
if s.starts_with("/") || s.is_empty() {
ResolvedStaticPath {
path: format!("{}{s}", p.path),
}
} else {
ResolvedStaticPath {
path: format!("{}/{s}", p.path),
}
}
})
.collect::<Vec<_>>();
}
Param(name) | Splat(name) => {
let mut new_paths = vec![];
if let Some(params) = params.as_ref() {
for path in paths {
if let Some(params) = params.get(name) {
for val in params.iter() {
new_paths.push(if val.starts_with("/") {
ResolvedStaticPath {
path: format!(
"{}{}",
path.path, val
),
}
} else {
ResolvedStaticPath {
path: format!(
"{}/{}",
path.path, val
),
}
});
}
}
}
}
paths = new_paths;
}
OptionalParam(_) => todo!(),
}
}
paths
}
}
/// A path to be used in static route generation.
#[derive(Debug, Clone, PartialEq)]
pub struct ResolvedStaticPath {
pub(crate) path: String,
}
impl ResolvedStaticPath {
/// Defines a path to be used for static route generation.
pub fn new(path: impl Into<String>) -> Self {
Self { path: path.into() }
}
}
impl AsRef<str> for ResolvedStaticPath {
fn as_ref(&self) -> &str {
self.path.as_ref()
}
}
impl Display for ResolvedStaticPath {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
Display::fmt(&self.path, f)
}
}
impl ResolvedStaticPath {
/// Builds the page that corresponds to this path.
pub async fn build<Fut, WriterFut>(
self,
render_fn: impl Fn(&ResolvedStaticPath) -> Fut + Send + Clone + 'static,
writer: impl Fn(&ResolvedStaticPath, &Owner, String) -> WriterFut
+ Send
+ Clone
+ 'static,
was_404: impl Fn(&Owner) -> bool + Send + Clone + 'static,
regenerate: Vec<RegenerationFn>,
) -> (Owner, Option<String>)
where
Fut: Future<Output = (Owner, String)> + Send + 'static,
WriterFut: Future<Output = Result<(), std::io::Error>> + Send + 'static,
{
let (tx, rx) = oneshot::channel();
// spawns a separate task for each path it's rendering
// this allows us to parallelize all static site rendering,
// and also to create long-lived tasks
spawn({
let render_fn = render_fn.clone();
let writer = writer.clone();
let was_error = was_404.clone();
async move {
// render and write the initial page
let (owner, html) = render_fn(&self).await;
// if rendering this page resulted in an error (404, 500, etc.)
// then we should not cache it: the `was_error` function can handle notifying
// the user that there was an error, and the server can give a dynamic response
// that will include the 404 or 500
if was_error(&owner) {
// can ignore errors from channel here, because it just means we're not
// awaiting the Future
_ = tx.send((owner.clone(), Some(html)));
} else {
if let Err(e) = writer(&self, &owner, html).await {
#[cfg(feature = "tracing")]
tracing::warn!("{e}");
#[cfg(not(feature = "tracing"))]
eprintln!("{e}");
}
_ = tx.send((owner.clone(), None));
}
// if there's a regeneration function, keep looping
let params = if regenerate.is_empty() {
None
} else {
Some(
owner
.use_context_bidirectional::<RawParamsMap>()
.expect(
"using static routing, but couldn't find \
ParamsMap",
)
.get_untracked(),
)
};
let mut regenerate = stream::select_all(
regenerate
.into_iter()
.map(|r| owner.with(|| r(params.as_ref().unwrap()))),
);
while regenerate.next().await.is_some() {
let (owner, html) = render_fn(&self).await;
if !was_error(&owner) {
if let Err(e) = writer(&self, &owner, html).await {
#[cfg(feature = "tracing")]
tracing::warn!("{e}");
#[cfg(not(feature = "tracing"))]
eprintln!("{e}");
}
}
owner.unset_with_forced_cleanup();
}
}
});
rx.await.unwrap()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn static_path_segments_into_path_ignore_empty_segments() {
let segments = StaticPath::new(vec![
PathSegment::Static("".into()),
PathSegment::Static("post".into()),
]);
assert_eq!(
segments.into_paths(None),
vec![ResolvedStaticPath::new("/post")]
);
}
#[test]
fn static_path_segments_into_path_flatten_param() {
let mut params = StaticParamsMap::new();
params
.0
.push(("slug".into(), vec!["first".into(), "second".into()]));
let segments = StaticPath::new(vec![
PathSegment::Static("/post".into()),
PathSegment::Param("slug".into()),
]);
assert_eq!(
segments.into_paths(Some(params)),
vec![
ResolvedStaticPath::new("/post/first"),
ResolvedStaticPath::new("/post/second")
]
);
}
#[test]
fn static_path_segments_into_path_no_double_slash() {
let segments = StaticPath::new(vec![
PathSegment::Static("/post".into()),
PathSegment::Static("/leptos".into()),
]);
assert_eq!(
segments.into_paths(None),
vec![ResolvedStaticPath::new("/post/leptos")]
);
let mut params = StaticParamsMap::new();
params
.0
.push(("slug".into(), vec!["/first".into(), "/second".into()]));
let segments = StaticPath::new(vec![
PathSegment::Static("/post".into()),
PathSegment::Param("slug".into()),
]);
assert_eq!(
segments.into_paths(Some(params)),
vec![
ResolvedStaticPath::new("/post/first"),
ResolvedStaticPath::new("/post/second")
]
);
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/router/src/components.rs | router/src/components.rs | pub use super::{form::*, link::*};
#[cfg(feature = "ssr")]
use crate::location::RequestUrl;
pub use crate::nested_router::Outlet;
use crate::{
flat_router::FlatRoutesView,
hooks::{use_matched, use_navigate},
location::{
BrowserUrl, Location, LocationChange, LocationProvider, State, Url,
},
navigate::NavigateOptions,
nested_router::NestedRoutesView,
resolve_path::resolve_path,
ChooseView, MatchNestedRoutes, NestedRoute, PossibleRouteMatch, RouteDefs,
SsrMode,
};
use either_of::EitherOf3;
use leptos::{children, prelude::*};
use reactive_graph::{
owner::{provide_context, use_context, Owner},
signal::ArcRwSignal,
traits::{GetUntracked, ReadUntracked, Set},
wrappers::write::SignalSetter,
};
use std::{
borrow::Cow,
fmt::{Debug, Display},
mem,
sync::Arc,
time::Duration,
};
/// A wrapper that allows passing route definitions as children to a component like [`Routes`],
/// [`FlatRoutes`], [`ParentRoute`], or [`ProtectedParentRoute`].
#[derive(Clone, Debug)]
pub struct RouteChildren<Children>(Children);
impl<Children> RouteChildren<Children> {
/// Extracts the inner route definition.
pub fn into_inner(self) -> Children {
self.0
}
}
impl<F, Children> ToChildren<F> for RouteChildren<Children>
where
F: FnOnce() -> Children,
{
fn to_children(f: F) -> Self {
RouteChildren(f())
}
}
#[component(transparent)]
pub fn Router<Chil>(
/// The base URL for the router. Defaults to `""`.
#[prop(optional, into)]
base: Option<Cow<'static, str>>,
/// A signal that will be set while the navigation process is underway.
#[prop(optional, into)]
set_is_routing: Option<SignalSetter<bool>>,
// TODO trailing slashes
///// How trailing slashes should be handled in [`Route`] paths.
//#[prop(optional)]
//trailing_slash: TrailingSlash,
/// The `<Router/>` should usually wrap your whole page. It can contain
/// any elements, and should include a [`Routes`] component somewhere
/// to define and display [`Route`]s.
children: TypedChildren<Chil>,
) -> impl IntoView
where
Chil: IntoView,
{
#[cfg(feature = "ssr")]
let (location_provider, current_url, redirect_hook) = {
let req = use_context::<RequestUrl>().expect("no RequestUrl provided");
let parsed = req.parse().expect("could not parse RequestUrl");
let current_url = ArcRwSignal::new(parsed);
(None, current_url, Box::new(move |_: &str| {}))
};
#[cfg(not(feature = "ssr"))]
let (location_provider, current_url, redirect_hook) = {
let owner = Owner::current();
let location =
BrowserUrl::new().expect("could not access browser navigation"); // TODO options here
location.init(base.clone());
provide_context(location.clone());
let current_url = location.as_url().clone();
let redirect_hook = Box::new(move |loc: &str| {
if let Some(owner) = &owner {
owner.with(|| BrowserUrl::redirect(loc));
}
});
(Some(location), current_url, redirect_hook)
};
// provide router context
let state = ArcRwSignal::new(State::new(None));
let location = Location::new(current_url.read_only(), state.read_only());
// set server function redirect hook
_ = server_fn::redirect::set_redirect_hook(redirect_hook);
provide_context(RouterContext {
base,
current_url,
location,
state,
set_is_routing,
query_mutations: Default::default(),
location_provider,
});
let children = children.into_inner();
children()
}
#[derive(Clone)]
pub(crate) struct RouterContext {
pub base: Option<Cow<'static, str>>,
pub current_url: ArcRwSignal<Url>,
pub location: Location,
pub state: ArcRwSignal<State>,
pub set_is_routing: Option<SignalSetter<bool>>,
pub query_mutations:
ArcStoredValue<Vec<(Oco<'static, str>, Option<String>)>>,
pub location_provider: Option<BrowserUrl>,
}
impl RouterContext {
pub fn navigate(&self, path: &str, options: NavigateOptions) {
let current = self.current_url.read_untracked();
let resolved_to = if options.resolve {
resolve_path(
self.base.as_deref().unwrap_or_default(),
path,
// TODO this should be relative to the current *Route*, I think...
Some(current.path()),
)
} else {
resolve_path("", path, None)
};
let mut url = match BrowserUrl::parse(&resolved_to) {
Ok(url) => url,
Err(e) => {
leptos::logging::error!("Error parsing URL: {e:?}");
return;
}
};
let query_mutations =
mem::take(&mut *self.query_mutations.write_value());
if !query_mutations.is_empty() {
for (key, value) in query_mutations {
if let Some(value) = value {
url.search_params_mut().replace(key, value);
} else {
url.search_params_mut().remove(&key);
}
}
*url.search_mut() = url
.search_params()
.to_query_string()
.trim_start_matches('?')
.into()
}
if url.origin() != current.origin() {
window().location().set_href(path).unwrap();
return;
}
// update state signal, if necessary
if options.state != self.state.get_untracked() {
self.state.set(options.state.clone());
}
// update URL signal, if necessary
let value = url.to_full_path();
if current != url {
drop(current);
self.current_url.set(url);
}
if let Some(location_provider) = &self.location_provider {
location_provider.complete_navigation(&LocationChange {
value,
replace: options.replace,
scroll: options.scroll,
state: options.state,
});
}
}
pub fn resolve_path<'a>(
&'a self,
path: &'a str,
from: Option<&'a str>,
) -> Cow<'a, str> {
let base = self.base.as_deref().unwrap_or_default();
resolve_path(base, path, from)
}
}
impl Debug for RouterContext {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RouterContext")
.field("base", &self.base)
.field("current_url", &self.current_url)
.field("location", &self.location)
.finish_non_exhaustive()
}
}
#[component(transparent)]
pub fn Routes<Defs, FallbackFn, Fallback>(
/// A function that returns the view that should be shown if no route is matched.
fallback: FallbackFn,
/// Whether to use the View Transition API during navigation.
#[prop(optional)]
transition: bool,
/// The route definitions. This should consist of one or more [`ParentRoute`] or [`Route`]
/// components.
children: RouteChildren<Defs>,
) -> impl IntoView
where
Defs: MatchNestedRoutes + Clone + Send + 'static,
FallbackFn: FnOnce() -> Fallback + Clone + Send + 'static,
Fallback: IntoView + 'static,
{
let location = use_context::<BrowserUrl>();
let RouterContext {
current_url,
base,
set_is_routing,
..
} = use_context()
.expect("<Routes> should be used inside a <Router> component");
let base = base.map(|base| {
let mut base = Oco::from(base);
base.upgrade_inplace();
base
});
let routes = RouteDefs::new_with_base(
children.into_inner(),
base.clone().unwrap_or_default(),
);
let outer_owner =
Owner::current().expect("creating Routes, but no Owner was found");
move || {
current_url.track();
outer_owner.with(|| {
current_url.read_untracked().provide_server_action_error()
});
NestedRoutesView {
location: location.clone(),
routes: routes.clone(),
outer_owner: outer_owner.clone(),
current_url: current_url.clone(),
base: base.clone(),
fallback: fallback.clone(),
set_is_routing,
transition,
}
}
}
#[component(transparent)]
pub fn FlatRoutes<Defs, FallbackFn, Fallback>(
/// A function that returns the view that should be shown if no route is matched.
fallback: FallbackFn,
/// Whether to use the View Transition API during navigation.
#[prop(optional)]
transition: bool,
/// The route definitions. This should consist of one or more [`ParentRoute`] or [`Route`]
/// components.
children: RouteChildren<Defs>,
) -> impl IntoView
where
Defs: MatchNestedRoutes + Clone + Send + 'static,
FallbackFn: FnOnce() -> Fallback + Clone + Send + 'static,
Fallback: IntoView + 'static,
{
let location = use_context::<BrowserUrl>();
let RouterContext {
current_url,
base,
set_is_routing,
..
} = use_context()
.expect("<FlatRoutes> should be used inside a <Router> component");
// TODO base
#[allow(unused)]
let base = base.map(|base| {
let mut base = Oco::from(base);
base.upgrade_inplace();
base
});
let routes = RouteDefs::new_with_base(
children.into_inner(),
base.clone().unwrap_or_default(),
);
let outer_owner =
Owner::current().expect("creating Router, but no Owner was found");
move || {
current_url.track();
outer_owner.with(|| {
current_url.read_untracked().provide_server_action_error()
});
FlatRoutesView {
current_url: current_url.clone(),
location: location.clone(),
routes: routes.clone(),
fallback: fallback.clone(),
outer_owner: outer_owner.clone(),
set_is_routing,
transition,
}
}
}
/// Describes a portion of the nested layout of the app, specifying the route it should match
/// and the element it should display.
#[component(transparent)]
pub fn Route<Segments, View>(
/// The path fragment that this route should match. This can be created using the
/// [`path`](crate::path) macro, or path segments ([`StaticSegment`](crate::StaticSegment),
/// [`ParamSegment`](crate::ParamSegment), [`WildcardSegment`](crate::WildcardSegment), and
/// [`OptionalParamSegment`](crate::OptionalParamSegment)).
path: Segments,
/// The view for this route.
view: View,
/// The mode that this route prefers during server-side rendering.
/// Defaults to out-of-order streaming.
#[prop(optional)]
ssr: SsrMode,
) -> <NestedRoute<Segments, (), (), View> as IntoMaybeErased>::Output
where
View: ChooseView + Clone + 'static,
Segments: PossibleRouteMatch + Clone + Send + 'static,
{
NestedRoute::new(path, view)
.ssr_mode(ssr)
.into_maybe_erased()
}
/// Describes a portion of the nested layout of the app, specifying the route it should match
/// and the element it should display.
#[component(transparent)]
pub fn ParentRoute<Segments, View, Children>(
/// The path fragment that this route should match. This can be created using the
/// [`path`](crate::path) macro, or path segments ([`StaticSegment`](crate::StaticSegment),
/// [`ParamSegment`](crate::ParamSegment), [`WildcardSegment`](crate::WildcardSegment), and
/// [`OptionalParamSegment`](crate::OptionalParamSegment)).
path: Segments,
/// The view for this route.
view: View,
/// Nested child routes.
children: RouteChildren<Children>,
/// The mode that this route prefers during server-side rendering.
/// Defaults to out-of-order streaming.
#[prop(optional)]
ssr: SsrMode,
) -> <NestedRoute<Segments, Children, (), View> as IntoMaybeErased>::Output
where
View: ChooseView + Clone + 'static,
Children: MatchNestedRoutes + Send + Clone + 'static,
Segments: PossibleRouteMatch + Clone + Send + 'static,
{
let children = children.into_inner();
NestedRoute::new(path, view)
.ssr_mode(ssr)
.child(children)
.into_maybe_erased()
}
/// With the `impl Fn` in the return signature, IntoMaybeErased::Output isn't accepted by the compiler, so changing return type depending on the erasure flag.
macro_rules! define_protected_route {
($ret:ty) => {
/// Describes a route that is guarded by a certain condition. This works the same way as
/// [`<Route/>`], except that if the `condition` function evaluates to `Some(false)`, it
/// redirects to `redirect_path` instead of displaying its `view`.
#[component(transparent)]
pub fn ProtectedRoute<Segments, ViewFn, View, C, PathFn, P>(
/// The path fragment that this route should match. This can be created using the
/// [`path`](crate::path) macro, or path segments ([`StaticSegment`](crate::StaticSegment),
/// [`ParamSegment`](crate::ParamSegment), [`WildcardSegment`](crate::WildcardSegment), and
/// [`OptionalParamSegment`](crate::OptionalParamSegment)).
path: Segments,
/// The view for this route.
view: ViewFn,
/// A function that returns `Option<bool>`, where `Some(true)` means that the user can access
/// the page, `Some(false)` means the user cannot access the page, and `None` means this
/// information is still loading.
condition: C,
/// The path that will be redirected to if the condition is `Some(false)`.
redirect_path: PathFn,
/// Will be displayed while the condition is pending. By default this is the empty view.
#[prop(optional, into)]
fallback: children::ViewFn,
/// The mode that this route prefers during server-side rendering.
/// Defaults to out-of-order streaming.
#[prop(optional)]
ssr: SsrMode,
) -> $ret
where
Segments: PossibleRouteMatch + Clone + Send + 'static,
ViewFn: Fn() -> View + Send + Clone + 'static,
View: IntoView + 'static,
C: Fn() -> Option<bool> + Send + Clone + 'static,
PathFn: Fn() -> P + Send + Clone + 'static,
P: Display + 'static,
{
let fallback = move || fallback.run();
let view = move || {
let condition = condition.clone();
let redirect_path = redirect_path.clone();
let view = view.clone();
let fallback = fallback.clone();
(view! {
<Transition fallback=fallback.clone()>
{move || {
let condition = condition();
let view = view.clone();
let redirect_path = redirect_path.clone();
let fallback = fallback.clone();
Unsuspend::new(move || match condition {
Some(true) => EitherOf3::A(view()),
#[allow(clippy::unit_arg)]
Some(false) => {
EitherOf3::B(view! { <Redirect path=redirect_path()/> }.into_inner())
}
None => EitherOf3::C(fallback()),
})
}}
</Transition>
})
.into_any()
};
NestedRoute::new(path, view).ssr_mode(ssr).into_maybe_erased()
}
};
}
#[cfg(erase_components)]
define_protected_route!(crate::any_nested_route::AnyNestedRoute);
#[cfg(not(erase_components))]
define_protected_route!(NestedRoute<Segments, (), (), impl Fn() -> AnyView + Send + Clone>);
/// With the `impl Fn` in the return signature, IntoMaybeErased::Output isn't accepted by the compiler, so changing return type depending on the erasure flag.
macro_rules! define_protected_parent_route {
($ret:ty) => {
#[component(transparent)]
pub fn ProtectedParentRoute<
Segments,
ViewFn,
View,
C,
PathFn,
P,
Children,
>(
/// The path fragment that this route should match. This can be created using the
/// [`path`](crate::path) macro, or path segments ([`StaticSegment`](crate::StaticSegment),
/// [`ParamSegment`](crate::ParamSegment), [`WildcardSegment`](crate::WildcardSegment), and
/// [`OptionalParamSegment`](crate::OptionalParamSegment)).
path: Segments,
/// The view for this route.
view: ViewFn,
/// A function that returns `Option<bool>`, where `Some(true)` means that the user can access
/// the page, `Some(false)` means the user cannot access the page, and `None` means this
/// information is still loading.
condition: C,
/// Will be displayed while the condition is pending. By default this is the empty view.
#[prop(optional, into)]
fallback: children::ViewFn,
/// The path that will be redirected to if the condition is `Some(false)`.
redirect_path: PathFn,
/// Nested child routes.
children: RouteChildren<Children>,
/// The mode that this route prefers during server-side rendering.
/// Defaults to out-of-order streaming.
#[prop(optional)]
ssr: SsrMode,
) -> $ret
where
Segments: PossibleRouteMatch + Clone + Send + 'static,
Children: MatchNestedRoutes + Send + Clone + 'static,
ViewFn: Fn() -> View + Send + Clone + 'static,
View: IntoView + 'static,
C: Fn() -> Option<bool> + Send + Clone + 'static,
PathFn: Fn() -> P + Send + Clone + 'static,
P: Display + 'static,
{
let fallback = move || fallback.run();
let children = children.into_inner();
let view = move || {
let condition = condition.clone();
let redirect_path = redirect_path.clone();
let fallback = fallback.clone();
let view = view.clone();
let owner = Owner::current().unwrap();
let view = {
let fallback = fallback.clone();
move || {
let condition = condition();
let view = view.clone();
let redirect_path = redirect_path.clone();
let fallback = fallback.clone();
let owner = owner.clone();
Unsuspend::new(move || match condition {
// reset the owner so that things like providing context work
// otherwise, this will be a child owner nested within the Transition, not
// the parent owner of the Outlet
//
// clippy: not redundant, a FnOnce vs FnMut issue
#[allow(clippy::redundant_closure)]
Some(true) => EitherOf3::A(owner.with(|| view())),
#[allow(clippy::unit_arg)]
Some(false) => EitherOf3::B(
view! { <Redirect path=redirect_path()/> }
.into_inner(),
),
None => EitherOf3::C(fallback()),
})
}
};
(view! { <Transition fallback>{view}</Transition> }).into_any()
};
NestedRoute::new(path, view)
.ssr_mode(ssr)
.child(children)
.into_maybe_erased()
}
};
}
#[cfg(erase_components)]
define_protected_parent_route!(crate::any_nested_route::AnyNestedRoute);
#[cfg(not(erase_components))]
define_protected_parent_route!(NestedRoute<Segments, Children, (), impl Fn() -> AnyView + Send + Clone>);
/// Redirects the user to a new URL, whether on the client side or on the server
/// side. If rendered on the server, this sets a `302` status code and sets a `Location`
/// header. If rendered in the browser, it uses client-side navigation to redirect.
/// In either case, it resolves the route relative to the current route. (To use
/// an absolute path, prefix it with `/`).
///
/// **Note**: Support for server-side redirects is provided by the server framework
/// integrations ([`leptos_actix`] and [`leptos_axum`]. If you’re not using one of those
/// integrations, you should manually provide a way of redirecting on the server
/// using [`provide_server_redirect`].
///
/// [`leptos_actix`]: <https://docs.rs/leptos_actix/>
/// [`leptos_axum`]: <https://docs.rs/leptos_axum/>
#[component(transparent)]
pub fn Redirect<P>(
/// The relative path to which the user should be redirected.
path: P,
/// Navigation options to be used on the client side.
#[prop(optional)]
#[allow(unused)]
options: Option<NavigateOptions>,
) where
P: core::fmt::Display + 'static,
{
// TODO resolve relative path
let path = path.to_string();
// redirect on the server
if let Some(redirect_fn) = use_context::<ServerRedirectFunction>() {
(redirect_fn.f)(&resolve_path(
"",
&path,
Some(&use_matched().get_untracked()),
));
}
// redirect on the client
else {
if cfg!(feature = "ssr") {
#[cfg(feature = "tracing")]
tracing::warn!(
"Calling <Redirect/> without a ServerRedirectFunction \
provided, in SSR mode."
);
#[cfg(not(feature = "tracing"))]
eprintln!(
"Calling <Redirect/> without a ServerRedirectFunction \
provided, in SSR mode."
);
return;
}
let navigate = use_navigate();
navigate(&path, options.unwrap_or_default());
}
}
/// Wrapping type for a function provided as context to allow for
/// server-side redirects. See [`provide_server_redirect`]
/// and [`Redirect`].
#[derive(Clone)]
pub struct ServerRedirectFunction {
f: Arc<dyn Fn(&str) + Send + Sync>,
}
impl core::fmt::Debug for ServerRedirectFunction {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("ServerRedirectFunction").finish()
}
}
/// Provides a function that can be used to redirect the user to another
/// absolute path, on the server. This should set a `302` status code and an
/// appropriate `Location` header.
pub fn provide_server_redirect(handler: impl Fn(&str) + Send + Sync + 'static) {
provide_context(ServerRedirectFunction {
f: Arc::new(handler),
})
}
/// A visible indicator that the router is in the process of navigating
/// to another route.
///
/// This is used when `<Router set_is_routing>` has been provided, to
/// provide some visual indicator that the page is currently loading
/// async data, so that it is does not appear to have frozen. It can be
/// styled independently.
#[component]
pub fn RoutingProgress(
/// Whether the router is currently loading the new page.
#[prop(into)]
is_routing: Signal<bool>,
/// The maximum expected time for loading, which is used to
/// calibrate the animation process.
#[prop(optional, into)]
max_time: std::time::Duration,
/// The time to show the full progress bar after page has loaded, before hiding it. (Defaults to 100ms.)
#[prop(default = std::time::Duration::from_millis(250))]
before_hiding: std::time::Duration,
) -> impl IntoView {
const INCREMENT_EVERY_MS: f32 = 5.0;
let expected_increments =
max_time.as_secs_f32() / (INCREMENT_EVERY_MS / 1000.0);
let percent_per_increment = 100.0 / expected_increments;
let (is_showing, set_is_showing) = signal(false);
let (progress, set_progress) = signal(0.0);
StoredValue::new(RenderEffect::new(
move |prev: Option<Option<IntervalHandle>>| {
if is_routing.get() && !is_showing.get() {
set_is_showing.set(true);
set_interval_with_handle(
move || {
set_progress.update(|n| *n += percent_per_increment);
},
Duration::from_millis(INCREMENT_EVERY_MS as u64),
)
.ok()
} else if is_routing.get() && is_showing.get() {
set_progress.set(0.0);
prev?
} else {
set_progress.set(100.0);
set_timeout(
move || {
set_progress.set(0.0);
set_is_showing.set(false);
},
before_hiding,
);
if let Some(Some(interval)) = prev {
interval.clear();
}
None
}
},
));
view! {
<Show when=move || is_showing.get() fallback=|| ()>
<progress min="0" max="100" value=move || progress.get()></progress>
</Show>
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/router/src/ssr_mode.rs | router/src/ssr_mode.rs | use crate::static_routes::StaticRoute;
/// Indicates which rendering mode should be used for this route during server-side rendering.
///
/// Leptos supports the following ways of rendering HTML that contains `async` data loaded
/// under `<Suspense/>`.
/// 1. **Synchronous** (use any mode except `Async`, don't depend on any resource): Serve an HTML shell that includes `fallback` for any `Suspense`. Load data on the client (using `create_local_resource`), replacing `fallback` once they're loaded.
/// - *Pros*: App shell appears very quickly: great TTFB (time to first byte).
/// - *Cons*: Resources load relatively slowly; you need to wait for JS + Wasm to load before even making a request.
/// 2. **Out-of-order streaming** (`OutOfOrder`, the default): Serve an HTML shell that includes `fallback` for any `Suspense`. Load data on the **server**, streaming it down to the client as it resolves, and streaming down HTML for `Suspense` nodes.
/// - *Pros*: Combines the best of **synchronous** and `Async`, with a very fast shell and resources that begin loading on the server.
/// - *Cons*: Requires JS for suspended fragments to appear in correct order. Weaker meta tag support when it depends on data that's under suspense (has already streamed down `<head>`)
/// 3. **Partially-blocked out-of-order streaming** (`PartiallyBlocked`): Using `create_blocking_resource` with out-of-order streaming still sends fallbacks and relies on JavaScript to fill them in with the fragments. Partially-blocked streaming does this replacement on the server, making for a slower response but requiring no JavaScript to show blocking resources.
/// - *Pros*: Works better if JS is disabled.
/// - *Cons*: Slower initial response because of additional string manipulation on server.
/// 4. **In-order streaming** (`InOrder`): Walk through the tree, returning HTML synchronously as in synchronous rendering and out-of-order streaming until you hit a `Suspense`. At that point, wait for all its data to load, then render it, then the rest of the tree.
/// - *Pros*: Does not require JS for HTML to appear in correct order.
/// - *Cons*: Loads the shell more slowly than out-of-order streaming or synchronous rendering because it needs to pause at every `Suspense`. Cannot begin hydration until the entire page has loaded, so earlier pieces
/// of the page will not be interactive until the suspended chunks have loaded.
/// 5. **`Async`**: Load all resources on the server. Wait until all data are loaded, and render HTML in one sweep.
/// - *Pros*: Better handling for meta tags (because you know async data even before you render the `<head>`). Faster complete load than **synchronous** because async resources begin loading on server.
/// - *Cons*: Slower load time/TTFB: you need to wait for all async resources to load before displaying anything on the client.
/// 6. **`Static`**: Renders the page when the server starts up, or incrementally, using the
/// configuration provided by a [`StaticRoute`].
///
/// The mode defaults to out-of-order streaming. For a path that includes multiple nested routes, the most
/// restrictive mode will be used: i.e., if even a single nested route asks for `Async` rendering, the whole initial
/// request will be rendered `Async`. (`Async` is the most restricted requirement, followed by `InOrder`, `PartiallyBlocked`, and `OutOfOrder`.)
#[derive(Default, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum SsrMode {
/// **Out-of-order streaming** (`OutOfOrder`, the default): Serve an HTML shell that includes `fallback` for any `Suspense`. Load data on the **server**, streaming it down to the client as it resolves, and streaming down HTML for `Suspense` nodes.
/// - *Pros*: Combines the best of **synchronous** and `Async`, with a very fast shell and resources that begin loading on the server.
/// - *Cons*: Requires JS for suspended fragments to appear in correct order. Weaker meta tag support when it depends on data that's under suspense (has already streamed down `<head>`)
#[default]
OutOfOrder,
/// **Partially-blocked out-of-order streaming** (`PartiallyBlocked`): Using `create_blocking_resource` with out-of-order streaming still sends fallbacks and relies on JavaScript to fill them in with the fragments. Partially-blocked streaming does this replacement on the server, making for a slower response but requiring no JavaScript to show blocking resources.
/// - *Pros*: Works better if JS is disabled.
/// - *Cons*: Slower initial response because of additional string manipulation on server.
PartiallyBlocked,
/// **In-order streaming** (`InOrder`): Walk through the tree, returning HTML synchronously as in synchronous rendering and out-of-order streaming until you hit a `Suspense`. At that point, wait for all its data to load, then render it, then the rest of the tree.
/// - *Pros*: Does not require JS for HTML to appear in correct order.
/// - *Cons*: Loads the shell more slowly than out-of-order streaming or synchronous rendering because it needs to pause at every `Suspense`. Cannot begin hydration until the entire page has loaded, so earlier pieces
/// of the page will not be interactive until the suspended chunks have loaded.
InOrder,
/// **`Async`**: Load all resources on the server. Wait until all data are loaded, and render HTML in one sweep.
/// - *Pros*: Better handling for meta tags (because you know async data even before you render the `<head>`). Faster complete load than **synchronous** because async resources begin loading on server.
/// - *Cons*: Slower load time/TTFB: you need to wait for all async resources to load before displaying anything on the client.
Async,
/// **`Static`**: Renders the page when the server starts up, or incrementally, using the
/// configuration provided by a [`StaticRoute`].
Static(StaticRoute),
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/router/src/navigate.rs | router/src/navigate.rs | use crate::location::State;
/// Options that can be used to configure a navigation. Used with [use_navigate](crate::hooks::use_navigate).
#[derive(Clone, Debug)]
pub struct NavigateOptions {
/// Whether the URL being navigated to should be resolved relative to the current route.
pub resolve: bool,
/// If `true` the new location will replace the current route in the history stack, meaning
/// the "back" button will skip over the current route. (Defaults to `false`).
pub replace: bool,
/// If `true`, the router will scroll to the top of the window at the end of navigation.
/// Defaults to `true`.
pub scroll: bool,
/// [State](https://developer.mozilla.org/en-US/docs/Web/API/History/state) that should be pushed
/// onto the history stack during navigation.
pub state: State,
}
impl Default for NavigateOptions {
fn default() -> Self {
Self {
resolve: true,
replace: false,
scroll: true,
state: State::new(None),
}
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/router/src/location/history.rs | router/src/location/history.rs | use super::{handle_anchor_click, LocationChange, LocationProvider, Url};
use crate::{hooks::use_navigate, params::ParamsMap};
use core::fmt;
use futures::channel::oneshot;
use js_sys::{try_iter, Array, JsString};
use leptos::{ev, prelude::*};
use or_poisoned::OrPoisoned;
use reactive_graph::{
signal::ArcRwSignal,
traits::{ReadUntracked, Set},
};
use std::{
borrow::Cow,
string::String,
sync::{Arc, Mutex},
};
use tachys::dom::{document, window};
use wasm_bindgen::{JsCast, JsValue};
use web_sys::UrlSearchParams;
#[derive(Clone)]
pub struct BrowserUrl {
url: ArcRwSignal<Url>,
pub(crate) pending_navigation: Arc<Mutex<Option<oneshot::Sender<()>>>>,
pub(crate) path_stack: ArcStoredValue<Vec<Url>>,
pub(crate) is_back: ArcRwSignal<bool>,
}
impl fmt::Debug for BrowserUrl {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("BrowserUrl").finish_non_exhaustive()
}
}
impl BrowserUrl {
fn scroll_to_el(loc_scroll: bool) {
if let Ok(hash) = window().location().hash() {
if !hash.is_empty() {
let hash = js_sys::decode_uri(&hash[1..])
.ok()
.and_then(|decoded| decoded.as_string())
.unwrap_or(hash);
let el = document().get_element_by_id(&hash);
if let Some(el) = el {
el.scroll_into_view();
return;
}
}
}
// scroll to top
if loc_scroll {
window().scroll_to_with_x_and_y(0.0, 0.0);
}
}
}
impl LocationProvider for BrowserUrl {
type Error = JsValue;
fn new() -> Result<Self, JsValue> {
let url = ArcRwSignal::new(Self::current()?);
let path_stack = ArcStoredValue::new(
Self::current().map(|n| vec![n]).unwrap_or_default(),
);
Ok(Self {
url,
pending_navigation: Default::default(),
path_stack,
is_back: Default::default(),
})
}
fn as_url(&self) -> &ArcRwSignal<Url> {
&self.url
}
fn current() -> Result<Url, Self::Error> {
let location = window().location();
Ok(Url {
origin: location.origin()?,
path: location.pathname()?,
search: location
.search()?
.strip_prefix('?')
.map(String::from)
.unwrap_or_default(),
search_params: search_params_from_web_url(
&UrlSearchParams::new_with_str(&location.search()?)?,
)?,
hash: location.hash()?,
})
}
fn parse(url: &str) -> Result<Url, Self::Error> {
let base = window().location().origin()?;
Self::parse_with_base(url, &base)
}
fn parse_with_base(url: &str, base: &str) -> Result<Url, Self::Error> {
let location = web_sys::Url::new_with_base(url, base)?;
Ok(Url {
origin: location.origin(),
path: location.pathname(),
search: location
.search()
.strip_prefix('?')
.map(String::from)
.unwrap_or_default(),
search_params: search_params_from_web_url(
&location.search_params(),
)?,
hash: location.hash(),
})
}
fn init(&self, base: Option<Cow<'static, str>>) {
let navigate = {
let url = self.url.clone();
let pending = Arc::clone(&self.pending_navigation);
let this = self.clone();
move |new_url: Url, loc| {
let same_path = {
let curr = url.read_untracked();
curr.origin() == new_url.origin()
&& curr.path() == new_url.path()
};
url.set(new_url.clone());
if same_path {
this.complete_navigation(&loc);
}
let pending = Arc::clone(&pending);
let (tx, rx) = oneshot::channel::<()>();
if !same_path {
*pending.lock().or_poisoned() = Some(tx);
}
let url = url.clone();
let this = this.clone();
async move {
if !same_path {
// if it has been canceled, ignore
// otherwise, complete navigation -- i.e., set URL in address bar
if rx.await.is_ok() {
// only update the URL in the browser if this is still the current URL
// if we've navigated to another page in the meantime, don't update the
// browser URL
let curr = url.read_untracked();
if curr == new_url {
this.complete_navigation(&loc);
}
}
}
}
}
};
let handle_anchor_click =
handle_anchor_click(base, Self::parse_with_base, navigate);
let click_handle = window_event_listener(ev::click, move |ev| {
if let Err(e) = handle_anchor_click(ev) {
#[cfg(feature = "tracing")]
tracing::error!("{e:?}");
#[cfg(not(feature = "tracing"))]
web_sys::console::error_1(&e);
}
});
// handle popstate event (forward/back navigation)
let popstate_cb = {
let url = self.url.clone();
let path_stack = self.path_stack.clone();
let is_back = self.is_back.clone();
move || match Self::current() {
Ok(new_url) => {
let mut stack = path_stack.write_value();
let is_navigating_back = stack.len() == 1
|| (stack.len() >= 2
&& stack.get(stack.len() - 2) == Some(&new_url));
if is_navigating_back {
stack.pop();
}
is_back.set(is_navigating_back);
url.set(new_url);
}
Err(e) => {
#[cfg(feature = "tracing")]
tracing::error!("{e:?}");
#[cfg(not(feature = "tracing"))]
web_sys::console::error_1(&e);
}
}
};
let popstate_handle =
window_event_listener(ev::popstate, move |_| popstate_cb());
on_cleanup(|| {
click_handle.remove();
popstate_handle.remove();
});
}
fn ready_to_complete(&self) {
if let Some(tx) = self.pending_navigation.lock().or_poisoned().take() {
_ = tx.send(());
}
}
fn complete_navigation(&self, loc: &LocationChange) {
let history = window().history().unwrap();
let current_path = self
.path_stack
.read_value()
.last()
.map(|url| url.to_full_path());
let add_to_stack = current_path.as_ref() != Some(&loc.value);
if loc.replace {
history
.replace_state_with_url(
&loc.state.to_js_value(),
"",
Some(&loc.value),
)
.unwrap();
} else if add_to_stack {
// push the "forward direction" marker
let state = &loc.state.to_js_value();
history
.push_state_with_url(state, "", Some(&loc.value))
.unwrap();
}
// add this URL to the "path stack" for detecting back navigations, and
// unset "navigating back" state
if let Ok(url) = Self::current() {
if add_to_stack {
self.path_stack.write_value().push(url);
}
self.is_back.set(false);
}
// scroll to el
Self::scroll_to_el(loc.scroll);
}
fn redirect(loc: &str) {
let navigate = use_navigate();
let Some(url) = resolve_redirect_url(loc) else {
return; // resolve_redirect_url() already logs an error
};
let current_origin = location().origin().unwrap();
if url.origin() == current_origin {
let navigate = navigate.clone();
// delay by a tick here, so that the Action updates *before* the redirect
request_animation_frame(move || {
navigate(&url.href(), Default::default());
});
// Use set_href() if the conditions for client-side navigation were not satisfied
} else if let Err(e) = location().set_href(&url.href()) {
leptos::logging::error!("Failed to redirect: {e:#?}");
}
}
fn is_back(&self) -> ReadSignal<bool> {
self.is_back.read_only().into()
}
}
fn search_params_from_web_url(
params: &web_sys::UrlSearchParams,
) -> Result<ParamsMap, JsValue> {
try_iter(params)?
.into_iter()
.flatten()
.map(|pair| {
pair.and_then(|pair| {
let row = pair.dyn_into::<Array>()?;
Ok((
String::from(row.get(0).dyn_into::<JsString>()?),
String::from(row.get(1).dyn_into::<JsString>()?),
))
})
})
.collect()
}
/// Resolves a redirect location to an (absolute) URL.
pub(crate) fn resolve_redirect_url(loc: &str) -> Option<web_sys::Url> {
let origin = match window().location().origin() {
Ok(origin) => origin,
Err(e) => {
leptos::logging::error!("Failed to get origin: {:#?}", e);
return None;
}
};
// TODO: Use server function's URL as base instead.
let base = origin;
match web_sys::Url::new_with_base(loc, &base) {
Ok(url) => Some(url),
Err(e) => {
leptos::logging::error!(
"Invalid redirect location: {}",
e.as_string().unwrap_or_default(),
);
None
}
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/router/src/location/mod.rs | router/src/location/mod.rs | #![allow(missing_docs)]
use any_spawner::Executor;
use core::fmt::Debug;
use js_sys::Reflect;
use leptos::server::ServerActionError;
use reactive_graph::{
computed::Memo,
owner::provide_context,
signal::{ArcRwSignal, ReadSignal},
traits::With,
};
use send_wrapper::SendWrapper;
use std::{borrow::Cow, future::Future};
use tachys::dom::window;
use wasm_bindgen::{JsCast, JsValue};
use web_sys::{HtmlAnchorElement, MouseEvent};
mod history;
mod server;
use crate::params::ParamsMap;
pub use history::*;
pub use server::*;
pub(crate) const BASE: &str = "https://leptos.dev";
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct Url {
origin: String,
path: String,
search: String,
search_params: ParamsMap,
hash: String,
}
impl Url {
pub fn origin(&self) -> &str {
&self.origin
}
pub fn origin_mut(&mut self) -> &mut String {
&mut self.origin
}
pub fn path(&self) -> &str {
&self.path
}
pub fn path_mut(&mut self) -> &mut str {
&mut self.path
}
pub fn search(&self) -> &str {
&self.search
}
pub fn search_mut(&mut self) -> &mut String {
&mut self.search
}
pub fn search_params(&self) -> &ParamsMap {
&self.search_params
}
pub fn search_params_mut(&mut self) -> &mut ParamsMap {
&mut self.search_params
}
pub fn hash(&self) -> &str {
#[cfg(all(feature = "ssr", any(debug_assertions, leptos_debuginfo)))]
{
#[cfg(feature = "tracing")]
tracing::warn!(
"Reading hash on the server can lead to hydration errors."
);
#[cfg(not(feature = "tracing"))]
eprintln!(
"Reading hash on the server can lead to hydration errors."
);
}
&self.hash
}
pub fn hash_mut(&mut self) -> &mut String {
#[cfg(all(feature = "ssr", any(debug_assertions, leptos_debuginfo)))]
{
#[cfg(feature = "tracing")]
tracing::warn!(
"Reading hash on the server can lead to hydration errors."
);
#[cfg(not(feature = "tracing"))]
eprintln!(
"Reading hash on the server can lead to hydration errors."
);
}
&mut self.hash
}
pub fn provide_server_action_error(&self) {
let search_params = self.search_params();
if let (Some(err), Some(path)) = (
search_params.get_str("__err"),
search_params.get_str("__path"),
) {
provide_context(ServerActionError::new(path, err))
}
}
pub(crate) fn to_full_path(&self) -> String {
let mut path = self.path.to_string();
if !self.search.is_empty() {
path.push('?');
path.push_str(&self.search);
}
if !self.hash.is_empty() {
if !self.hash.starts_with('#') {
path.push('#');
}
path.push_str(&self.hash);
}
path
}
pub fn escape(s: &str) -> String {
#[cfg(not(feature = "ssr"))]
{
js_sys::encode_uri_component(s).as_string().unwrap()
}
#[cfg(feature = "ssr")]
{
percent_encoding::utf8_percent_encode(
s,
percent_encoding::NON_ALPHANUMERIC,
)
.to_string()
}
}
pub fn unescape(s: &str) -> String {
#[cfg(feature = "ssr")]
{
percent_encoding::percent_decode_str(s)
.decode_utf8()
.unwrap()
.to_string()
}
#[cfg(not(feature = "ssr"))]
{
match js_sys::decode_uri_component(s) {
Ok(v) => v.into(),
Err(_) => s.into(),
}
}
}
pub fn unescape_minimal(s: &str) -> String {
#[cfg(not(feature = "ssr"))]
{
match js_sys::decode_uri(s) {
Ok(v) => v.into(),
Err(_) => s.into(),
}
}
#[cfg(feature = "ssr")]
{
Self::unescape(s)
}
}
}
/// A reactive description of the current URL, containing equivalents to the local parts of
/// the browser's [`Location`](https://developer.mozilla.org/en-US/docs/Web/API/Location).
#[derive(Debug, Clone, PartialEq)]
pub struct Location {
/// The path of the URL, not containing the query string or hash fragment.
pub pathname: Memo<String>,
/// The raw query string.
pub search: Memo<String>,
/// The query string parsed into its key-value pairs.
pub query: Memo<ParamsMap>,
/// The hash fragment.
pub hash: Memo<String>,
/// The [`state`](https://developer.mozilla.org/en-US/docs/Web/API/History/state) at the top of the history stack.
pub state: ReadSignal<State>,
}
impl Location {
pub(crate) fn new(
url: impl Into<ReadSignal<Url>>,
state: impl Into<ReadSignal<State>>,
) -> Self {
let url = url.into();
let state = state.into();
let pathname = Memo::new(move |_| url.with(|url| url.path.clone()));
let search = Memo::new(move |_| url.with(|url| url.search.clone()));
let hash = Memo::new(move |_| url.with(|url| url.hash().to_string()));
let query =
Memo::new(move |_| url.with(|url| url.search_params.clone()));
Location {
pathname,
search,
query,
hash,
state,
}
}
}
/// A description of a navigation.
#[derive(Debug, Clone, PartialEq)]
pub struct LocationChange {
/// The new URL.
pub value: String,
/// If true, the new location will replace the current one in the history stack, i.e.,
/// clicking the "back" button will not return to the current location.
pub replace: bool,
/// If true, the router will scroll to the top of the page at the end of the navigation.
pub scroll: bool,
/// The [`state`](https://developer.mozilla.org/en-US/docs/Web/API/History/state) that will be added during navigation.
pub state: State,
}
impl Default for LocationChange {
fn default() -> Self {
Self {
value: Default::default(),
replace: true,
scroll: true,
state: Default::default(),
}
}
}
pub trait LocationProvider: Clone + 'static {
type Error: Debug;
fn new() -> Result<Self, Self::Error>;
fn as_url(&self) -> &ArcRwSignal<Url>;
fn current() -> Result<Url, Self::Error>;
/// Sets up any global event listeners or other initialization needed.
fn init(&self, base: Option<Cow<'static, str>>);
/// Should be called after a navigation when all route components and data have been loaded and
/// the URL can be updated.
fn ready_to_complete(&self);
/// Update the browser's history to reflect a new location.
fn complete_navigation(&self, loc: &LocationChange);
fn parse(url: &str) -> Result<Url, Self::Error> {
Self::parse_with_base(url, BASE)
}
fn parse_with_base(url: &str, base: &str) -> Result<Url, Self::Error>;
fn redirect(loc: &str);
/// Whether we are currently in a "back" navigation.
fn is_back(&self) -> ReadSignal<bool>;
}
#[derive(Debug, Clone, Default)]
pub struct State(Option<SendWrapper<JsValue>>);
impl State {
pub fn new(state: Option<JsValue>) -> Self {
Self(state.map(SendWrapper::new))
}
pub fn to_js_value(&self) -> JsValue {
match &self.0 {
Some(v) => v.clone().take(),
None => JsValue::UNDEFINED,
}
}
}
impl PartialEq for State {
fn eq(&self, other: &Self) -> bool {
self.0.as_ref().map(|n| n.as_ref())
== other.0.as_ref().map(|n| n.as_ref())
}
}
impl<T> From<T> for State
where
T: Into<JsValue>,
{
fn from(value: T) -> Self {
State::new(Some(value.into()))
}
}
pub(crate) fn handle_anchor_click<NavFn, NavFut>(
router_base: Option<Cow<'static, str>>,
parse_with_base: fn(&str, &str) -> Result<Url, JsValue>,
navigate: NavFn,
) -> Box<dyn Fn(MouseEvent) -> Result<(), JsValue>>
where
NavFn: Fn(Url, LocationChange) -> NavFut + 'static,
NavFut: Future<Output = ()> + 'static,
{
let router_base = router_base.unwrap_or_default();
Box::new(move |ev: MouseEvent| {
let origin = window().location().origin()?;
if ev.default_prevented()
|| ev.button() != 0
|| ev.meta_key()
|| ev.alt_key()
|| ev.ctrl_key()
|| ev.shift_key()
{
return Ok(());
}
let composed_path = ev.composed_path();
let mut a: Option<HtmlAnchorElement> = None;
for i in 0..composed_path.length() {
if let Ok(el) = composed_path.get(i).dyn_into::<HtmlAnchorElement>()
{
a = Some(el);
}
}
if let Some(a) = a {
let href = a.href();
let target = a.target();
// let browser handle this event if link has target,
// or if it doesn't have href or state
// TODO "state" is set as a prop, not an attribute
if !target.is_empty()
|| (href.is_empty() && !a.has_attribute("state"))
{
return Ok(());
}
let rel = a.get_attribute("rel").unwrap_or_default();
let mut rel = rel.split([' ', '\t']);
// let browser handle event if it has rel=external or download
if a.has_attribute("download") || rel.any(|p| p == "external") {
return Ok(());
}
let url = parse_with_base(href.as_str(), &origin).unwrap();
let path_name = Url::unescape_minimal(&url.path);
// let browser handle this event if it leaves our domain
// or our base path
if url.origin != origin
|| (!router_base.is_empty()
&& !path_name.is_empty()
// NOTE: the two `to_lowercase()` calls here added a total of about 14kb to
// release binary size, for limited gain
&& !path_name.starts_with(&*router_base))
{
return Ok(());
}
// we've passed all the checks to navigate on the client side, so we prevent the
// default behavior of the click
ev.prevent_default();
let to = path_name
+ if url.search.is_empty() { "" } else { "?" }
+ &url.search
+ &url.hash;
let state = Reflect::get(&a, &JsValue::from_str("state"))
.ok()
.and_then(|value| {
if value == JsValue::UNDEFINED {
None
} else {
Some(value)
}
});
let replace = Reflect::get(&a, &JsValue::from_str("replace"))
.ok()
.and_then(|value| value.as_bool())
.unwrap_or(false);
let change = LocationChange {
value: to,
replace,
scroll: !a.has_attribute("noscroll")
&& !a.has_attribute("data-noscroll"),
state: State::new(state),
};
Executor::spawn_local(navigate(url, change));
}
Ok(())
})
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/router/src/location/server.rs | router/src/location/server.rs | use super::{Url, BASE};
use crate::params::ParamsMap;
use std::sync::Arc;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RequestUrl(Arc<str>);
impl RequestUrl {
/// Creates a server-side request URL from a path.
pub fn new(path: &str) -> Self {
Self(path.into())
}
}
impl AsRef<str> for RequestUrl {
fn as_ref(&self) -> &str {
&self.0
}
}
impl Default for RequestUrl {
fn default() -> Self {
Self::new("/")
}
}
impl RequestUrl {
pub fn parse(&self) -> Result<Url, url::ParseError> {
self.parse_with_base(BASE)
}
pub fn parse_with_base(&self, base: &str) -> Result<Url, url::ParseError> {
let base = url::Url::parse(base)?;
let url = url::Url::options().base_url(Some(&base)).parse(&self.0)?;
let search_params = url
.query_pairs()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect::<ParamsMap>();
Ok(Url {
origin: url.origin().unicode_serialization(),
path: url.path().to_string(),
search: url.query().unwrap_or_default().to_string(),
search_params,
hash: Default::default(),
})
}
}
#[cfg(test)]
mod tests {
use super::RequestUrl;
#[test]
pub fn should_parse_url_without_origin() {
let url = RequestUrl::new("/foo/bar").parse().unwrap();
assert_eq!(url.path(), "/foo/bar");
}
#[test]
pub fn should_not_parse_url_without_slash() {
let url = RequestUrl::new("foo/bar").parse().unwrap();
assert_eq!(url.path(), "/foo/bar");
}
#[test]
pub fn should_parse_with_base() {
let url = RequestUrl::new("https://www.example.com/foo/bar")
.parse()
.unwrap();
assert_eq!(url.origin(), "https://www.example.com");
assert_eq!(url.path(), "/foo/bar");
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/router/src/matching/choose_view.rs | router/src/matching/choose_view.rs | use either_of::*;
use leptos::prelude::{ArcStoredValue, WriteValue};
use std::{future::Future, marker::PhantomData};
use tachys::view::any_view::{AnyView, IntoAny};
pub trait ChooseView
where
Self: Send + Clone + 'static,
{
fn choose(self) -> impl Future<Output = AnyView>;
fn preload(&self) -> impl Future<Output = ()>;
}
impl<F, View> ChooseView for F
where
F: Fn() -> View + Send + Clone + 'static,
View: IntoAny,
{
async fn choose(self) -> AnyView {
self().into_any()
}
async fn preload(&self) {}
}
impl<T> ChooseView for Lazy<T>
where
T: Send + Sync + LazyRoute,
{
async fn choose(self) -> AnyView {
let data = self.data.write_value().take().unwrap_or_else(T::data);
T::view(data).await
}
async fn preload(&self) {
*self.data.write_value() = Some(T::data());
T::preload().await;
}
}
pub trait LazyRoute: Send + 'static {
fn data() -> Self;
fn view(this: Self) -> impl Future<Output = AnyView>;
fn preload() -> impl Future<Output = ()> {
async {}
}
}
#[derive(Debug)]
pub struct Lazy<T> {
ty: PhantomData<T>,
data: ArcStoredValue<Option<T>>,
}
impl<T> Clone for Lazy<T> {
fn clone(&self) -> Self {
Self {
ty: self.ty,
data: self.data.clone(),
}
}
}
impl<T> Lazy<T> {
pub fn new() -> Self {
Self::default()
}
}
impl<T> Default for Lazy<T> {
fn default() -> Self {
Self {
ty: Default::default(),
data: ArcStoredValue::new(None),
}
}
}
impl ChooseView for () {
async fn choose(self) -> AnyView {
().into_any()
}
async fn preload(&self) {}
}
impl<A, B> ChooseView for Either<A, B>
where
A: ChooseView,
B: ChooseView,
{
async fn choose(self) -> AnyView {
match self {
Either::Left(f) => f.choose().await.into_any(),
Either::Right(f) => f.choose().await.into_any(),
}
}
async fn preload(&self) {
match self {
Either::Left(f) => f.preload().await,
Either::Right(f) => f.preload().await,
}
}
}
macro_rules! tuples {
($either:ident => $($ty:ident),*) => {
impl<$($ty,)*> ChooseView for $either<$($ty,)*>
where
$($ty: ChooseView,)*
{
async fn choose(self) -> AnyView {
match self {
$(
$either::$ty(f) => f.choose().await.into_any(),
)*
}
}
async fn preload(&self) {
match self {
$($either::$ty(f) => f.preload().await,)*
}
}
}
};
}
tuples!(EitherOf3 => A, B, C);
tuples!(EitherOf4 => A, B, C, D);
tuples!(EitherOf5 => A, B, C, D, E);
tuples!(EitherOf6 => A, B, C, D, E, F);
tuples!(EitherOf7 => A, B, C, D, E, F, G);
tuples!(EitherOf8 => A, B, C, D, E, F, G, H);
tuples!(EitherOf9 => A, B, C, D, E, F, G, H, I);
tuples!(EitherOf10 => A, B, C, D, E, F, G, H, I, J);
tuples!(EitherOf11 => A, B, C, D, E, F, G, H, I, J, K);
tuples!(EitherOf12 => A, B, C, D, E, F, G, H, I, J, K, L);
tuples!(EitherOf13 => A, B, C, D, E, F, G, H, I, J, K, L, M);
tuples!(EitherOf14 => A, B, C, D, E, F, G, H, I, J, K, L, M, N);
tuples!(EitherOf15 => A, B, C, D, E, F, G, H, I, J, K, L, M, N, O);
tuples!(EitherOf16 => A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P);
/// A version of [`IntoMaybeErased`] for the [`ChooseView`] trait.
pub trait IntoChooseViewMaybeErased {
/// The type of the erased view.
type Output: IntoChooseViewMaybeErased;
/// Erase the type of the view.
fn into_maybe_erased(self) -> Self::Output;
}
impl<T> IntoChooseViewMaybeErased for T
where
T: ChooseView + Send + Clone + 'static,
{
#[cfg(erase_components)]
type Output = crate::matching::any_choose_view::AnyChooseView;
#[cfg(not(erase_components))]
type Output = Self;
fn into_maybe_erased(self) -> Self::Output {
#[cfg(erase_components)]
{
crate::matching::any_choose_view::AnyChooseView::new(self)
}
#[cfg(not(erase_components))]
{
self
}
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/router/src/matching/any_choose_view.rs | router/src/matching/any_choose_view.rs | use super::ChooseView;
use futures::FutureExt;
use std::{future::Future, pin::Pin};
use tachys::{erased::Erased, view::any_view::AnyView};
/// A type-erased [`ChooseView`].
pub struct AnyChooseView {
value: Erased,
clone: fn(&Erased) -> AnyChooseView,
#[allow(clippy::type_complexity)]
choose: fn(Erased) -> Pin<Box<dyn Future<Output = AnyView>>>,
preload: for<'a> fn(&'a Erased) -> Pin<Box<dyn Future<Output = ()> + 'a>>,
}
impl Clone for AnyChooseView {
fn clone(&self) -> Self {
(self.clone)(&self.value)
}
}
impl AnyChooseView {
pub(crate) fn new<T: ChooseView>(value: T) -> Self {
fn clone<T: ChooseView>(value: &Erased) -> AnyChooseView {
AnyChooseView::new(value.get_ref::<T>().clone())
}
fn choose<T: ChooseView>(
value: Erased,
) -> Pin<Box<dyn Future<Output = AnyView>>> {
value.into_inner::<T>().choose().boxed_local()
}
fn preload<'a, T: ChooseView>(
value: &'a Erased,
) -> Pin<Box<dyn Future<Output = ()> + 'a>> {
value.get_ref::<T>().preload().boxed_local()
}
Self {
value: Erased::new(value),
clone: clone::<T>,
choose: choose::<T>,
preload: preload::<T>,
}
}
}
impl ChooseView for AnyChooseView {
async fn choose(self) -> AnyView {
(self.choose)(self.value).await
}
async fn preload(&self) {
(self.preload)(&self.value).await;
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/router/src/matching/mod.rs | router/src/matching/mod.rs | #![allow(missing_docs)]
mod any_choose_view;
mod choose_view;
mod path_segment;
pub(crate) mod resolve_path;
pub use choose_view::*;
pub use path_segment::*;
mod horizontal;
mod nested;
mod vertical;
use crate::{static_routes::RegenerationFn, Method, SsrMode};
pub use horizontal::*;
pub use nested::*;
use std::{borrow::Cow, collections::HashSet, sync::atomic::Ordering};
pub use vertical::*;
#[derive(Debug)]
pub struct RouteDefs<Children> {
base: Option<Cow<'static, str>>,
children: Children,
}
impl<Children> Clone for RouteDefs<Children>
where
Children: Clone,
{
fn clone(&self) -> Self {
Self {
base: self.base.clone(),
children: self.children.clone(),
}
}
}
impl<Children> RouteDefs<Children> {
pub fn new(children: Children) -> Self {
Self {
base: None,
children,
}
}
pub fn new_with_base(
children: Children,
base: impl Into<Cow<'static, str>>,
) -> Self {
Self {
base: Some(base.into()),
children,
}
}
}
impl<Children> RouteDefs<Children>
where
Children: MatchNestedRoutes,
{
pub fn match_route(&self, path: &str) -> Option<Children::Match> {
let path = match &self.base {
None => path,
Some(base) => {
let (base, path) = if base.starts_with('/') {
(base.trim_start_matches('/'), path.trim_start_matches('/'))
} else {
(base.as_ref(), path)
};
path.strip_prefix(base)?
}
};
let (matched, remaining) = self.children.match_nested(path);
let matched = matched?;
if !(remaining.is_empty() || remaining == "/") {
None
} else {
Some(matched.1)
}
}
pub fn generate_routes(
&self,
) -> (
Option<&str>,
impl IntoIterator<Item = GeneratedRouteData> + '_,
) {
(self.base.as_deref(), self.children.generate_routes())
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct RouteMatchId(pub(crate) u16);
impl RouteMatchId {
/// Creates a new match ID based on the current route ID used in nested route generation.
///
/// In general, you do not need this; it should only be used for custom route matching behavior
/// in a library that creates its own route types.
pub fn new_from_route_id() -> RouteMatchId {
RouteMatchId(ROUTE_ID.fetch_add(1, Ordering::Relaxed))
}
}
pub trait MatchInterface {
type Child: MatchInterface + MatchParams + 'static;
fn as_id(&self) -> RouteMatchId;
fn as_matched(&self) -> &str;
fn into_view_and_child(self) -> (impl ChooseView, Option<Self::Child>);
}
pub trait MatchParams {
fn to_params(&self) -> Vec<(Cow<'static, str>, String)>;
}
pub trait MatchNestedRoutes {
type Data;
type Match: MatchInterface + MatchParams;
/// Matches nested routes
///
/// # Arguments
///
/// * path - A path which is being navigated to
///
/// # Returns
///
/// Tuple where
///
/// * 0 - If match has been found `Some` containing tuple where
/// * 0 - [RouteMatchId] identifying the matching route
/// * 1 - [Self::Match] matching route
/// * 1 - Remaining path
fn match_nested<'a>(
&'a self,
path: &'a str,
) -> (Option<(RouteMatchId, Self::Match)>, &'a str);
fn generate_routes(
&self,
) -> impl IntoIterator<Item = GeneratedRouteData> + '_;
fn optional(&self) -> bool;
}
#[derive(Default, Debug, PartialEq)]
pub struct GeneratedRouteData {
pub segments: Vec<PathSegment>,
pub ssr_mode: SsrMode,
pub methods: HashSet<Method>,
pub regenerate: Vec<RegenerationFn>,
}
#[cfg(test)]
mod tests {
use super::{NestedRoute, ParamSegment, RouteDefs};
use crate::{
matching::MatchParams, MatchInterface, PathSegment, StaticSegment,
WildcardSegment,
};
use either_of::{Either, EitherOf4};
#[test]
pub fn matches_single_root_route() {
let routes =
RouteDefs::<_>::new(NestedRoute::new(StaticSegment("/"), || ()));
let matched = routes.match_route("/");
assert!(matched.is_some());
// this case seems like it should match, but implementing it interferes with
// handling trailing slash requirements accurately -- paths for the root are "/",
// not "", in any case
let matched = routes.match_route("");
assert!(matched.is_none());
let (base, paths) = routes.generate_routes();
assert_eq!(base, None);
let paths = paths.into_iter().map(|g| g.segments).collect::<Vec<_>>();
assert_eq!(paths, vec![vec![PathSegment::Static("/".into())]]);
}
#[test]
pub fn matches_nested_route() {
let routes: RouteDefs<_> = RouteDefs::new(
NestedRoute::new(StaticSegment(""), || "Home").child(
NestedRoute::new(
(StaticSegment("author"), StaticSegment("contact")),
|| "Contact Me",
),
),
);
// route generation
let (base, paths) = routes.generate_routes();
assert_eq!(base, None);
let paths = paths.into_iter().map(|g| g.segments).collect::<Vec<_>>();
assert_eq!(
paths,
vec![vec![
PathSegment::Static("".into()),
PathSegment::Static("author".into()),
PathSegment::Static("contact".into())
]]
);
let matched = routes.match_route("/author/contact").unwrap();
assert_eq!(MatchInterface::as_matched(&matched), "");
let (_, child) = MatchInterface::into_view_and_child(matched);
assert_eq!(
MatchInterface::as_matched(&child.unwrap()),
"/author/contact"
);
}
#[test]
pub fn does_not_match_route_unless_full_param_matches() {
let routes = RouteDefs::<_>::new((
NestedRoute::new(StaticSegment("/property-api"), || ()),
NestedRoute::new(StaticSegment("/property"), || ()),
));
let matched = routes.match_route("/property").unwrap();
assert!(matches!(matched, Either::Right(_)));
}
#[test]
pub fn does_not_match_incomplete_route() {
let routes: RouteDefs<_> = RouteDefs::new(
NestedRoute::new(StaticSegment(""), || "Home").child(
NestedRoute::new(
(StaticSegment("author"), StaticSegment("contact")),
|| "Contact Me",
),
),
);
let matched = routes.match_route("/");
assert!(matched.is_none());
}
#[test]
pub fn chooses_between_nested_routes() {
let routes: RouteDefs<_> = RouteDefs::new((
NestedRoute::new(StaticSegment("/"), || ()).child((
NestedRoute::new(StaticSegment(""), || ()),
NestedRoute::new(StaticSegment("about"), || ()),
)),
NestedRoute::new(StaticSegment("/blog"), || ()).child((
NestedRoute::new(StaticSegment(""), || ()),
NestedRoute::new(
(StaticSegment("post"), ParamSegment("id")),
|| (),
),
)),
));
// generates routes correctly
let (base, paths) = routes.generate_routes();
assert_eq!(base, None);
let paths = paths.into_iter().map(|g| g.segments).collect::<Vec<_>>();
assert_eq!(
paths,
vec![
vec![
PathSegment::Static("/".into()),
PathSegment::Static("".into()),
],
vec![
PathSegment::Static("/".into()),
PathSegment::Static("about".into())
],
vec![
PathSegment::Static("/blog".into()),
PathSegment::Static("".into()),
],
vec![
PathSegment::Static("/blog".into()),
PathSegment::Static("post".into()),
PathSegment::Param("id".into())
]
]
);
let matched = routes.match_route("/about").unwrap();
let params = matched.to_params();
assert!(params.is_empty());
let matched = routes.match_route("/blog").unwrap();
let params = matched.to_params();
assert!(params.is_empty());
let matched = routes.match_route("/blog/post/42").unwrap();
let params = matched.to_params();
assert_eq!(params, vec![("id".into(), "42".into())]);
}
#[test]
pub fn arbitrary_nested_routes() {
let routes: RouteDefs<_> = RouteDefs::new_with_base(
(
NestedRoute::new(StaticSegment("/"), || ()).child((
NestedRoute::new(StaticSegment("/"), || ()),
NestedRoute::new(StaticSegment("about"), || ()),
)),
NestedRoute::new(StaticSegment("/blog"), || ()).child((
NestedRoute::new(StaticSegment(""), || ()),
NestedRoute::new(StaticSegment("category"), || ()),
NestedRoute::new(
(StaticSegment("post"), ParamSegment("id")),
|| (),
),
)),
NestedRoute::new(
(StaticSegment("/contact"), WildcardSegment("any")),
|| (),
),
),
"/portfolio",
);
// generates routes correctly
let (base, _paths) = routes.generate_routes();
assert_eq!(base, Some("/portfolio"));
let matched = routes.match_route("/about");
assert!(matched.is_none());
let matched = routes.match_route("/portfolio/about").unwrap();
let params = matched.to_params();
assert!(params.is_empty());
let matched = routes.match_route("/portfolio/blog/post/42").unwrap();
let params = matched.to_params();
assert_eq!(params, vec![("id".into(), "42".into())]);
let matched = routes.match_route("/portfolio/contact").unwrap();
let params = matched.to_params();
assert_eq!(params, vec![("any".into(), "".into())]);
let matched = routes.match_route("/portfolio/contact/foobar").unwrap();
let params = matched.to_params();
assert_eq!(params, vec![("any".into(), "foobar".into())]);
}
#[test]
pub fn dont_match_smooshed_static_segments() {
let routes = RouteDefs::<_>::new((
NestedRoute::new(StaticSegment(""), || ()),
NestedRoute::new(StaticSegment("users"), || ()),
NestedRoute::new(
(StaticSegment("users"), StaticSegment("id")),
|| (),
),
NestedRoute::new(WildcardSegment("any"), || ()),
));
let matched = routes.match_route("/users");
assert!(matches!(matched, Some(EitherOf4::B(..))));
let matched = routes.match_route("/users/id");
assert!(matches!(matched, Some(EitherOf4::C(..))));
let matched = routes.match_route("/usersid");
assert!(matches!(matched, Some(EitherOf4::D(..))));
}
}
/// Successful result of [testing](PossibleRouteMatch::test) a single segment in the route path
#[derive(Debug)]
pub struct PartialPathMatch<'a> {
/// unmatched yet part of the path
pub(crate) remaining: &'a str,
/// value of parameters encoded inside of the path
pub(crate) params: Vec<(Cow<'static, str>, String)>,
/// part of the original path that was matched by segment
pub(crate) matched: &'a str,
}
impl<'a> PartialPathMatch<'a> {
pub fn new(
remaining: &'a str,
params: Vec<(Cow<'static, str>, String)>,
matched: &'a str,
) -> Self {
Self {
remaining,
params,
matched,
}
}
pub fn is_complete(&self) -> bool {
self.remaining.is_empty() || self.remaining == "/"
}
pub fn remaining(&self) -> &'a str {
self.remaining
}
pub fn params(self) -> Vec<(Cow<'static, str>, String)> {
self.params
}
pub fn matched(&self) -> &'a str {
self.matched
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/router/src/matching/path_segment.rs | router/src/matching/path_segment.rs | use std::borrow::Cow;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PathSegment {
Unit,
Static(Cow<'static, str>),
Param(Cow<'static, str>),
OptionalParam(Cow<'static, str>),
Splat(Cow<'static, str>),
}
impl PathSegment {
pub fn as_raw_str(&self) -> &str {
match self {
PathSegment::Unit => "",
PathSegment::Static(i) => i,
PathSegment::Param(i) => i,
PathSegment::OptionalParam(i) => i,
PathSegment::Splat(i) => i,
}
}
}
pub trait ExpandOptionals {
fn expand_optionals(&self) -> Vec<Vec<PathSegment>>;
}
impl ExpandOptionals for Vec<PathSegment> {
fn expand_optionals(&self) -> Vec<Vec<PathSegment>> {
let mut segments = vec![self.to_vec()];
let mut checked = Vec::new();
while let Some(next_to_check) = segments.pop() {
let mut had_optional = false;
for (idx, segment) in next_to_check.iter().enumerate() {
if let PathSegment::OptionalParam(name) = segment {
had_optional = true;
let mut unit_variant = next_to_check.to_vec();
unit_variant.remove(idx);
let mut param_variant = next_to_check.to_vec();
param_variant[idx] = PathSegment::Param(name.clone());
segments.push(unit_variant);
segments.push(param_variant);
break;
}
}
if !had_optional {
checked.push(next_to_check.to_vec());
}
}
checked
}
}
#[cfg(test)]
mod tests {
use crate::{ExpandOptionals, PathSegment};
#[test]
fn expand_optionals_on_plain() {
let plain = vec![
PathSegment::Static("a".into()),
PathSegment::Param("b".into()),
];
assert_eq!(plain.expand_optionals(), vec![plain]);
}
#[test]
fn expand_optionals_once() {
let plain = vec![
PathSegment::OptionalParam("a".into()),
PathSegment::Static("b".into()),
];
assert_eq!(
plain.expand_optionals(),
vec![
vec![
PathSegment::Param("a".into()),
PathSegment::Static("b".into())
],
vec![PathSegment::Static("b".into())]
]
);
}
#[test]
fn expand_optionals_twice() {
let plain = vec![
PathSegment::OptionalParam("a".into()),
PathSegment::OptionalParam("b".into()),
PathSegment::Static("c".into()),
];
assert_eq!(
plain.expand_optionals(),
vec![
vec![
PathSegment::Param("a".into()),
PathSegment::Param("b".into()),
PathSegment::Static("c".into()),
],
vec![
PathSegment::Param("a".into()),
PathSegment::Static("c".into()),
],
vec![
PathSegment::Param("b".into()),
PathSegment::Static("c".into()),
],
vec![PathSegment::Static("c".into())]
]
);
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/router/src/matching/resolve_path.rs | router/src/matching/resolve_path.rs | use std::borrow::Cow;
pub fn resolve_path<'a>(
base: &'a str,
path: &'a str,
from: Option<&'a str>,
) -> Cow<'a, str> {
if has_scheme(path) {
path.into()
} else {
let base_path = normalize(base, false);
let from_path = from.map(|from| normalize(from, false));
let result = if let Some(from_path) = from_path {
if path.starts_with('/') {
base_path
} else if from_path.find(base_path.as_ref()) != Some(0) {
base_path + from_path
} else {
from_path
}
} else {
base_path
};
let result_empty = result.is_empty();
let prefix = if result_empty { "/".into() } else { result };
prefix + normalize(path, result_empty)
}
}
fn has_scheme(path: &str) -> bool {
path.starts_with("//")
|| path.starts_with("tel:")
|| path.starts_with("mailto:")
|| path
.split_once("://")
.map(|(prefix, _)| {
prefix.chars().all(
|c: char| matches!(c, 'a'..='z' | 'A'..='Z' | '0'..='9'),
)
})
.unwrap_or(false)
}
#[doc(hidden)]
fn normalize(path: &str, omit_slash: bool) -> Cow<'_, str> {
let s = path.trim_start_matches('/');
let trim_end = s
.chars()
.rev()
.take_while(|c| *c == '/')
.count()
.saturating_sub(1);
let s = &s[0..s.len() - trim_end];
if s.is_empty() || omit_slash || begins_with_query_or_hash(s) {
s.into()
} else {
format!("/{s}").into()
}
}
fn begins_with_query_or_hash(text: &str) -> bool {
matches!(text.chars().next(), Some('#') | Some('?'))
}
/* TODO can remove?
#[doc(hidden)]
pub fn join_paths<'a>(from: &'a str, to: &'a str) -> String {
let from = remove_wildcard(&normalize(from, false));
from + normalize(to, false).as_ref()
}
fn remove_wildcard(text: &str) -> String {
text.rsplit_once('*')
.map(|(prefix, _)| prefix)
.unwrap_or(text)
.trim_end_matches('/')
.to_string()
}
*/
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn normalize_query_string_with_opening_slash() {
assert_eq!(normalize("/?foo=bar", false), "?foo=bar");
}
#[test]
fn normalize_retain_trailing_slash() {
assert_eq!(normalize("foo/bar/", false), "/foo/bar/");
}
#[test]
fn normalize_dedup_trailing_slashes() {
assert_eq!(normalize("foo/bar/////", false), "/foo/bar/");
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/router/src/matching/horizontal/static_segment.rs | router/src/matching/horizontal/static_segment.rs | use super::{PartialPathMatch, PathSegment, PossibleRouteMatch};
use std::fmt::Debug;
impl PossibleRouteMatch for () {
fn optional(&self) -> bool {
false
}
fn test<'a>(&self, path: &'a str) -> Option<PartialPathMatch<'a>> {
Some(PartialPathMatch::new(path, vec![], ""))
}
fn generate_path(&self, _path: &mut Vec<PathSegment>) {}
}
pub trait AsPath {
fn as_path(&self) -> &'static str;
}
impl AsPath for &'static str {
fn as_path(&self) -> &'static str {
self
}
}
/// A segment that is expected to be static. Not requiring mapping into params.
///
/// Should work exactly as you would expect.
///
/// # Examples
/// ```rust
/// # (|| -> Option<()> { // Option does not impl Terminate, so no main
/// use leptos::prelude::*;
/// use leptos_router::{path, PossibleRouteMatch, StaticSegment};
///
/// let path = &"/users";
///
/// // Manual definition
/// let manual = (StaticSegment("users"),);
/// let matched = manual.test(path)?;
/// assert_eq!(matched.matched(), "/users");
///
/// // Params are empty as we had no `ParamSegement`s or `WildcardSegment`s
/// // If you did have additional dynamic segments, this would not be empty.
/// assert_eq!(matched.params().len(), 0);
///
/// // Macro definition
/// let using_macro = path!("/users");
/// let matched = manual.test(path)?;
/// assert_eq!(matched.matched(), "/users");
///
/// assert_eq!(matched.params().len(), 0);
///
/// # Some(())
/// # })().unwrap();
/// ```
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct StaticSegment<T: AsPath>(pub T);
impl<T: AsPath> PossibleRouteMatch for StaticSegment<T> {
fn optional(&self) -> bool {
false
}
fn test<'a>(&self, path: &'a str) -> Option<PartialPathMatch<'a>> {
let mut matched_len = 0;
let mut test = path.chars().peekable();
let mut this = self.0.as_path().chars();
let mut has_matched =
self.0.as_path().is_empty() || self.0.as_path() == "/";
// match an initial /
if let Some('/') = test.peek() {
test.next();
if !self.0.as_path().is_empty() {
matched_len += 1;
}
if self.0.as_path().starts_with('/') || self.0.as_path().is_empty()
{
this.next();
}
} else if !path.is_empty() {
// Path must start with `/` otherwise we are not certain about being at the beginning of the segment in the path
return None;
}
for char in test {
let n = this.next();
// when we get a closing /, stop matching
if char == '/' {
if n.is_some() {
return None;
}
break;
} else if n.is_none() {
break;
}
// if the next character in the path matches the
// next character in the segment, add it to the match
else if Some(char) == n {
has_matched = true;
matched_len += char.len_utf8();
}
// otherwise, this route doesn't match and we should
// return None
else {
return None;
}
}
// if we still have remaining, unmatched characters in this segment, it was not a match
if this.next().is_some() {
return None;
}
// build the match object
let (matched, remaining) = if matched_len == 1 && path.starts_with('/')
{
// If only thing that matched is `/` we can't eat it, otherwise next invocation of the
// test function will not be able to tell that we are matching from the beginning of the path segment
("/", path)
} else {
// the remaining is built from the path in, with the slice moved
// by the length of this match
path.split_at(matched_len)
};
has_matched.then(|| PartialPathMatch::new(remaining, vec![], matched))
}
fn generate_path(&self, path: &mut Vec<PathSegment>) {
path.push(PathSegment::Static(self.0.as_path().into()))
}
}
#[cfg(test)]
mod tests {
use super::{PossibleRouteMatch, StaticSegment};
use crate::AsPath;
#[derive(Debug, Clone)]
enum Paths {
Foo,
Bar,
}
impl AsPath for Paths {
fn as_path(&self) -> &'static str {
match self {
Foo => "foo",
Bar => "bar",
}
}
}
use Paths::*;
#[test]
fn single_static_match() {
let path = "/foo";
let def = StaticSegment("foo");
let matched = def.test(path).expect("couldn't match route");
assert_eq!(matched.matched(), "/foo");
assert_eq!(matched.remaining(), "");
let params = matched.params();
assert!(params.is_empty());
}
#[test]
fn single_static_match_on_enum() {
let path = "/foo";
let def = StaticSegment(Foo);
let matched = def.test(path).expect("couldn't match route");
assert_eq!(matched.matched(), "/foo");
assert_eq!(matched.remaining(), "");
let params = matched.params();
assert!(params.is_empty());
}
#[test]
fn single_static_mismatch() {
let path = "/foo";
let def = StaticSegment("bar");
assert!(def.test(path).is_none());
}
#[test]
fn single_static_mismatch_on_enum() {
let path = "/foo";
let def = StaticSegment(Bar);
assert!(def.test(path).is_none());
}
#[test]
fn single_static_match_with_trailing_slash() {
let path = "/foo/";
let def = StaticSegment("foo");
let matched = def.test(path).expect("couldn't match route");
assert_eq!(matched.matched(), "/foo");
assert_eq!(matched.remaining(), "/");
let params = matched.params();
assert!(params.is_empty());
}
#[test]
fn single_static_match_with_trailing_slash_on_enum() {
let path = "/foo/";
let def = StaticSegment(Foo);
let matched = def.test(path).expect("couldn't match route");
assert_eq!(matched.matched(), "/foo");
assert_eq!(matched.remaining(), "/");
let params = matched.params();
assert!(params.is_empty());
}
#[test]
fn tuple_of_static_matches() {
let path = "/foo/bar";
let def = (StaticSegment("foo"), StaticSegment("bar"));
let matched = def.test(path).expect("couldn't match route");
assert_eq!(matched.matched(), "/foo/bar");
assert_eq!(matched.remaining(), "");
let params = matched.params();
assert!(params.is_empty());
}
#[test]
fn tuple_of_static_matches_on_enum() {
let path = "/foo/bar";
let def = (StaticSegment(Foo), StaticSegment(Bar));
let matched = def.test(path).expect("couldn't match route");
assert_eq!(matched.matched(), "/foo/bar");
assert_eq!(matched.remaining(), "");
let params = matched.params();
assert!(params.is_empty());
}
#[test]
fn allow_empty_match() {
let path = "";
let def = StaticSegment("");
let matched = def.test(path).expect("couldn't match route");
assert_eq!(matched.matched(), "");
assert_eq!(matched.remaining(), "");
let params = matched.params();
assert!(params.is_empty());
}
#[test]
fn tuple_static_mismatch() {
let path = "/foo/baz";
let def = (StaticSegment("foo"), StaticSegment("bar"));
assert!(def.test(path).is_none());
}
#[test]
fn tuple_static_mismatch_on_enum() {
let path = "/foo/baz";
let def = (StaticSegment(Foo), StaticSegment(Bar));
assert!(def.test(path).is_none());
}
#[test]
fn dont_match_smooshed_segments() {
let path = "/foobar";
let def = (StaticSegment(Foo), StaticSegment(Bar));
assert!(def.test(path).is_none());
}
#[test]
fn arbitrary_nesting_of_tuples_has_no_effect_on_matching() {
let path = "/foo/bar";
let def = (
(),
(StaticSegment("foo")),
(),
((), ()),
StaticSegment("bar"),
(),
);
let matched = def.test(path).expect("couldn't match route");
assert_eq!(matched.matched(), "/foo/bar");
assert_eq!(matched.remaining(), "");
let params = matched.params();
assert!(params.is_empty());
}
#[test]
fn arbitrary_nesting_of_tuples_has_no_effect_on_matching_on_enum() {
let path = "/foo/bar";
let def = (
(),
(StaticSegment(Foo)),
(),
((), ()),
StaticSegment(Bar),
(),
);
let matched = def.test(path).expect("couldn't match route");
assert_eq!(matched.matched(), "/foo/bar");
assert_eq!(matched.remaining(), "");
let params = matched.params();
assert!(params.is_empty());
}
#[test]
fn only_match_full_static_paths() {
let def = (StaticSegment("tests"), StaticSegment("abc"));
assert!(def.test("/tes/abc").is_none());
assert!(def.test("/test/abc").is_none());
assert!(def.test("/tes/abc/").is_none());
assert!(def.test("/test/abc/").is_none());
assert!(def.test("/tests/ab").is_none());
assert!(def.test("/tests/ab/").is_none());
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/router/src/matching/horizontal/param_segments.rs | router/src/matching/horizontal/param_segments.rs | use super::{PartialPathMatch, PathSegment, PossibleRouteMatch};
use core::iter;
use std::borrow::Cow;
/// A segment that captures a value from the url and maps it to a key.
///
/// # Examples
/// ```rust
/// # (|| -> Option<()> { // Option does not impl Terminate, so no main
/// use leptos::prelude::*;
/// use leptos_router::{path, ParamSegment, PossibleRouteMatch};
///
/// let path = &"/hello";
///
/// // Manual definition
/// let manual = (ParamSegment("message"),);
/// let params = manual.test(path)?.params();
/// let (key, value) = params.last()?;
///
/// assert_eq!(key, "message");
/// assert_eq!(value, "hello");
///
/// // Macro definition
/// let using_macro = path!("/:message");
/// let params = using_macro.test(path)?.params();
/// let (key, value) = params.last()?;
///
/// assert_eq!(key, "message");
/// assert_eq!(value, "hello");
///
/// # Some(())
/// # })().unwrap();
/// ```
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct ParamSegment(pub &'static str);
impl PossibleRouteMatch for ParamSegment {
fn optional(&self) -> bool {
false
}
fn test<'a>(&self, path: &'a str) -> Option<PartialPathMatch<'a>> {
let mut matched_len = 0;
let mut param_offset = 0;
let mut param_len = 0;
let mut test = path.chars();
// match an initial /
if let Some('/') = test.next() {
matched_len += 1;
param_offset = 1;
}
for char in test {
// when we get a closing /, stop matching
if char == '/' {
break;
}
// otherwise, push into the matched param
else {
matched_len += char.len_utf8();
param_len += char.len_utf8();
}
}
if matched_len == 0 || (matched_len == 1 && path.starts_with('/')) {
return None;
}
let (matched, remaining) = path.split_at(matched_len);
let param_value = vec![(
Cow::Borrowed(self.0),
path[param_offset..param_len + param_offset].to_string(),
)];
Some(PartialPathMatch::new(remaining, param_value, matched))
}
fn generate_path(&self, path: &mut Vec<PathSegment>) {
path.push(PathSegment::Param(self.0.into()));
}
}
/// A segment that captures all remaining values from the url and maps it to a key.
///
/// A [`WildcardSegment`] __must__ be the last segment of your path definition.
///
/// ```rust
/// # (|| -> Option<()> { // Option does not impl Terminate, so no main
/// use leptos::prelude::*;
/// use leptos_router::{
/// path, ParamSegment, PossibleRouteMatch, StaticSegment, WildcardSegment,
/// };
///
/// let path = &"/echo/send/sync/and/static";
///
/// // Manual definition
/// let manual = (StaticSegment("echo"), WildcardSegment("kitchen_sink"));
/// let params = manual.test(path)?.params();
/// let (key, value) = params.last()?;
///
/// assert_eq!(key, "kitchen_sink");
/// assert_eq!(value, "send/sync/and/static");
///
/// // Macro definition
/// let using_macro = path!("/echo/*else");
/// let params = using_macro.test(path)?.params();
/// let (key, value) = params.last()?;
///
/// assert_eq!(key, "else");
/// assert_eq!(value, "send/sync/and/static");
///
/// // This fails to compile because the macro will catch the bad ordering
/// // let bad = path!("/echo/*foo/bar/:baz");
///
/// // This compiles but may not work as you expect at runtime.
/// (
/// StaticSegment("echo"),
/// WildcardSegment("foo"),
/// ParamSegment("baz"),
/// );
///
/// # Some(())
/// # })().unwrap();
/// ```
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct WildcardSegment(pub &'static str);
impl PossibleRouteMatch for WildcardSegment {
fn optional(&self) -> bool {
false
}
fn test<'a>(&self, path: &'a str) -> Option<PartialPathMatch<'a>> {
let mut matched_len = 0;
let mut param_offset = 0;
let mut param_len = 0;
let mut test = path.chars();
// match an initial /
if let Some('/') = test.next() {
matched_len += 1;
param_offset += 1;
}
for char in test {
matched_len += char.len_utf8();
param_len += char.len_utf8();
}
let (matched, remaining) = path.split_at(matched_len);
let param_value = iter::once((
Cow::Borrowed(self.0),
path[param_offset..param_len + param_offset].to_string(),
));
Some(PartialPathMatch::new(
remaining,
param_value.into_iter().collect(),
matched,
))
}
fn generate_path(&self, path: &mut Vec<PathSegment>) {
path.push(PathSegment::Splat(self.0.into()));
}
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct OptionalParamSegment(pub &'static str);
impl PossibleRouteMatch for OptionalParamSegment {
fn optional(&self) -> bool {
true
}
fn test<'a>(&self, path: &'a str) -> Option<PartialPathMatch<'a>> {
let mut matched_len = 0;
let mut param_offset = 0;
let mut param_len = 0;
let mut test = path.chars();
// match an initial /
if let Some('/') = test.next() {
matched_len += 1;
param_offset = 1;
}
for char in test {
// when we get a closing /, stop matching
if char == '/' {
break;
}
// otherwise, push into the matched param
else {
matched_len += char.len_utf8();
param_len += char.len_utf8();
}
}
let matched_len = if matched_len == 1 && path.starts_with('/') {
0
} else {
matched_len
};
let (matched, remaining) = path.split_at(matched_len);
let param_value = (matched_len > 0)
.then(|| {
(
Cow::Borrowed(self.0),
path[param_offset..param_len + param_offset].to_string(),
)
})
.into_iter()
.collect();
Some(PartialPathMatch::new(remaining, param_value, matched))
}
fn generate_path(&self, path: &mut Vec<PathSegment>) {
path.push(PathSegment::OptionalParam(self.0.into()));
}
}
#[cfg(test)]
mod tests {
use super::PossibleRouteMatch;
use crate::{
OptionalParamSegment, ParamSegment, StaticSegment, WildcardSegment,
};
#[test]
fn single_param_match() {
let path = "/foo";
let def = ParamSegment("a");
let matched = def.test(path).expect("couldn't match route");
assert_eq!(matched.matched(), "/foo");
assert_eq!(matched.remaining(), "");
let params = matched.params();
assert_eq!(params[0], ("a".into(), "foo".into()));
}
#[test]
fn single_param_match_with_trailing_slash() {
let path = "/foo/";
let def = ParamSegment("a");
let matched = def.test(path).expect("couldn't match route");
assert_eq!(matched.matched(), "/foo");
assert_eq!(matched.remaining(), "/");
let params = matched.params();
assert_eq!(params[0], ("a".into(), "foo".into()));
}
#[test]
fn tuple_of_param_matches() {
let path = "/foo/bar";
let def = (ParamSegment("a"), ParamSegment("b"));
let matched = def.test(path).expect("couldn't match route");
assert_eq!(matched.matched(), "/foo/bar");
assert_eq!(matched.remaining(), "");
let params = matched.params();
assert_eq!(params[0], ("a".into(), "foo".into()));
assert_eq!(params[1], ("b".into(), "bar".into()));
}
#[test]
fn splat_should_match_all() {
let path = "/foo/bar/////";
let def = (
StaticSegment("foo"),
StaticSegment("bar"),
WildcardSegment("rest"),
);
let matched = def.test(path).expect("couldn't match route");
assert_eq!(matched.matched(), "/foo/bar/////");
assert_eq!(matched.remaining(), "");
let params = matched.params();
assert_eq!(params[0], ("rest".into(), "////".into()));
}
#[test]
fn optional_param_can_match() {
let path = "/foo";
let def = OptionalParamSegment("a");
let matched = def.test(path).expect("couldn't match route");
assert_eq!(matched.matched(), "/foo");
assert_eq!(matched.remaining(), "");
let params = matched.params();
assert_eq!(params[0], ("a".into(), "foo".into()));
}
#[test]
fn optional_param_can_not_match() {
let path = "/";
let def = OptionalParamSegment("a");
let matched = def.test(path).expect("couldn't match route");
assert_eq!(matched.matched(), "");
assert_eq!(matched.remaining(), "/");
let params = matched.params();
assert_eq!(params.first(), None);
}
#[test]
fn optional_params_match_first() {
let path = "/foo";
let def = (OptionalParamSegment("a"), OptionalParamSegment("b"));
let matched = def.test(path).expect("couldn't match route");
assert_eq!(matched.matched(), "/foo");
assert_eq!(matched.remaining(), "");
let params = matched.params();
assert_eq!(params[0], ("a".into(), "foo".into()));
}
#[test]
fn optional_params_can_match_both() {
let path = "/foo/bar";
let def = (OptionalParamSegment("a"), OptionalParamSegment("b"));
let matched = def.test(path).expect("couldn't match route");
assert_eq!(matched.matched(), "/foo/bar");
assert_eq!(matched.remaining(), "");
let params = matched.params();
assert_eq!(params[0], ("a".into(), "foo".into()));
assert_eq!(params[1], ("b".into(), "bar".into()));
}
#[test]
fn matching_after_optional_param() {
let path = "/bar";
let def = (OptionalParamSegment("a"), StaticSegment("bar"));
let matched = def.test(path).expect("couldn't match route");
assert_eq!(matched.matched(), "/bar");
assert_eq!(matched.remaining(), "");
let params = matched.params();
assert!(params.is_empty());
}
#[test]
fn static_before_param() {
let path = "/foo/bar";
let def = (StaticSegment("foo"), ParamSegment("b"));
let matched = def.test(path).expect("couldn't match route");
assert_eq!(matched.matched(), "/foo/bar");
assert_eq!(matched.remaining(), "");
let params = matched.params();
assert_eq!(params[0], ("b".into(), "bar".into()));
}
#[test]
fn static_before_optional_param() {
let path = "/foo/bar";
let def = (StaticSegment("foo"), OptionalParamSegment("b"));
let matched = def.test(path).expect("couldn't match route");
assert_eq!(matched.matched(), "/foo/bar");
assert_eq!(matched.remaining(), "");
let params = matched.params();
assert_eq!(params[0], ("b".into(), "bar".into()));
}
#[test]
fn multiple_optional_params_match_first() {
let path = "/foo/bar";
let def = (
OptionalParamSegment("a"),
OptionalParamSegment("b"),
StaticSegment("bar"),
);
let matched = def.test(path).expect("couldn't match route");
assert_eq!(matched.matched(), "/foo/bar");
assert_eq!(matched.remaining(), "");
let params = matched.params();
assert_eq!(params[0], ("a".into(), "foo".into()));
}
#[test]
fn multiple_optionals_can_match_both() {
let path = "/foo/qux/bar";
let def = (
OptionalParamSegment("a"),
OptionalParamSegment("b"),
StaticSegment("bar"),
);
let matched = def.test(path).expect("couldn't match route");
assert_eq!(matched.matched(), "/foo/qux/bar");
assert_eq!(matched.remaining(), "");
let params = matched.params();
assert_eq!(params[0], ("a".into(), "foo".into()));
assert_eq!(params[1], ("b".into(), "qux".into()));
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/router/src/matching/horizontal/mod.rs | router/src/matching/horizontal/mod.rs | use super::{PartialPathMatch, PathSegment};
use std::sync::Arc;
mod param_segments;
mod static_segment;
mod tuples;
pub use param_segments::*;
pub use static_segment::*;
/// Defines a route which may or may not be matched by any given URL,
/// or URL segment.
///
/// This is a "horizontal" matching: i.e., it treats a tuple of route segments
/// as subsequent segments of the URL and tries to match them all.
pub trait PossibleRouteMatch {
fn optional(&self) -> bool;
/// Checks if this segment matches beginning of the path
///
///
/// # Arguments
///
/// * path - unmatched reminder of the path.
///
/// # Returns
///
/// If segment doesn't match a path then returns `None`. In case of a match returns the
/// information about which part of the path was matched.
///
/// 1. Paths which are empty `""` or just `"/"` should match.
/// 2. If you match just a path `"/"`, you should preserve the starting slash
/// in the [remaining](PartialPathMatch::remaining) part, so other segments which will be
/// tested can detect wherever they are matching from the beginning of the given path segment.
fn test<'a>(&self, path: &'a str) -> Option<PartialPathMatch<'a>>;
fn generate_path(&self, path: &mut Vec<PathSegment>);
}
impl PossibleRouteMatch for Box<dyn PossibleRouteMatch + Send + Sync> {
fn optional(&self) -> bool {
(**self).optional()
}
fn test<'a>(&self, path: &'a str) -> Option<PartialPathMatch<'a>> {
(**self).test(path)
}
fn generate_path(&self, path: &mut Vec<PathSegment>) {
(**self).generate_path(path);
}
}
impl PossibleRouteMatch for Arc<dyn PossibleRouteMatch + Send + Sync> {
fn optional(&self) -> bool {
(**self).optional()
}
fn test<'a>(&self, path: &'a str) -> Option<PartialPathMatch<'a>> {
(**self).test(path)
}
fn generate_path(&self, path: &mut Vec<PathSegment>) {
(**self).generate_path(path);
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/router/src/matching/horizontal/tuples.rs | router/src/matching/horizontal/tuples.rs | use super::{PartialPathMatch, PathSegment, PossibleRouteMatch};
macro_rules! tuples {
($first:ident => $($ty:ident),*) => {
impl<$first, $($ty),*> PossibleRouteMatch for ($first, $($ty,)*)
where
$first: PossibleRouteMatch,
$($ty: PossibleRouteMatch),*,
{
fn optional(&self) -> bool {
#[allow(non_snake_case)]
let ($first, $($ty,)*) = &self;
[$first.optional(), $($ty.optional()),*].into_iter().any(|n| n)
}
fn test<'a>(&self, path: &'a str) -> Option<PartialPathMatch<'a>> {
#[allow(non_snake_case)]
let ($first, $($ty,)*) = &self;
// on the first run, include all optionals
let mut include_optionals = {
[$first.optional(), $($ty.optional()),*].into_iter().filter(|n| *n).count()
};
loop {
let mut nth_field = 0;
let mut matched_len = 0;
let mut r = path;
let mut p = Vec::new();
let mut m = String::new();
if $first.optional() {
nth_field += 1;
}
if !$first.optional() || nth_field <= include_optionals {
match $first.test(r) {
None => {
return None;
},
Some(PartialPathMatch { remaining, matched, params }) => {
p.extend(params.into_iter());
m.push_str(matched);
r = remaining;
},
}
}
matched_len += m.len();
$(
if $ty.optional() {
nth_field += 1;
}
if !$ty.optional() || nth_field <= include_optionals {
let PartialPathMatch {
remaining,
matched,
params
} = match $ty.test(r) {
None => if $ty.optional() {
return None;
} else {
if include_optionals == 0 {
return None;
}
include_optionals -= 1;
continue;
},
Some(v) => v,
};
r = remaining;
matched_len += matched.len();
p.extend(params);
}
)*
return Some(PartialPathMatch {
remaining: r,
matched: &path[0..matched_len],
params: p
});
}
}
fn generate_path(&self, path: &mut Vec<PathSegment>) {
#[allow(non_snake_case)]
let ($first, $($ty,)*) = &self;
$first.generate_path(path);
$(
$ty.generate_path(path);
)*
}
}
};
}
impl<A> PossibleRouteMatch for (A,)
where
Self: core::fmt::Debug,
A: PossibleRouteMatch,
{
fn optional(&self) -> bool {
self.0.optional()
}
fn test<'a>(&self, path: &'a str) -> Option<PartialPathMatch<'a>> {
let remaining = path;
let PartialPathMatch {
remaining,
matched,
params,
} = self.0.test(remaining)?;
Some(PartialPathMatch {
remaining,
matched: &path[0..matched.len()],
params,
})
}
fn generate_path(&self, path: &mut Vec<PathSegment>) {
self.0.generate_path(path);
}
}
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/router/src/matching/nested/any_nested_match.rs | router/src/matching/nested/any_nested_match.rs | #![allow(clippy::type_complexity)]
use crate::{
matching::any_choose_view::AnyChooseView, ChooseView, MatchInterface,
MatchParams, RouteMatchId,
};
use std::{borrow::Cow, fmt::Debug};
use tachys::erased::ErasedLocal;
/// A type-erased container for any [`MatchParams'] + [`MatchInterface`].
pub struct AnyNestedMatch {
value: ErasedLocal,
to_params: fn(&ErasedLocal) -> Vec<(Cow<'static, str>, String)>,
as_id: fn(&ErasedLocal) -> RouteMatchId,
as_matched: for<'a> fn(&'a ErasedLocal) -> &'a str,
into_view_and_child:
fn(ErasedLocal) -> (AnyChooseView, Option<AnyNestedMatch>),
}
impl Debug for AnyNestedMatch {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("AnyNestedMatch").finish_non_exhaustive()
}
}
/// Converts anything implementing [`MatchParams'] + [`MatchInterface`] into an erased type.
pub trait IntoAnyNestedMatch {
/// Wraps the nested route.
fn into_any_nested_match(self) -> AnyNestedMatch;
}
impl<T> IntoAnyNestedMatch for T
where
T: MatchParams + MatchInterface + 'static,
{
fn into_any_nested_match(self) -> AnyNestedMatch {
let value = ErasedLocal::new(self);
fn to_params<T: MatchParams + 'static>(
value: &ErasedLocal,
) -> Vec<(Cow<'static, str>, String)> {
let value = value.get_ref::<T>();
value.to_params()
}
fn as_id<T: MatchInterface + 'static>(
value: &ErasedLocal,
) -> RouteMatchId {
let value = value.get_ref::<T>();
value.as_id()
}
fn as_matched<T: MatchInterface + 'static>(
value: &ErasedLocal,
) -> &str {
let value = value.get_ref::<T>();
value.as_matched()
}
fn into_view_and_child<T: MatchInterface + 'static>(
value: ErasedLocal,
) -> (AnyChooseView, Option<AnyNestedMatch>) {
let value = value.into_inner::<T>();
let (view, child) = value.into_view_and_child();
(
AnyChooseView::new(view),
child.map(|child| child.into_any_nested_match()),
)
}
AnyNestedMatch {
value,
to_params: to_params::<T>,
as_id: as_id::<T>,
as_matched: as_matched::<T>,
into_view_and_child: into_view_and_child::<T>,
}
}
}
impl MatchParams for AnyNestedMatch {
fn to_params(&self) -> Vec<(Cow<'static, str>, String)> {
(self.to_params)(&self.value)
}
}
impl MatchInterface for AnyNestedMatch {
type Child = AnyNestedMatch;
fn as_id(&self) -> RouteMatchId {
(self.as_id)(&self.value)
}
fn as_matched(&self) -> &str {
(self.as_matched)(&self.value)
}
fn into_view_and_child(self) -> (impl ChooseView, Option<Self::Child>) {
(self.into_view_and_child)(self.value)
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/router/src/matching/nested/mod.rs | router/src/matching/nested/mod.rs | use super::{
IntoChooseViewMaybeErased, MatchInterface, MatchNestedRoutes,
PartialPathMatch, PathSegment, PossibleRouteMatch, RouteMatchId,
};
use crate::{ChooseView, GeneratedRouteData, MatchParams, Method, SsrMode};
use core::{fmt, iter};
use either_of::Either;
use std::{
borrow::Cow,
collections::HashSet,
sync::atomic::{AtomicU16, Ordering},
};
use tachys::prelude::IntoMaybeErased;
pub mod any_nested_match;
pub mod any_nested_route;
mod tuples;
pub(crate) static ROUTE_ID: AtomicU16 = AtomicU16::new(1);
#[derive(Debug, PartialEq, Eq)]
pub struct NestedRoute<Segments, Children, Data, View> {
id: u16,
segments: Segments,
children: Option<Children>,
data: Data,
view: View,
methods: HashSet<Method>,
ssr_mode: SsrMode,
}
impl<Segments, Children, Data, View> IntoMaybeErased
for NestedRoute<Segments, Children, Data, View>
where
Self: MatchNestedRoutes + Send + Clone + 'static,
{
#[cfg(erase_components)]
type Output = any_nested_route::AnyNestedRoute;
#[cfg(not(erase_components))]
type Output = Self;
fn into_maybe_erased(self) -> Self::Output {
#[cfg(erase_components)]
{
use any_nested_route::IntoAnyNestedRoute;
self.into_any_nested_route()
}
#[cfg(not(erase_components))]
{
self
}
}
}
impl<Segments, Children, Data, View> Clone
for NestedRoute<Segments, Children, Data, View>
where
Segments: Clone,
Children: Clone,
Data: Clone,
View: Clone,
{
fn clone(&self) -> Self {
Self {
id: self.id,
segments: self.segments.clone(),
children: self.children.clone(),
data: self.data.clone(),
view: self.view.clone(),
methods: self.methods.clone(),
ssr_mode: self.ssr_mode.clone(),
}
}
}
impl<Segments, View> NestedRoute<Segments, (), (), View> {
pub fn new(
path: Segments,
view: View,
) -> NestedRoute<
Segments,
(),
(),
<View as IntoChooseViewMaybeErased>::Output,
>
where
View: ChooseView,
{
NestedRoute {
id: ROUTE_ID.fetch_add(1, Ordering::Relaxed),
segments: path,
children: None,
data: (),
view: view.into_maybe_erased(),
methods: [Method::Get].into(),
ssr_mode: Default::default(),
}
}
}
impl<Segments, Data, View> NestedRoute<Segments, (), Data, View> {
pub fn child<Children>(
self,
child: Children,
) -> NestedRoute<Segments, Children, Data, View> {
let Self {
id,
segments,
data,
view,
ssr_mode,
methods,
..
} = self;
NestedRoute {
id,
segments,
children: Some(child),
data,
view,
ssr_mode,
methods,
}
}
pub fn ssr_mode(mut self, ssr_mode: SsrMode) -> Self {
self.ssr_mode = ssr_mode;
self
}
}
#[derive(PartialEq, Eq)]
pub struct NestedMatch<Child, View> {
id: RouteMatchId,
/// The portion of the full path matched only by this nested route.
matched: String,
/// The map of params matched only by this nested route.
params: Vec<(Cow<'static, str>, String)>,
/// The nested route.
child: Option<Child>,
view_fn: View,
}
impl<Child, View> fmt::Debug for NestedMatch<Child, View>
where
Child: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("NestedMatch")
.field("matched", &self.matched)
.field("params", &self.params)
.field("child", &self.child)
.finish()
}
}
impl<Child, View> MatchParams for NestedMatch<Child, View> {
#[inline(always)]
fn to_params(&self) -> Vec<(Cow<'static, str>, String)> {
self.params.clone()
}
}
impl<Child, View> MatchInterface for NestedMatch<Child, View>
where
Child: MatchInterface + MatchParams + 'static,
View: ChooseView,
{
type Child = Child;
fn as_id(&self) -> RouteMatchId {
self.id
}
fn as_matched(&self) -> &str {
&self.matched
}
fn into_view_and_child(self) -> (impl ChooseView, Option<Self::Child>) {
(self.view_fn, self.child)
}
}
impl<Segments, Children, Data, View> MatchNestedRoutes
for NestedRoute<Segments, Children, Data, View>
where
Self: 'static,
Segments: PossibleRouteMatch,
Children: MatchNestedRoutes,
Children::Match: MatchParams,
Children: 'static,
View: ChooseView + Clone,
{
type Data = Data;
type Match = NestedMatch<Children::Match, View>;
fn optional(&self) -> bool {
self.segments.optional()
&& self.children.as_ref().map(|n| n.optional()).unwrap_or(true)
}
fn match_nested<'a>(
&'a self,
path: &'a str,
) -> (Option<(RouteMatchId, Self::Match)>, &'a str) {
// if this was optional (for example, this whole nested route definition consisted of an optional param),
// then we'll need to retest the inner value against the starting path, if this one succeeds and the inner one fails
let this_was_optional = self.segments.optional();
self.segments
.test(path)
.and_then(
|PartialPathMatch {
remaining,
mut params,
matched,
}| {
let (_, inner, remaining, was_optional_fallback) =
match &self.children {
None => (None, None, remaining, false),
Some(children) => {
let (inner, remaining) =
children.match_nested(remaining);
match inner {
Some((id, inner)) => (
Some(id),
Some(inner),
remaining,
false,
),
None if this_was_optional => {
// if the parent route was optional, re-match children against full path
let (inner, remaining) =
children.match_nested(path);
let (id, inner) = inner?;
(Some(id), Some(inner), remaining, true)
}
None => {
return None;
}
}
}
};
// if this was an optional route, re-parse its params
if was_optional_fallback {
// new params are based on the path it matched (up to the point where the matched child begins)
// e.g., if we have /:foo?/bar, for /bar we should *not* have { "foo": "bar" }
// so, we re-parse based on "" to yield { "foo": "" }
let matched = inner
.as_ref()
.map(|inner| inner.as_matched())
.unwrap_or("");
let rematch = path
.trim_end_matches(&format!("{matched}{remaining}"));
let new_partial = self.segments.test(rematch).unwrap();
params = new_partial.params;
}
let inner_params = inner
.as_ref()
.map(|inner| inner.to_params())
.unwrap_or_default();
let id = RouteMatchId(self.id);
if remaining.is_empty() || remaining == "/" {
params.extend(inner_params);
Some((
Some((
id,
NestedMatch {
id,
matched: matched.to_string(),
params,
child: inner,
view_fn: self.view.clone(),
},
)),
remaining,
))
} else {
None
}
},
)
.unwrap_or((None, path))
}
fn generate_routes(
&self,
) -> impl IntoIterator<Item = GeneratedRouteData> + '_ {
let mut segment_routes = Vec::new();
self.segments.generate_path(&mut segment_routes);
let children = self.children.as_ref();
let ssr_mode = self.ssr_mode.clone();
let methods = self.methods.clone();
let regenerate = match &ssr_mode {
SsrMode::Static(data) => match data.regenerate.as_ref() {
None => vec![],
Some(regenerate) => vec![regenerate.clone()],
},
_ => vec![],
};
match children {
None => Either::Left(iter::once(GeneratedRouteData {
segments: segment_routes,
ssr_mode,
methods,
regenerate,
})),
Some(children) => {
Either::Right(children.generate_routes().into_iter().map(
move |child| {
// extend this route's segments with child segments
let segments = segment_routes
.clone()
.into_iter()
.chain(child.segments)
.collect();
let mut methods = methods.clone();
methods.extend(child.methods);
let mut regenerate = regenerate.clone();
regenerate.extend(child.regenerate);
if child.ssr_mode > ssr_mode {
GeneratedRouteData {
segments,
ssr_mode: child.ssr_mode,
methods,
regenerate,
}
} else {
GeneratedRouteData {
segments,
ssr_mode: ssr_mode.clone(),
methods,
regenerate,
}
}
},
))
}
}
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/router/src/matching/nested/tuples.rs | router/src/matching/nested/tuples.rs | use super::{MatchInterface, MatchNestedRoutes, PathSegment, RouteMatchId};
use crate::{ChooseView, GeneratedRouteData, MatchParams};
use core::iter;
use either_of::*;
use std::borrow::Cow;
use tachys::view::iterators::StaticVec;
impl MatchParams for () {
fn to_params(&self) -> Vec<(Cow<'static, str>, String)> {
Vec::new()
}
}
impl MatchInterface for () {
type Child = ();
fn as_id(&self) -> RouteMatchId {
RouteMatchId(0)
}
fn as_matched(&self) -> &str {
""
}
fn into_view_and_child(self) -> (impl ChooseView, Option<Self::Child>) {
((), None)
}
}
impl MatchNestedRoutes for () {
type Data = ();
type Match = ();
fn optional(&self) -> bool {
false
}
fn match_nested<'a>(
&self,
path: &'a str,
) -> (Option<(RouteMatchId, Self::Match)>, &'a str) {
(Some((RouteMatchId(0), ())), path)
}
fn generate_routes(
&self,
) -> impl IntoIterator<Item = GeneratedRouteData> + '_ {
iter::once(GeneratedRouteData {
segments: vec![PathSegment::Unit],
..Default::default()
})
}
}
impl<A> MatchParams for (A,)
where
A: MatchParams,
{
fn to_params(&self) -> Vec<(Cow<'static, str>, String)> {
self.0.to_params()
}
}
impl<A> MatchInterface for (A,)
where
A: MatchInterface + 'static,
{
type Child = A::Child;
fn as_id(&self) -> RouteMatchId {
self.0.as_id()
}
fn as_matched(&self) -> &str {
self.0.as_matched()
}
fn into_view_and_child(self) -> (impl ChooseView, Option<Self::Child>) {
self.0.into_view_and_child()
}
}
impl<A> MatchNestedRoutes for (A,)
where
A: MatchNestedRoutes + 'static,
{
type Data = A::Data;
type Match = A::Match;
fn match_nested<'a>(
&'a self,
path: &'a str,
) -> (Option<(RouteMatchId, Self::Match)>, &'a str) {
self.0.match_nested(path)
}
fn generate_routes(
&self,
) -> impl IntoIterator<Item = GeneratedRouteData> + '_ {
self.0.generate_routes()
}
fn optional(&self) -> bool {
self.0.optional()
}
}
impl<A, B> MatchParams for Either<A, B>
where
A: MatchParams,
B: MatchParams,
{
fn to_params(&self) -> Vec<(Cow<'static, str>, String)> {
match self {
Either::Left(i) => i.to_params(),
Either::Right(i) => i.to_params(),
}
}
}
impl<A, B> MatchInterface for Either<A, B>
where
A: MatchInterface,
B: MatchInterface,
{
type Child = Either<A::Child, B::Child>;
fn as_id(&self) -> RouteMatchId {
match self {
Either::Left(i) => i.as_id(),
Either::Right(i) => i.as_id(),
}
}
fn as_matched(&self) -> &str {
match self {
Either::Left(i) => i.as_matched(),
Either::Right(i) => i.as_matched(),
}
}
fn into_view_and_child(self) -> (impl ChooseView, Option<Self::Child>) {
match self {
Either::Left(i) => {
let (view, child) = i.into_view_and_child();
(Either::Left(view), child.map(Either::Left))
}
Either::Right(i) => {
let (view, child) = i.into_view_and_child();
(Either::Right(view), child.map(Either::Right))
}
}
}
}
impl<A, B> MatchNestedRoutes for (A, B)
where
A: MatchNestedRoutes,
B: MatchNestedRoutes,
{
type Data = (A::Data, B::Data);
type Match = Either<A::Match, B::Match>;
fn match_nested<'a>(
&'a self,
path: &'a str,
) -> (Option<(RouteMatchId, Self::Match)>, &'a str) {
#[allow(non_snake_case)]
let (A, B) = &self;
if let (Some((id, matched)), remaining) = A.match_nested(path) {
return (Some((id, Either::Left(matched))), remaining);
}
if let (Some((id, matched)), remaining) = B.match_nested(path) {
return (Some((id, Either::Right(matched))), remaining);
}
(None, path)
}
fn generate_routes(
&self,
) -> impl IntoIterator<Item = GeneratedRouteData> + '_ {
#![allow(non_snake_case)]
let (A, B) = &self;
let A = A.generate_routes().into_iter();
let B = B.generate_routes().into_iter();
A.chain(B)
}
fn optional(&self) -> bool {
self.0.optional() && self.1.optional()
}
}
impl<T> MatchNestedRoutes for StaticVec<T>
where
T: MatchNestedRoutes,
{
type Data = Vec<T::Data>;
type Match = T::Match;
fn match_nested<'a>(
&'a self,
path: &'a str,
) -> (Option<(RouteMatchId, Self::Match)>, &'a str) {
for item in self.iter() {
if let (Some((id, matched)), remaining) = item.match_nested(path) {
return (Some((id, matched)), remaining);
}
}
(None, path)
}
fn generate_routes(
&self,
) -> impl IntoIterator<Item = GeneratedRouteData> + '_ {
self.iter().flat_map(T::generate_routes)
}
fn optional(&self) -> bool {
self.iter().all(|n| n.optional())
}
}
macro_rules! chain_generated {
($first:expr, $second:expr, ) => {
$first.chain($second)
};
($first:expr, $second:ident, $($rest:ident,)+) => {
chain_generated!(
$first.chain($second),
$($rest,)+
)
}
}
macro_rules! tuples {
($either:ident => $($ty:ident = $count:expr),*) => {
impl<'a, $($ty,)*> MatchParams for $either <$($ty,)*>
where
$($ty: MatchParams),*,
{
fn to_params(&self) -> Vec<(Cow<'static, str>, String)> {
match self {
$($either::$ty(i) => i.to_params(),)*
}
}
}
impl<$($ty,)*> MatchInterface for $either <$($ty,)*>
where
$($ty: MatchInterface + 'static),*,
{
type Child = $either<$($ty::Child,)*>;
fn as_id(&self) -> RouteMatchId {
match self {
$($either::$ty(i) => i.as_id(),)*
}
}
fn as_matched(&self) -> &str {
match self {
$($either::$ty(i) => i.as_matched(),)*
}
}
fn into_view_and_child(
self,
) -> (
impl ChooseView,
Option<Self::Child>,
) {
match self {
$($either::$ty(i) => {
let (view, child) = i.into_view_and_child();
($either::$ty(view), child.map($either::$ty))
})*
}
}
}
impl<$($ty),*> MatchNestedRoutes for ($($ty,)*)
where
$($ty: MatchNestedRoutes + 'static),*,
{
type Data = ($($ty::Data,)*);
type Match = $either<$($ty::Match,)*>;
fn optional(&self) -> bool {
#[allow(non_snake_case)]
let ($($ty,)*) = &self;
$($ty.optional() &&)*
true
}
fn match_nested<'a>(&'a self, path: &'a str) -> (Option<(RouteMatchId, Self::Match)>, &'a str) {
#[allow(non_snake_case)]
let ($($ty,)*) = &self;
$(if let (Some((_, matched)), remaining) = $ty.match_nested(path) {
return (Some((RouteMatchId($count), $either::$ty(matched))), remaining);
})*
(None, path)
}
fn generate_routes(
&self,
) -> impl IntoIterator<Item = GeneratedRouteData> + '_ {
#![allow(non_snake_case)]
let ($($ty,)*) = &self;
$(let $ty = $ty.generate_routes().into_iter();)*
chain_generated!($($ty,)*)
}
}
}
}
tuples!(EitherOf3 => A = 0, B = 1, C = 2);
tuples!(EitherOf4 => A = 0, B = 1, C = 2, D = 3);
tuples!(EitherOf5 => A = 0, B = 1, C = 2, D = 3, E = 4);
tuples!(EitherOf6 => A = 0, B = 1, C = 2, D = 3, E = 4, F = 5);
tuples!(EitherOf7 => A = 0, B = 1, C = 2, D = 3, E = 4, F = 5, G = 6);
tuples!(EitherOf8 => A = 0, B = 1, C = 2, D = 3, E = 4, F = 5, G = 6, H = 7);
tuples!(EitherOf9 => A = 0, B = 1, C = 2, D = 3, E = 4, F = 5, G = 6, H = 7, I = 8);
tuples!(EitherOf10 => A = 0, B = 1, C = 2, D = 3, E = 4, F = 5, G = 6, H = 7, I = 8, J = 9);
tuples!(EitherOf11 => A = 0, B = 1, C = 2, D = 3, E = 4, F = 5, G = 6, H = 7, I = 8, J = 9, K = 10);
tuples!(EitherOf12 => A = 0, B = 1, C = 2, D = 3, E = 4, F = 5, G = 6, H = 7, I = 8, J = 9, K = 10, L = 11);
tuples!(EitherOf13 => A = 0, B = 1, C = 2, D = 3, E = 4, F = 5, G = 6, H = 7, I = 8, J = 9, K = 10, L = 11, M = 12);
tuples!(EitherOf14 => A = 0, B = 1, C = 2, D = 3, E = 4, F = 5, G = 6, H = 7, I = 8, J = 9, K = 10, L = 11, M = 12, N = 13);
tuples!(EitherOf15 => A = 0, B = 1, C = 2, D = 3, E = 4, F = 5, G = 6, H = 7, I = 8, J = 9, K = 10, L = 11, M = 12, N = 13, O = 14);
tuples!(EitherOf16 => A = 0, B = 1, C = 2, D = 3, E = 4, F = 5, G = 6, H = 7, I = 8, J = 9, K = 10, L = 11, M = 12, N = 13, O = 14, P = 15);
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/router/src/matching/nested/any_nested_route.rs | router/src/matching/nested/any_nested_route.rs | #![allow(clippy::type_complexity)]
use crate::{
matching::nested::any_nested_match::{AnyNestedMatch, IntoAnyNestedMatch},
GeneratedRouteData, MatchNestedRoutes, RouteMatchId,
};
use std::fmt::Debug;
use tachys::{erased::Erased, prelude::IntoMaybeErased};
/// A type-erased container for any [`MatchNestedRoutes`].
pub struct AnyNestedRoute {
value: Erased,
clone: fn(&Erased) -> AnyNestedRoute,
match_nested:
for<'a> fn(
&'a Erased,
&'a str,
)
-> (Option<(RouteMatchId, AnyNestedMatch)>, &'a str),
generate_routes: fn(&Erased) -> Vec<GeneratedRouteData>,
optional: fn(&Erased) -> bool,
}
impl Clone for AnyNestedRoute {
fn clone(&self) -> Self {
(self.clone)(&self.value)
}
}
impl Debug for AnyNestedRoute {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("AnyNestedRoute").finish_non_exhaustive()
}
}
impl IntoMaybeErased for AnyNestedRoute {
type Output = Self;
fn into_maybe_erased(self) -> Self::Output {
self
}
}
/// Converts anything implementing [`MatchNestedRoutes`] into [`AnyNestedRoute`].
pub trait IntoAnyNestedRoute {
/// Wraps the nested route.
fn into_any_nested_route(self) -> AnyNestedRoute;
}
impl<T> IntoAnyNestedRoute for T
where
T: MatchNestedRoutes + Send + Clone + 'static,
{
fn into_any_nested_route(self) -> AnyNestedRoute {
fn clone<T: MatchNestedRoutes + Send + Clone + 'static>(
value: &Erased,
) -> AnyNestedRoute {
value.get_ref::<T>().clone().into_any_nested_route()
}
fn match_nested<'a, T: MatchNestedRoutes + Send + Clone + 'static>(
value: &'a Erased,
path: &'a str,
) -> (Option<(RouteMatchId, AnyNestedMatch)>, &'a str) {
let (maybe_match, path) = value.get_ref::<T>().match_nested(path);
(
maybe_match
.map(|(id, matched)| (id, matched.into_any_nested_match())),
path,
)
}
fn generate_routes<T: MatchNestedRoutes + Send + Clone + 'static>(
value: &Erased,
) -> Vec<GeneratedRouteData> {
value.get_ref::<T>().generate_routes().into_iter().collect()
}
fn optional<T: MatchNestedRoutes + Send + Clone + 'static>(
value: &Erased,
) -> bool {
value.get_ref::<T>().optional()
}
AnyNestedRoute {
value: Erased::new(self),
clone: clone::<T>,
match_nested: match_nested::<T>,
generate_routes: generate_routes::<T>,
optional: optional::<T>,
}
}
}
impl MatchNestedRoutes for AnyNestedRoute {
type Data = AnyNestedMatch;
type Match = AnyNestedMatch;
fn match_nested<'a>(
&'a self,
path: &'a str,
) -> (Option<(RouteMatchId, Self::Match)>, &'a str) {
(self.match_nested)(&self.value, path)
}
fn generate_routes(&self) -> impl IntoIterator<Item = GeneratedRouteData> {
(self.generate_routes)(&self.value)
}
fn optional(&self) -> bool {
(self.optional)(&self.value)
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/router/src/matching/vertical/mod.rs | router/src/matching/vertical/mod.rs | use super::PartialPathMatch;
pub trait ChooseRoute {
fn choose_route<'a>(&self, path: &'a str) -> Option<PartialPathMatch<'a>>;
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos_server/src/once_resource.rs | leptos_server/src/once_resource.rs | use crate::{
initial_value, FromEncodedStr, IntoEncodedString,
IS_SUPPRESSING_RESOURCE_LOAD,
};
#[cfg(feature = "rkyv")]
use codee::binary::RkyvCodec;
#[cfg(feature = "serde-wasm-bindgen")]
use codee::string::JsonSerdeWasmCodec;
#[cfg(feature = "miniserde")]
use codee::string::MiniserdeCodec;
#[cfg(feature = "serde-lite")]
use codee::SerdeLite;
use codee::{
string::{FromToStringCodec, JsonSerdeCodec},
Decoder, Encoder,
};
use core::{fmt::Debug, marker::PhantomData};
use futures::{Future, FutureExt};
use or_poisoned::OrPoisoned;
use reactive_graph::{
computed::{
suspense::SuspenseContext, AsyncDerivedReadyFuture, ScopedFuture,
},
diagnostics::{SpecialNonReactiveFuture, SpecialNonReactiveZone},
graph::{AnySource, ToAnySource},
owner::{use_context, ArenaItem, Owner},
prelude::*,
signal::{
guards::{Plain, ReadGuard},
ArcTrigger,
},
unwrap_signal,
};
use std::{
future::IntoFuture,
mem,
panic::Location,
pin::Pin,
sync::{
atomic::{AtomicBool, Ordering},
Arc, RwLock,
},
task::{Context, Poll, Waker},
};
/// A reference-counted resource that only loads once.
///
/// Resources allow asynchronously loading data and serializing it from the server to the client,
/// so that it loads on the server, and is then deserialized on the client. This improves
/// performance by beginning data loading on the server when the request is made, rather than
/// beginning it on the client after WASM has been loaded.
///
/// You can access the value of the resource either synchronously using `.get()` or asynchronously
/// using `.await`.
#[derive(Debug)]
pub struct ArcOnceResource<T, Ser = JsonSerdeCodec> {
trigger: ArcTrigger,
value: Arc<RwLock<Option<T>>>,
wakers: Arc<RwLock<Vec<Waker>>>,
suspenses: Arc<RwLock<Vec<SuspenseContext>>>,
loading: Arc<AtomicBool>,
ser: PhantomData<fn() -> Ser>,
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: &'static Location<'static>,
}
impl<T, Ser> Clone for ArcOnceResource<T, Ser> {
fn clone(&self) -> Self {
Self {
trigger: self.trigger.clone(),
value: self.value.clone(),
wakers: self.wakers.clone(),
suspenses: self.suspenses.clone(),
loading: self.loading.clone(),
ser: self.ser,
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: self.defined_at,
}
}
}
impl<T, Ser> ArcOnceResource<T, Ser>
where
T: Send + Sync + 'static,
Ser: Encoder<T> + Decoder<T>,
<Ser as Encoder<T>>::Error: Debug,
<Ser as Decoder<T>>::Error: Debug,
<<Ser as Decoder<T>>::Encoded as FromEncodedStr>::DecodingError: Debug,
<Ser as Encoder<T>>::Encoded: IntoEncodedString,
<Ser as Decoder<T>>::Encoded: FromEncodedStr,
{
/// Creates a new resource with the encoding `Ser`. If `blocking` is `true`, this is a blocking
/// resource.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
#[track_caller]
pub fn new_with_options(
fut: impl Future<Output = T> + Send + 'static,
#[allow(unused)] // this is used with `feature = "ssr"`
blocking: bool,
) -> Self {
let shared_context = Owner::current_shared_context();
let id = shared_context
.as_ref()
.map(|sc| sc.next_id())
.unwrap_or_default();
let initial = initial_value::<T, Ser>(&id, shared_context.as_ref());
let is_ready = initial.is_some();
let value = Arc::new(RwLock::new(initial));
let wakers = Arc::new(RwLock::new(Vec::<Waker>::new()));
let suspenses = Arc::new(RwLock::new(Vec::<SuspenseContext>::new()));
let loading = Arc::new(AtomicBool::new(!is_ready));
let trigger = ArcTrigger::new();
let fut = ScopedFuture::new(fut);
if !is_ready && !IS_SUPPRESSING_RESOURCE_LOAD.load(Ordering::Relaxed) {
let value = Arc::clone(&value);
let wakers = Arc::clone(&wakers);
let loading = Arc::clone(&loading);
let trigger = trigger.clone();
reactive_graph::spawn(async move {
let loaded = fut.await;
*value.write().or_poisoned() = Some(loaded);
loading.store(false, Ordering::Relaxed);
for waker in mem::take(&mut *wakers.write().or_poisoned()) {
waker.wake();
}
trigger.notify();
});
}
let data = Self {
trigger,
value: value.clone(),
loading,
wakers,
suspenses,
ser: PhantomData,
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
};
#[cfg(feature = "ssr")]
if let Some(shared_context) = shared_context {
let value = Arc::clone(&value);
let ready_fut = data.ready();
if blocking {
shared_context.defer_stream(Box::pin(data.ready()));
}
if shared_context.get_is_hydrating() {
shared_context.write_async(
id,
Box::pin(async move {
ready_fut.await;
let value = value.read().or_poisoned();
let value = value.as_ref().unwrap();
Ser::encode(value).unwrap().into_encoded_string()
}),
);
}
}
data
}
/// Synchronously, reactively reads the current value of the resource and applies the function
/// `f` to its value if it is `Some(_)`.
#[track_caller]
pub fn map<U>(&self, f: impl FnOnce(&T) -> U) -> Option<U>
where
T: Send + Sync + 'static,
{
self.try_with(|n| n.as_ref().map(f))?
}
}
impl<T, E, Ser> ArcOnceResource<Result<T, E>, Ser>
where
Ser: Encoder<Result<T, E>> + Decoder<Result<T, E>>,
<Ser as Encoder<Result<T, E>>>::Error: Debug,
<Ser as Decoder<Result<T, E>>>::Error: Debug,
<<Ser as Decoder<Result<T, E>>>::Encoded as FromEncodedStr>::DecodingError:
Debug,
<Ser as Encoder<Result<T, E>>>::Encoded: IntoEncodedString,
<Ser as Decoder<Result<T, E>>>::Encoded: FromEncodedStr,
T: Send + Sync + 'static,
E: Send + Sync + Clone + 'static,
{
/// Applies the given function when a resource that returns `Result<T, E>`
/// has resolved and loaded an `Ok(_)`, rather than requiring nested `.map()`
/// calls over the `Option<Result<_, _>>` returned by the resource.
///
/// This is useful when used with features like server functions, in conjunction
/// with `<ErrorBoundary/>` and `<Suspense/>`, when these other components are
/// left to handle the `None` and `Err(_)` states.
#[track_caller]
pub fn and_then<U>(&self, f: impl FnOnce(&T) -> U) -> Option<Result<U, E>> {
self.map(|data| data.as_ref().map(f).map_err(|e| e.clone()))
}
}
impl<T, Ser> ArcOnceResource<T, Ser> {
/// Returns a `Future` that is ready when this resource has next finished loading.
pub fn ready(&self) -> AsyncDerivedReadyFuture {
AsyncDerivedReadyFuture::new(
self.to_any_source(),
&self.loading,
&self.wakers,
)
}
}
impl<T, Ser> DefinedAt for ArcOnceResource<T, Ser> {
fn defined_at(&self) -> Option<&'static Location<'static>> {
#[cfg(not(any(debug_assertions, leptos_debuginfo)))]
{
None
}
#[cfg(any(debug_assertions, leptos_debuginfo))]
{
Some(self.defined_at)
}
}
}
impl<T, Ser> IsDisposed for ArcOnceResource<T, Ser> {
#[inline(always)]
fn is_disposed(&self) -> bool {
false
}
}
impl<T, Ser> ToAnySource for ArcOnceResource<T, Ser> {
fn to_any_source(&self) -> AnySource {
self.trigger.to_any_source()
}
}
impl<T, Ser> Track for ArcOnceResource<T, Ser> {
fn track(&self) {
self.trigger.track();
}
}
impl<T, Ser> ReadUntracked for ArcOnceResource<T, Ser>
where
T: 'static,
{
type Value = ReadGuard<Option<T>, Plain<Option<T>>>;
fn try_read_untracked(&self) -> Option<Self::Value> {
if let Some(suspense_context) = use_context::<SuspenseContext>() {
if self.value.read().or_poisoned().is_none() {
let handle = suspense_context.task_id();
let mut ready =
Box::pin(SpecialNonReactiveFuture::new(self.ready()));
match ready.as_mut().now_or_never() {
Some(_) => drop(handle),
None => {
reactive_graph::spawn(async move {
ready.await;
drop(handle);
});
}
}
self.suspenses.write().or_poisoned().push(suspense_context);
}
}
Plain::try_new(Arc::clone(&self.value)).map(ReadGuard::new)
}
}
impl<T, Ser> IntoFuture for ArcOnceResource<T, Ser>
where
T: Clone + 'static,
{
type Output = T;
type IntoFuture = OnceResourceFuture<T>;
fn into_future(self) -> Self::IntoFuture {
OnceResourceFuture {
source: self.to_any_source(),
value: Arc::clone(&self.value),
loading: Arc::clone(&self.loading),
wakers: Arc::clone(&self.wakers),
suspenses: Arc::clone(&self.suspenses),
}
}
}
/// A [`Future`] that is ready when an
/// [`ArcAsyncDerived`](reactive_graph::computed::ArcAsyncDerived) is finished loading or reloading,
/// and contains its value. `.await`ing this clones the value `T`.
pub struct OnceResourceFuture<T> {
source: AnySource,
value: Arc<RwLock<Option<T>>>,
loading: Arc<AtomicBool>,
wakers: Arc<RwLock<Vec<Waker>>>,
suspenses: Arc<RwLock<Vec<SuspenseContext>>>,
}
impl<T> Future for OnceResourceFuture<T>
where
T: Clone + 'static,
{
type Output = T;
#[track_caller]
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
#[cfg(any(debug_assertions, leptos_debuginfo))]
let _guard = SpecialNonReactiveZone::enter();
let waker = cx.waker();
self.source.track();
if let Some(suspense_context) = use_context::<SuspenseContext>() {
self.suspenses.write().or_poisoned().push(suspense_context);
}
if self.loading.load(Ordering::Relaxed) {
self.wakers.write().or_poisoned().push(waker.clone());
Poll::Pending
} else {
Poll::Ready(
self.value.read().or_poisoned().as_ref().unwrap().clone(),
)
}
}
}
impl<T> ArcOnceResource<T, JsonSerdeCodec>
where
T: Send + Sync + 'static,
JsonSerdeCodec: Encoder<T> + Decoder<T>,
<JsonSerdeCodec as Encoder<T>>::Error: Debug,
<JsonSerdeCodec as Decoder<T>>::Error: Debug,
<<JsonSerdeCodec as Decoder<T>>::Encoded as FromEncodedStr>::DecodingError:
Debug,
<JsonSerdeCodec as Encoder<T>>::Encoded: IntoEncodedString,
<JsonSerdeCodec as Decoder<T>>::Encoded: FromEncodedStr,
{
/// Creates a resource using [`JsonSerdeCodec`] for encoding/decoding the value.
#[track_caller]
pub fn new(fut: impl Future<Output = T> + Send + 'static) -> Self {
ArcOnceResource::new_with_options(fut, false)
}
/// Creates a blocking resource using [`JsonSerdeCodec`] for encoding/decoding the value.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
#[track_caller]
pub fn new_blocking(fut: impl Future<Output = T> + Send + 'static) -> Self {
ArcOnceResource::new_with_options(fut, true)
}
}
impl<T> ArcOnceResource<T, FromToStringCodec>
where
T: Send + Sync + 'static,
FromToStringCodec: Encoder<T> + Decoder<T>,
<FromToStringCodec as Encoder<T>>::Error: Debug, <FromToStringCodec as Decoder<T>>::Error: Debug,
<<FromToStringCodec as Decoder<T>>::Encoded as FromEncodedStr>::DecodingError: Debug,
<FromToStringCodec as Encoder<T>>::Encoded: IntoEncodedString,
<FromToStringCodec as Decoder<T>>::Encoded: FromEncodedStr,
{
/// Creates a resource using [`FromToStringCodec`] for encoding/decoding the value.
pub fn new_str(
fut: impl Future<Output = T> + Send + 'static
) -> Self
{
ArcOnceResource::new_with_options(fut, false)
}
/// Creates a blocking resource using [`FromToStringCodec`] for encoding/decoding the value.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
pub fn new_str_blocking(
fut: impl Future<Output = T> + Send + 'static
) -> Self
{
ArcOnceResource::new_with_options(fut, true)
}
}
#[cfg(feature = "serde-wasm-bindgen")]
#[cfg_attr(docsrs, doc(cfg(feature = "serde-wasm-bindgen")))]
impl<T> ArcOnceResource<T, JsonSerdeWasmCodec>
where
T: Send + Sync + 'static,
JsonSerdeWasmCodec: Encoder<T> + Decoder<T>,
<JsonSerdeWasmCodec as Encoder<T>>::Error: Debug, <JsonSerdeWasmCodec as Decoder<T>>::Error: Debug,
<<JsonSerdeWasmCodec as Decoder<T>>::Encoded as FromEncodedStr>::DecodingError: Debug,
<JsonSerdeWasmCodec as Encoder<T>>::Encoded: IntoEncodedString,
<JsonSerdeWasmCodec as Decoder<T>>::Encoded: FromEncodedStr,
{
/// Creates a resource using [`JsonSerdeWasmCodec`] for encoding/decoding the value.
#[track_caller]
pub fn new_serde_wb(
fut: impl Future<Output = T> + Send + 'static
) -> Self
{
ArcOnceResource::new_with_options(fut, false)
}
/// Creates a blocking resource using [`JsonSerdeWasmCodec`] for encoding/decoding the value.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
#[track_caller]
pub fn new_serde_wb_blocking(
fut: impl Future<Output = T> + Send + 'static
) -> Self
{
ArcOnceResource::new_with_options(fut, true)
}
}
#[cfg(feature = "miniserde")]
#[cfg_attr(docsrs, doc(cfg(feature = "miniserde")))]
impl<T> ArcOnceResource<T, MiniserdeCodec>
where
T: Send + Sync + 'static,
MiniserdeCodec: Encoder<T> + Decoder<T>,
<MiniserdeCodec as Encoder<T>>::Error: Debug,
<MiniserdeCodec as Decoder<T>>::Error: Debug,
<<MiniserdeCodec as Decoder<T>>::Encoded as FromEncodedStr>::DecodingError:
Debug,
<MiniserdeCodec as Encoder<T>>::Encoded: IntoEncodedString,
<MiniserdeCodec as Decoder<T>>::Encoded: FromEncodedStr,
{
/// Creates a resource using [`MiniserdeCodec`] for encoding/decoding the value.
#[track_caller]
pub fn new_miniserde(
fut: impl Future<Output = T> + Send + 'static,
) -> Self {
ArcOnceResource::new_with_options(fut, false)
}
/// Creates a blocking resource using [`MiniserdeCodec`] for encoding/decoding the value.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
#[track_caller]
pub fn new_miniserde_blocking(
fut: impl Future<Output = T> + Send + 'static,
) -> Self {
ArcOnceResource::new_with_options(fut, true)
}
}
#[cfg(feature = "serde-lite")]
#[cfg_attr(docsrs, doc(cfg(feature = "serde-lite")))]
impl<T> ArcOnceResource<T, SerdeLite<JsonSerdeCodec>>
where
T: Send + Sync + 'static,
SerdeLite<JsonSerdeCodec>: Encoder<T> + Decoder<T>,
<SerdeLite<JsonSerdeCodec> as Encoder<T>>::Error: Debug, <SerdeLite<JsonSerdeCodec> as Decoder<T>>::Error: Debug,
<<SerdeLite<JsonSerdeCodec> as Decoder<T>>::Encoded as FromEncodedStr>::DecodingError: Debug,
<SerdeLite<JsonSerdeCodec> as Encoder<T>>::Encoded: IntoEncodedString,
<SerdeLite<JsonSerdeCodec> as Decoder<T>>::Encoded: FromEncodedStr,
{
/// Creates a resource using [`SerdeLite`] for encoding/decoding the value.
#[track_caller]
pub fn new_serde_lite(
fut: impl Future<Output = T> + Send + 'static
) -> Self
{
ArcOnceResource::new_with_options(fut, false)
}
/// Creates a blocking resource using [`SerdeLite`] for encoding/decoding the value.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
#[track_caller]
pub fn new_serde_lite_blocking(
fut: impl Future<Output = T> + Send + 'static
) -> Self
{
ArcOnceResource::new_with_options(fut, true)
}
}
#[cfg(feature = "rkyv")]
#[cfg_attr(docsrs, doc(cfg(feature = "rkyv")))]
impl<T> ArcOnceResource<T, RkyvCodec>
where
T: Send + Sync + 'static,
RkyvCodec: Encoder<T> + Decoder<T>,
<RkyvCodec as Encoder<T>>::Error: Debug,
<RkyvCodec as Decoder<T>>::Error: Debug,
<<RkyvCodec as Decoder<T>>::Encoded as FromEncodedStr>::DecodingError:
Debug,
<RkyvCodec as Encoder<T>>::Encoded: IntoEncodedString,
<RkyvCodec as Decoder<T>>::Encoded: FromEncodedStr,
{
/// Creates a resource using [`RkyvCodec`] for encoding/decoding the value.
#[track_caller]
pub fn new_rkyv(fut: impl Future<Output = T> + Send + 'static) -> Self {
ArcOnceResource::new_with_options(fut, false)
}
/// Creates a blocking resource using [`RkyvCodec`] for encoding/decoding the value.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
#[track_caller]
pub fn new_rkyv_blocking(
fut: impl Future<Output = T> + Send + 'static,
) -> Self {
ArcOnceResource::new_with_options(fut, true)
}
}
/// A resource that only loads once.
///
/// Resources allow asynchronously loading data and serializing it from the server to the client,
/// so that it loads on the server, and is then deserialized on the client. This improves
/// performance by beginning data loading on the server when the request is made, rather than
/// beginning it on the client after WASM has been loaded.
///
/// You can access the value of the resource either synchronously using `.get()` or asynchronously
/// using `.await`.
#[derive(Debug)]
pub struct OnceResource<T, Ser = JsonSerdeCodec> {
inner: ArenaItem<ArcOnceResource<T, Ser>>,
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: &'static Location<'static>,
}
impl<T, Ser> Clone for OnceResource<T, Ser> {
fn clone(&self) -> Self {
*self
}
}
impl<T, Ser> Copy for OnceResource<T, Ser> {}
impl<T, Ser> OnceResource<T, Ser>
where
T: Send + Sync + 'static,
Ser: Encoder<T> + Decoder<T>,
<Ser as Encoder<T>>::Error: Debug,
<Ser as Decoder<T>>::Error: Debug,
<<Ser as Decoder<T>>::Encoded as FromEncodedStr>::DecodingError: Debug,
<Ser as Encoder<T>>::Encoded: IntoEncodedString,
<Ser as Decoder<T>>::Encoded: FromEncodedStr,
{
/// Creates a new resource with the encoding `Ser`. If `blocking` is `true`, this is a blocking
/// resource.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
#[track_caller]
pub fn new_with_options(
fut: impl Future<Output = T> + Send + 'static,
blocking: bool,
) -> Self {
#[cfg(any(debug_assertions, leptos_debuginfo))]
let defined_at = Location::caller();
Self {
inner: ArenaItem::new(ArcOnceResource::new_with_options(
fut, blocking,
)),
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at,
}
}
/// Synchronously, reactively reads the current value of the resource and applies the function
/// `f` to its value if it is `Some(_)`.
pub fn map<U>(&self, f: impl FnOnce(&T) -> U) -> Option<U> {
self.try_with(|n| n.as_ref().map(|n| Some(f(n))))?.flatten()
}
}
impl<T, E, Ser> OnceResource<Result<T, E>, Ser>
where
Ser: Encoder<Result<T, E>> + Decoder<Result<T, E>>,
<Ser as Encoder<Result<T, E>>>::Error: Debug,
<Ser as Decoder<Result<T, E>>>::Error: Debug,
<<Ser as Decoder<Result<T, E>>>::Encoded as FromEncodedStr>::DecodingError:
Debug,
<Ser as Encoder<Result<T, E>>>::Encoded: IntoEncodedString,
<Ser as Decoder<Result<T, E>>>::Encoded: FromEncodedStr,
T: Send + Sync + 'static,
E: Send + Sync + Clone + 'static,
{
/// Applies the given function when a resource that returns `Result<T, E>`
/// has resolved and loaded an `Ok(_)`, rather than requiring nested `.map()`
/// calls over the `Option<Result<_, _>>` returned by the resource.
///
/// This is useful when used with features like server functions, in conjunction
/// with `<ErrorBoundary/>` and `<Suspense/>`, when these other components are
/// left to handle the `None` and `Err(_)` states.
#[track_caller]
pub fn and_then<U>(&self, f: impl FnOnce(&T) -> U) -> Option<Result<U, E>> {
self.map(|data| data.as_ref().map(f).map_err(|e| e.clone()))
}
}
impl<T, Ser> OnceResource<T, Ser>
where
T: Send + Sync + 'static,
Ser: 'static,
{
/// Returns a `Future` that is ready when this resource has next finished loading.
pub fn ready(&self) -> AsyncDerivedReadyFuture {
self.inner
.try_with_value(|inner| inner.ready())
.unwrap_or_else(unwrap_signal!(self))
}
}
impl<T, Ser> DefinedAt for OnceResource<T, Ser> {
fn defined_at(&self) -> Option<&'static Location<'static>> {
#[cfg(not(any(debug_assertions, leptos_debuginfo)))]
{
None
}
#[cfg(any(debug_assertions, leptos_debuginfo))]
{
Some(self.defined_at)
}
}
}
impl<T, Ser> IsDisposed for OnceResource<T, Ser> {
#[inline(always)]
fn is_disposed(&self) -> bool {
false
}
}
impl<T, Ser> ToAnySource for OnceResource<T, Ser>
where
T: Send + Sync + 'static,
Ser: 'static,
{
fn to_any_source(&self) -> AnySource {
self.inner
.try_with_value(|inner| inner.to_any_source())
.unwrap_or_else(unwrap_signal!(self))
}
}
impl<T, Ser> Track for OnceResource<T, Ser>
where
T: Send + Sync + 'static,
Ser: 'static,
{
fn track(&self) {
if let Some(inner) = self.inner.try_get_value() {
inner.track();
}
}
}
impl<T, Ser> ReadUntracked for OnceResource<T, Ser>
where
T: Send + Sync + 'static,
Ser: 'static,
{
type Value = ReadGuard<Option<T>, Plain<Option<T>>>;
fn try_read_untracked(&self) -> Option<Self::Value> {
self.inner
.try_with_value(|inner| inner.try_read_untracked())
.flatten()
}
}
impl<T, Ser> IntoFuture for OnceResource<T, Ser>
where
T: Clone + Send + Sync + 'static,
Ser: 'static,
{
type Output = T;
type IntoFuture = OnceResourceFuture<T>;
fn into_future(self) -> Self::IntoFuture {
self.inner
.try_get_value()
.unwrap_or_else(unwrap_signal!(self))
.into_future()
}
}
impl<T> OnceResource<T, JsonSerdeCodec>
where
T: Send + Sync + 'static,
JsonSerdeCodec: Encoder<T> + Decoder<T>,
<JsonSerdeCodec as Encoder<T>>::Error: Debug,
<JsonSerdeCodec as Decoder<T>>::Error: Debug,
<<JsonSerdeCodec as Decoder<T>>::Encoded as FromEncodedStr>::DecodingError:
Debug,
<JsonSerdeCodec as Encoder<T>>::Encoded: IntoEncodedString,
<JsonSerdeCodec as Decoder<T>>::Encoded: FromEncodedStr,
{
/// Creates a resource using [`JsonSerdeCodec`] for encoding/decoding the value.
#[track_caller]
pub fn new(fut: impl Future<Output = T> + Send + 'static) -> Self {
OnceResource::new_with_options(fut, false)
}
/// Creates a blocking resource using [`JsonSerdeCodec`] for encoding/decoding the value.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
#[track_caller]
pub fn new_blocking(fut: impl Future<Output = T> + Send + 'static) -> Self {
OnceResource::new_with_options(fut, true)
}
}
impl<T> OnceResource<T, FromToStringCodec>
where
T: Send + Sync + 'static,
FromToStringCodec: Encoder<T> + Decoder<T>,
<FromToStringCodec as Encoder<T>>::Error: Debug, <FromToStringCodec as Decoder<T>>::Error: Debug,
<<FromToStringCodec as Decoder<T>>::Encoded as FromEncodedStr>::DecodingError: Debug,
<FromToStringCodec as Encoder<T>>::Encoded: IntoEncodedString,
<FromToStringCodec as Decoder<T>>::Encoded: FromEncodedStr,
{
/// Creates a resource using [`FromToStringCodec`] for encoding/decoding the value.
pub fn new_str(
fut: impl Future<Output = T> + Send + 'static
) -> Self
{
OnceResource::new_with_options(fut, false)
}
/// Creates a blocking resource using [`FromToStringCodec`] for encoding/decoding the value.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
pub fn new_str_blocking(
fut: impl Future<Output = T> + Send + 'static
) -> Self
{
OnceResource::new_with_options(fut, true)
}
}
#[cfg(feature = "serde-wasm-bindgen")]
#[cfg_attr(docsrs, doc(cfg(feature = "serde-wasm-bindgen")))]
impl<T> OnceResource<T, JsonSerdeWasmCodec>
where
T: Send + Sync + 'static,
JsonSerdeWasmCodec: Encoder<T> + Decoder<T>,
<JsonSerdeWasmCodec as Encoder<T>>::Error: Debug, <JsonSerdeWasmCodec as Decoder<T>>::Error: Debug,
<<JsonSerdeWasmCodec as Decoder<T>>::Encoded as FromEncodedStr>::DecodingError: Debug,
<JsonSerdeWasmCodec as Encoder<T>>::Encoded: IntoEncodedString,
<JsonSerdeWasmCodec as Decoder<T>>::Encoded: FromEncodedStr,
{
/// Creates a resource using [`JsonSerdeWasmCodec`] for encoding/decoding the value.
#[track_caller]
pub fn new_serde_wb(
fut: impl Future<Output = T> + Send + 'static
) -> Self
{
OnceResource::new_with_options(fut, false)
}
/// Creates a blocking resource using [`JsonSerdeWasmCodec`] for encoding/decoding the value.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
#[track_caller]
pub fn new_serde_wb_blocking(
fut: impl Future<Output = T> + Send + 'static
) -> Self
{
OnceResource::new_with_options(fut, true)
}
}
#[cfg(feature = "miniserde")]
#[cfg_attr(docsrs, doc(cfg(feature = "miniserde")))]
impl<T> OnceResource<T, MiniserdeCodec>
where
T: Send + Sync + 'static,
MiniserdeCodec: Encoder<T> + Decoder<T>,
<MiniserdeCodec as Encoder<T>>::Error: Debug,
<MiniserdeCodec as Decoder<T>>::Error: Debug,
<<MiniserdeCodec as Decoder<T>>::Encoded as FromEncodedStr>::DecodingError:
Debug,
<MiniserdeCodec as Encoder<T>>::Encoded: IntoEncodedString,
<MiniserdeCodec as Decoder<T>>::Encoded: FromEncodedStr,
{
/// Creates a resource using [`MiniserdeCodec`] for encoding/decoding the value.
#[track_caller]
pub fn new_miniserde(
fut: impl Future<Output = T> + Send + 'static,
) -> Self {
OnceResource::new_with_options(fut, false)
}
/// Creates a blocking resource using [`MiniserdeCodec`] for encoding/decoding the value.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
#[track_caller]
pub fn new_miniserde_blocking(
fut: impl Future<Output = T> + Send + 'static,
) -> Self {
OnceResource::new_with_options(fut, true)
}
}
#[cfg(feature = "serde-lite")]
#[cfg_attr(docsrs, doc(cfg(feature = "serde-lite")))]
impl<T> OnceResource<T, SerdeLite<JsonSerdeCodec>>
where
T: Send + Sync + 'static,
SerdeLite<JsonSerdeCodec>: Encoder<T> + Decoder<T>,
<SerdeLite<JsonSerdeCodec> as Encoder<T>>::Error: Debug, <SerdeLite<JsonSerdeCodec> as Decoder<T>>::Error: Debug,
<<SerdeLite<JsonSerdeCodec> as Decoder<T>>::Encoded as FromEncodedStr>::DecodingError: Debug,
<SerdeLite<JsonSerdeCodec> as Encoder<T>>::Encoded: IntoEncodedString,
<SerdeLite<JsonSerdeCodec> as Decoder<T>>::Encoded: FromEncodedStr,
{
/// Creates a resource using [`SerdeLite`] for encoding/decoding the value.
#[track_caller]
pub fn new_serde_lite(
fut: impl Future<Output = T> + Send + 'static
) -> Self
{
OnceResource::new_with_options(fut, false)
}
/// Creates a blocking resource using [`SerdeLite`] for encoding/decoding the value.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
#[track_caller]
pub fn new_serde_lite_blocking(
fut: impl Future<Output = T> + Send + 'static
) -> Self
{
OnceResource::new_with_options(fut, true)
}
}
#[cfg(feature = "rkyv")]
#[cfg_attr(docsrs, doc(cfg(feature = "rkyv")))]
impl<T> OnceResource<T, RkyvCodec>
where
T: Send + Sync + 'static,
RkyvCodec: Encoder<T> + Decoder<T>,
<RkyvCodec as Encoder<T>>::Error: Debug,
<RkyvCodec as Decoder<T>>::Error: Debug,
<<RkyvCodec as Decoder<T>>::Encoded as FromEncodedStr>::DecodingError:
Debug,
<RkyvCodec as Encoder<T>>::Encoded: IntoEncodedString,
<RkyvCodec as Decoder<T>>::Encoded: FromEncodedStr,
{
/// Creates a resource using [`RkyvCodec`] for encoding/decoding the value.
#[track_caller]
pub fn new_rkyv(fut: impl Future<Output = T> + Send + 'static) -> Self {
OnceResource::new_with_options(fut, false)
}
/// Creates a blocking resource using [`RkyvCodec`] for encoding/decoding the value.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
#[track_caller]
pub fn new_rkyv_blocking(
fut: impl Future<Output = T> + Send + 'static,
) -> Self {
OnceResource::new_with_options(fut, true)
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos_server/src/resource.rs | leptos_server/src/resource.rs | use crate::{FromEncodedStr, IntoEncodedString};
#[cfg(feature = "rkyv")]
use codee::binary::RkyvCodec;
#[cfg(feature = "serde-wasm-bindgen")]
use codee::string::JsonSerdeWasmCodec;
#[cfg(feature = "miniserde")]
use codee::string::MiniserdeCodec;
#[cfg(feature = "serde-lite")]
use codee::SerdeLite;
use codee::{
string::{FromToStringCodec, JsonSerdeCodec},
Decoder, Encoder,
};
use core::{fmt::Debug, marker::PhantomData};
use futures::Future;
use hydration_context::{SerializedDataId, SharedContext};
use reactive_graph::{
computed::{
ArcAsyncDerived, ArcMemo, AsyncDerived, AsyncDerivedFuture,
AsyncDerivedRefFuture,
},
graph::{Source, ToAnySubscriber},
owner::Owner,
prelude::*,
signal::{ArcRwSignal, RwSignal},
};
use std::{
future::{pending, IntoFuture},
ops::{Deref, DerefMut},
panic::Location,
sync::{
atomic::{AtomicBool, Ordering},
Arc,
},
};
pub(crate) static IS_SUPPRESSING_RESOURCE_LOAD: AtomicBool =
AtomicBool::new(false);
/// Used to prevent resources from actually loading, in environments (like server route generation)
/// where they are not needed.
pub struct SuppressResourceLoad;
impl SuppressResourceLoad {
/// Prevents resources from loading until this is dropped.
pub fn new() -> Self {
IS_SUPPRESSING_RESOURCE_LOAD.store(true, Ordering::Relaxed);
Self
}
}
impl Default for SuppressResourceLoad {
fn default() -> Self {
Self::new()
}
}
impl Drop for SuppressResourceLoad {
fn drop(&mut self) {
IS_SUPPRESSING_RESOURCE_LOAD.store(false, Ordering::Relaxed);
}
}
/// A reference-counted asynchronous resource.
///
/// Resources allow asynchronously loading data and serializing it from the server to the client,
/// so that it loads on the server, and is then deserialized on the client. This improves
/// performance by beginning data loading on the server when the request is made, rather than
/// beginning it on the client after WASM has been loaded.
///
/// You can access the value of the resource either synchronously using `.get()` or asynchronously
/// using `.await`.
pub struct ArcResource<T, Ser = JsonSerdeCodec> {
ser: PhantomData<Ser>,
refetch: ArcRwSignal<usize>,
data: ArcAsyncDerived<T>,
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: &'static Location<'static>,
}
impl<T, Ser> Debug for ArcResource<T, Ser> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut d = f.debug_struct("ArcResource");
d.field("ser", &self.ser).field("data", &self.data);
#[cfg(any(debug_assertions, leptos_debuginfo))]
d.field("defined_at", self.defined_at);
d.finish_non_exhaustive()
}
}
impl<T, Ser> From<ArcResource<T, Ser>> for Resource<T, Ser>
where
T: Send + Sync,
{
#[track_caller]
fn from(arc_resource: ArcResource<T, Ser>) -> Self {
Resource {
ser: PhantomData,
data: arc_resource.data.into(),
refetch: arc_resource.refetch.into(),
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
}
}
}
impl<T, Ser> From<Resource<T, Ser>> for ArcResource<T, Ser>
where
T: Send + Sync,
{
#[track_caller]
fn from(resource: Resource<T, Ser>) -> Self {
ArcResource {
ser: PhantomData,
data: resource.data.into(),
refetch: resource.refetch.into(),
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
}
}
}
impl<T, Ser> DefinedAt for ArcResource<T, Ser> {
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, Ser> Clone for ArcResource<T, Ser> {
fn clone(&self) -> Self {
Self {
ser: self.ser,
refetch: self.refetch.clone(),
data: self.data.clone(),
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: self.defined_at,
}
}
}
impl<T, Ser> Deref for ArcResource<T, Ser> {
type Target = ArcAsyncDerived<T>;
fn deref(&self) -> &Self::Target {
&self.data
}
}
impl<T, Ser> Track for ArcResource<T, Ser>
where
T: 'static,
{
fn track(&self) {
self.data.track();
}
}
impl<T, Ser> Notify for ArcResource<T, Ser>
where
T: 'static,
{
fn notify(&self) {
self.data.notify()
}
}
impl<T, Ser> Write for ArcResource<T, Ser>
where
T: 'static,
{
type Value = Option<T>;
fn try_write(&self) -> Option<impl UntrackableGuard<Target = Self::Value>> {
self.data.try_write()
}
fn try_write_untracked(
&self,
) -> Option<impl DerefMut<Target = Self::Value>> {
self.data.try_write_untracked()
}
}
#[cfg(debug_assertions)]
thread_local! {
static RESOURCE_SOURCE_SIGNAL_ACTIVE: AtomicBool = const { AtomicBool::new(false) };
}
#[cfg(debug_assertions)]
/// Returns whether the current thread is currently running a resource source signal.
pub fn in_resource_source_signal() -> bool {
RESOURCE_SOURCE_SIGNAL_ACTIVE
.with(|scope| scope.load(std::sync::atomic::Ordering::Relaxed))
}
/// Set a static to true whilst running the given function.
/// [`is_in_effect_scope`] will return true whilst the function is running.
fn run_in_resource_source_signal<T>(fun: impl FnOnce() -> T) -> T {
#[cfg(debug_assertions)]
{
// For the theoretical nested case, set back to initial value rather than false:
let initial = RESOURCE_SOURCE_SIGNAL_ACTIVE.with(|scope| {
scope.swap(true, std::sync::atomic::Ordering::Relaxed)
});
let result = fun();
RESOURCE_SOURCE_SIGNAL_ACTIVE.with(|scope| {
scope.store(initial, std::sync::atomic::Ordering::Relaxed)
});
result
}
#[cfg(not(debug_assertions))]
{
fun()
}
}
impl<T, Ser> ReadUntracked for ArcResource<T, Ser>
where
T: 'static,
{
type Value = <ArcAsyncDerived<T> as ReadUntracked>::Value;
#[track_caller]
fn try_read_untracked(&self) -> Option<Self::Value> {
#[cfg(all(feature = "hydration", debug_assertions))]
{
use reactive_graph::{
computed::suspense::SuspenseContext, effect::in_effect_scope,
owner::use_context,
};
if !in_effect_scope()
&& !in_resource_source_signal()
&& use_context::<SuspenseContext>().is_none()
{
let location = std::panic::Location::caller();
reactive_graph::log_warning(format_args!(
"At {location}, you are reading a resource in `hydrate` \
mode outside a <Suspense/> or <Transition/> or effect. \
This can cause hydration mismatch errors and loses out \
on a significant performance optimization. To fix this \
issue, you can either: \n1. Wrap the place where you \
read the resource in a <Suspense/> or <Transition/> \
component, or \n2. Switch to using \
ArcLocalResource::new(), which will wait to load the \
resource until the app is hydrated on the client side. \
(This will have worse performance in most cases.)",
));
}
}
self.data.try_read_untracked()
}
}
impl<T, Ser> ArcResource<T, Ser>
where
Ser: Encoder<T> + Decoder<T>,
<Ser as Encoder<T>>::Error: Debug,
<Ser as Decoder<T>>::Error: Debug,
<<Ser as Decoder<T>>::Encoded as FromEncodedStr>::DecodingError: Debug,
<Ser as Encoder<T>>::Encoded: IntoEncodedString,
<Ser as Decoder<T>>::Encoded: FromEncodedStr,
{
/// Creates a new resource with the encoding `Ser`.
///
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
/// generate a new [`Future`] to load data.
///
/// On creation, if you are on the server, this will run the `fetcher` once to generate
/// a `Future` whose value will be serialized from the server to the client. If you are on
/// the client, the initial value will be deserialized without re-running that async task.
///
/// If `blocking` is `true`, this is a blocking resource.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
#[track_caller]
pub fn new_with_options<S, Fut>(
source: impl Fn() -> S + Send + Sync + 'static,
fetcher: impl Fn(S) -> Fut + Send + Sync + 'static,
#[allow(unused)] // this is used with `feature = "ssr"`
blocking: bool,
) -> ArcResource<T, Ser>
where
S: PartialEq + Clone + Send + Sync + 'static,
T: Send + Sync + 'static,
Fut: Future<Output = T> + Send + 'static,
{
let shared_context = Owner::current_shared_context();
let id = shared_context
.as_ref()
.map(|sc| sc.next_id())
.unwrap_or_default();
let initial = initial_value::<T, Ser>(&id, shared_context.as_ref());
let is_ready = initial.is_some();
let refetch = ArcRwSignal::new(0);
let source = ArcMemo::new({
let refetch = refetch.clone();
move |_| (refetch.get(), run_in_resource_source_signal(&source))
});
let fun = {
let source = source.clone();
move || {
let (_, source) = source.get();
let fut = fetcher(source);
async move {
if IS_SUPPRESSING_RESOURCE_LOAD.load(Ordering::Relaxed) {
pending().await
} else {
fut.await
}
}
}
};
let data = ArcAsyncDerived::new_with_manual_dependencies(
initial, fun, &source,
);
if is_ready {
source.with_untracked(|_| ());
source.add_subscriber(data.to_any_subscriber());
}
#[cfg(feature = "ssr")]
if let Some(shared_context) = shared_context {
let value = data.clone();
let ready_fut = data.ready();
if blocking {
shared_context.defer_stream(Box::pin(data.ready()));
}
if shared_context.get_is_hydrating() {
shared_context.write_async(
id,
Box::pin(async move {
ready_fut.await;
value.with_untracked(|data| match &data {
// TODO handle serialization errors
Some(val) => {
Ser::encode(val).unwrap().into_encoded_string()
}
_ => unreachable!(),
})
}),
);
}
}
ArcResource {
ser: PhantomData,
data,
refetch,
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
}
}
/// Synchronously, reactively reads the current value of the resource and applies the function
/// `f` to its value if it is `Some(_)`.
#[track_caller]
pub fn map<U>(&self, f: impl FnOnce(&T) -> U) -> Option<U>
where
T: Send + Sync + 'static,
{
self.data.try_with(|n| n.as_ref().map(f))?
}
/// Re-runs the async function with the current source data.
pub fn refetch(&self) {
*self.refetch.write() += 1;
}
}
#[inline(always)]
#[allow(unused)]
pub(crate) fn initial_value<T, Ser>(
id: &SerializedDataId,
shared_context: Option<&Arc<dyn SharedContext + Send + Sync>>,
) -> Option<T>
where
Ser: Encoder<T> + Decoder<T>,
<Ser as Encoder<T>>::Error: Debug,
<Ser as Decoder<T>>::Error: Debug,
<<Ser as Decoder<T>>::Encoded as FromEncodedStr>::DecodingError: Debug,
<Ser as Encoder<T>>::Encoded: IntoEncodedString,
<Ser as Decoder<T>>::Encoded: FromEncodedStr,
{
#[cfg(feature = "hydration")]
{
use std::borrow::Borrow;
let shared_context = Owner::current_shared_context();
if let Some(shared_context) = shared_context {
let value = shared_context.read_data(id);
if let Some(value) = value {
let encoded =
match <Ser as Decoder<T>>::Encoded::from_encoded_str(&value)
{
Ok(value) => value,
Err(e) => {
#[cfg(feature = "tracing")]
tracing::error!("couldn't deserialize: {e:?}");
return None;
}
};
let encoded = encoded.borrow();
match Ser::decode(encoded) {
Ok(value) => return Some(value),
#[allow(unused)]
Err(e) => {
#[cfg(feature = "tracing")]
tracing::error!("couldn't deserialize: {e:?}");
}
}
}
}
}
None
}
impl<T, E, Ser> ArcResource<Result<T, E>, Ser>
where
Ser: Encoder<Result<T, E>> + Decoder<Result<T, E>>,
<Ser as Encoder<Result<T, E>>>::Error: Debug,
<Ser as Decoder<Result<T, E>>>::Error: Debug,
<<Ser as Decoder<Result<T, E>>>::Encoded as FromEncodedStr>::DecodingError:
Debug,
<Ser as Encoder<Result<T, E>>>::Encoded: IntoEncodedString,
<Ser as Decoder<Result<T, E>>>::Encoded: FromEncodedStr,
T: Send + Sync + 'static,
E: Send + Sync + Clone + 'static,
{
/// Applies the given function when a resource that returns `Result<T, E>`
/// has resolved and loaded an `Ok(_)`, rather than requiring nested `.map()`
/// calls over the `Option<Result<_, _>>` returned by the resource.
///
/// This is useful when used with features like server functions, in conjunction
/// with `<ErrorBoundary/>` and `<Suspense/>`, when these other components are
/// left to handle the `None` and `Err(_)` states.
#[track_caller]
pub fn and_then<U>(&self, f: impl FnOnce(&T) -> U) -> Option<Result<U, E>> {
self.map(|data| data.as_ref().map(f).map_err(|e| e.clone()))
}
}
impl<T> ArcResource<T, JsonSerdeCodec>
where
JsonSerdeCodec: Encoder<T> + Decoder<T>,
<JsonSerdeCodec as Encoder<T>>::Error: Debug,
<JsonSerdeCodec as Decoder<T>>::Error: Debug,
<<JsonSerdeCodec as Decoder<T>>::Encoded as FromEncodedStr>::DecodingError:
Debug,
<JsonSerdeCodec as Encoder<T>>::Encoded: IntoEncodedString,
<JsonSerdeCodec as Decoder<T>>::Encoded: FromEncodedStr,
{
/// Creates a new resource with the encoding [`JsonSerdeCodec`].
///
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
/// generate a new [`Future`] to load data.
///
/// On creation, if you are on the server, this will run the `fetcher` once to generate
/// a `Future` whose value will be serialized from the server to the client. If you are on
/// the client, the initial value will be deserialized without re-running that async task.
#[track_caller]
pub fn new<S, Fut>(
source: impl Fn() -> S + Send + Sync + 'static,
fetcher: impl Fn(S) -> Fut + Send + Sync + 'static,
) -> Self
where
S: PartialEq + Clone + Send + Sync + 'static,
T: Send + Sync + 'static,
Fut: Future<Output = T> + Send + 'static,
{
ArcResource::new_with_options(source, fetcher, false)
}
/// Creates a new blocking resource with the encoding [`JsonSerdeCodec`].
///
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
/// generate a new [`Future`] to load data.
///
/// On creation, if you are on the server, this will run the `fetcher` once to generate
/// a `Future` whose value will be serialized from the server to the client. If you are on
/// the client, the initial value will be deserialized without re-running that async task.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
#[track_caller]
pub fn new_blocking<S, Fut>(
source: impl Fn() -> S + Send + Sync + 'static,
fetcher: impl Fn(S) -> Fut + Send + Sync + 'static,
) -> Self
where
S: PartialEq + Clone + Send + Sync + 'static,
T: Send + Sync + 'static,
Fut: Future<Output = T> + Send + 'static,
{
ArcResource::new_with_options(source, fetcher, true)
}
}
impl<T> ArcResource<T, FromToStringCodec>
where
FromToStringCodec: Encoder<T> + Decoder<T>,
<FromToStringCodec as Encoder<T>>::Error: Debug, <FromToStringCodec as Decoder<T>>::Error: Debug,
<<FromToStringCodec as Decoder<T>>::Encoded as FromEncodedStr>::DecodingError: Debug,
<FromToStringCodec as Encoder<T>>::Encoded: IntoEncodedString,
<FromToStringCodec as Decoder<T>>::Encoded: FromEncodedStr,
{
/// Creates a new resource with the encoding [`FromToStringCodec`].
///
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
/// generate a new [`Future`] to load data.
///
/// On creation, if you are on the server, this will run the `fetcher` once to generate
/// a `Future` whose value will be serialized from the server to the client. If you are on
/// the client, the initial value will be deserialized without re-running that async task.
pub fn new_str<S, Fut>(
source: impl Fn() -> S + Send + Sync + 'static,
fetcher: impl Fn(S) -> Fut + Send + Sync + 'static,
) -> Self
where
S: PartialEq + Clone + Send + Sync + 'static,
T: Send + Sync + 'static,
Fut: Future<Output = T> + Send + 'static,
{
ArcResource::new_with_options(source, fetcher, false)
}
/// Creates a new blocking resource with the encoding [`FromToStringCodec`].
///
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
/// generate a new [`Future`] to load data.
///
/// On creation, if you are on the server, this will run the `fetcher` once to generate
/// a `Future` whose value will be serialized from the server to the client. If you are on
/// the client, the initial value will be deserialized without re-running that async task.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
pub fn new_str_blocking<S, Fut>(
source: impl Fn() -> S + Send + Sync + 'static,
fetcher: impl Fn(S) -> Fut + Send + Sync + 'static,
) -> Self
where
S: PartialEq + Clone + Send + Sync + 'static,
T: Send + Sync + 'static,
Fut: Future<Output = T> + Send + 'static,
{
ArcResource::new_with_options(source, fetcher, true)
}
}
#[cfg(feature = "serde-wasm-bindgen")]
impl<T> ArcResource<T, JsonSerdeWasmCodec>
where
JsonSerdeWasmCodec: Encoder<T> + Decoder<T>,
<JsonSerdeWasmCodec as Encoder<T>>::Error: Debug, <JsonSerdeWasmCodec as Decoder<T>>::Error: Debug,
<<JsonSerdeWasmCodec as Decoder<T>>::Encoded as FromEncodedStr>::DecodingError: Debug,
<JsonSerdeWasmCodec as Encoder<T>>::Encoded: IntoEncodedString,
<JsonSerdeWasmCodec as Decoder<T>>::Encoded: FromEncodedStr,
{
/// Creates a new resource with the encoding [`JsonSerdeWasmCodec`].
///
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
/// generate a new [`Future`] to load data.
///
/// On creation, if you are on the server, this will run the `fetcher` once to generate
/// a `Future` whose value will be serialized from the server to the client. If you are on
/// the client, the initial value will be deserialized without re-running that async task.
#[track_caller]
pub fn new_serde_wb<S, Fut>(
source: impl Fn() -> S + Send + Sync + 'static,
fetcher: impl Fn(S) -> Fut + Send + Sync + 'static,
) -> Self
where
S: PartialEq + Clone + Send + Sync + 'static,
T: Send + Sync + 'static,
Fut: Future<Output = T> + Send + 'static,
{
ArcResource::new_with_options(source, fetcher, false)
}
/// Creates a new blocking resource with the encoding [`JsonSerdeWasmCodec`].
///
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
/// generate a new [`Future`] to load data.
///
/// On creation, if you are on the server, this will run the `fetcher` once to generate
/// a `Future` whose value will be serialized from the server to the client. If you are on
/// the client, the initial value will be deserialized without re-running that async task.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
#[track_caller]
pub fn new_serde_wb_blocking<S, Fut>(
source: impl Fn() -> S + Send + Sync + 'static,
fetcher: impl Fn(S) -> Fut + Send + Sync + 'static,
) -> Self
where
S: PartialEq + Clone + Send + Sync + 'static,
T: Send + Sync + 'static,
Fut: Future<Output = T> + Send + 'static,
{
ArcResource::new_with_options(source, fetcher, true)
}
}
#[cfg(feature = "miniserde")]
impl<T> ArcResource<T, MiniserdeCodec>
where
MiniserdeCodec: Encoder<T> + Decoder<T>,
<MiniserdeCodec as Encoder<T>>::Error: Debug,
<MiniserdeCodec as Decoder<T>>::Error: Debug,
<<MiniserdeCodec as Decoder<T>>::Encoded as FromEncodedStr>::DecodingError:
Debug,
<MiniserdeCodec as Encoder<T>>::Encoded: IntoEncodedString,
<MiniserdeCodec as Decoder<T>>::Encoded: FromEncodedStr,
{
/// Creates a new resource with the encoding [`MiniserdeCodec`].
///
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
/// generate a new [`Future`] to load data.
///
/// On creation, if you are on the server, this will run the `fetcher` once to generate
/// a `Future` whose value will be serialized from the server to the client. If you are on
/// the client, the initial value will be deserialized without re-running that async task.
#[track_caller]
pub fn new_miniserde<S, Fut>(
source: impl Fn() -> S + Send + Sync + 'static,
fetcher: impl Fn(S) -> Fut + Send + Sync + 'static,
) -> Self
where
S: PartialEq + Clone + Send + Sync + 'static,
T: Send + Sync + 'static,
Fut: Future<Output = T> + Send + 'static,
{
ArcResource::new_with_options(source, fetcher, false)
}
/// Creates a new blocking resource with the encoding [`MiniserdeCodec`].
///
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
/// generate a new [`Future`] to load data.
///
/// On creation, if you are on the server, this will run the `fetcher` once to generate
/// a `Future` whose value will be serialized from the server to the client. If you are on
/// the client, the initial value will be deserialized without re-running that async task.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
#[track_caller]
pub fn new_miniserde_blocking<S, Fut>(
source: impl Fn() -> S + Send + Sync + 'static,
fetcher: impl Fn(S) -> Fut + Send + Sync + 'static,
) -> Self
where
S: PartialEq + Clone + Send + Sync + 'static,
T: Send + Sync + 'static,
Fut: Future<Output = T> + Send + 'static,
{
ArcResource::new_with_options(source, fetcher, true)
}
}
#[cfg(feature = "serde-lite")]
impl<T> ArcResource<T, SerdeLite<JsonSerdeCodec>>
where
SerdeLite<JsonSerdeCodec>: Encoder<T> + Decoder<T>,
<SerdeLite<JsonSerdeCodec> as Encoder<T>>::Error: Debug, <SerdeLite<JsonSerdeCodec> as Decoder<T>>::Error: Debug,
<<SerdeLite<JsonSerdeCodec> as Decoder<T>>::Encoded as FromEncodedStr>::DecodingError: Debug,
<SerdeLite<JsonSerdeCodec> as Encoder<T>>::Encoded: IntoEncodedString,
<SerdeLite<JsonSerdeCodec> as Decoder<T>>::Encoded: FromEncodedStr,
{
/// Creates a new resource with the encoding [`SerdeLite`].
///
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
/// generate a new [`Future`] to load data.
///
/// On creation, if you are on the server, this will run the `fetcher` once to generate
/// a `Future` whose value will be serialized from the server to the client. If you are on
/// the client, the initial value will be deserialized without re-running that async task.
#[track_caller]
pub fn new_serde_lite<S, Fut>(
source: impl Fn() -> S + Send + Sync + 'static,
fetcher: impl Fn(S) -> Fut + Send + Sync + 'static,
) -> Self
where
S: PartialEq + Clone + Send + Sync + 'static,
T: Send + Sync + 'static,
Fut: Future<Output = T> + Send + 'static,
{
ArcResource::new_with_options(source, fetcher, false)
}
/// Creates a new blocking resource with the encoding [`SerdeLite`].
///
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
/// generate a new [`Future`] to load data.
///
/// On creation, if you are on the server, this will run the `fetcher` once to generate
/// a `Future` whose value will be serialized from the server to the client. If you are on
/// the client, the initial value will be deserialized without re-running that async task.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
#[track_caller]
pub fn new_serde_lite_blocking<S, Fut>(
source: impl Fn() -> S + Send + Sync + 'static,
fetcher: impl Fn(S) -> Fut + Send + Sync + 'static,
) -> Self
where
S: PartialEq + Clone + Send + Sync + 'static,
T: Send + Sync + 'static,
Fut: Future<Output = T> + Send + 'static,
{
ArcResource::new_with_options(source, fetcher, true)
}
}
#[cfg(feature = "rkyv")]
#[cfg_attr(docsrs, doc(cfg(feature = "rkyv")))]
impl<T> ArcResource<T, RkyvCodec>
where
RkyvCodec: Encoder<T> + Decoder<T>,
<RkyvCodec as Encoder<T>>::Error: Debug,
<RkyvCodec as Decoder<T>>::Error: Debug,
<<RkyvCodec as Decoder<T>>::Encoded as FromEncodedStr>::DecodingError:
Debug,
<RkyvCodec as Encoder<T>>::Encoded: IntoEncodedString,
<RkyvCodec as Decoder<T>>::Encoded: FromEncodedStr,
{
/// Creates a new resource with the encoding [`RkyvCodec`].
///
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
/// generate a new [`Future`] to load data.
///
/// On creation, if you are on the server, this will run the `fetcher` once to generate
/// a `Future` whose value will be serialized from the server to the client. If you are on
/// the client, the initial value will be deserialized without re-running that async task.
#[track_caller]
pub fn new_rkyv<S, Fut>(
source: impl Fn() -> S + Send + Sync + 'static,
fetcher: impl Fn(S) -> Fut + Send + Sync + 'static,
) -> Self
where
S: PartialEq + Clone + Send + Sync + 'static,
T: Send + Sync + 'static,
Fut: Future<Output = T> + Send + 'static,
{
ArcResource::new_with_options(source, fetcher, false)
}
/// Creates a new blocking resource with the encoding [`RkyvCodec`].
///
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
/// generate a new [`Future`] to load data.
///
/// On creation, if you are on the server, this will run the `fetcher` once to generate
/// a `Future` whose value will be serialized from the server to the client. If you are on
/// the client, the initial value will be deserialized without re-running that async task.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
#[track_caller]
pub fn new_rkyv_blocking<S, Fut>(
source: impl Fn() -> S + Send + Sync + 'static,
fetcher: impl Fn(S) -> Fut + Send + Sync + 'static,
) -> Self
where
S: PartialEq + Clone + Send + Sync + 'static,
T: Send + Sync + 'static,
Fut: Future<Output = T> + Send + 'static,
{
ArcResource::new_with_options(source, fetcher, true)
}
}
impl<T, Ser> IntoFuture for ArcResource<T, Ser>
where
T: Clone + 'static,
{
type Output = T;
type IntoFuture = AsyncDerivedFuture<T>;
fn into_future(self) -> Self::IntoFuture {
self.data.into_future()
}
}
impl<T, Ser> ArcResource<T, Ser>
where
T: 'static,
{
/// Returns a new [`Future`] that is ready when the resource has loaded, and accesses its inner
/// value by reference.
pub fn by_ref(&self) -> AsyncDerivedRefFuture<T> {
self.data.by_ref()
}
}
/// An asynchronous resource.
///
/// Resources allow asynchronously loading data and serializing it from the server to the client,
/// so that it loads on the server, and is then deserialized on the client. This improves
/// performance by beginning data loading on the server when the request is made, rather than
/// beginning it on the client after WASM has been loaded.
///
/// You can access the value of the resource either synchronously using `.get()` or asynchronously
/// using `.await`.
pub struct Resource<T, Ser = JsonSerdeCodec>
where
T: Send + Sync + 'static,
{
ser: PhantomData<Ser>,
data: AsyncDerived<T>,
refetch: RwSignal<usize>,
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: &'static Location<'static>,
}
impl<T, Ser> Debug for Resource<T, Ser>
where
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | true |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos_server/src/multi_action.rs | leptos_server/src/multi_action.rs | use reactive_graph::{
actions::{ArcMultiAction, MultiAction},
traits::DefinedAt,
};
use server_fn::ServerFn;
use std::{ops::Deref, panic::Location};
/// An [`ArcMultiAction`] that can be used to call a server function.
pub struct ArcServerMultiAction<S>
where
S: ServerFn + 'static,
S::Output: 'static,
{
inner: ArcMultiAction<S, Result<S::Output, S::Error>>,
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: &'static Location<'static>,
}
impl<S> ArcServerMultiAction<S>
where
S: ServerFn + Clone + Send + Sync + 'static,
S::Output: Send + Sync + 'static,
S::Error: Send + Sync + 'static,
{
/// Creates a new [`ArcMultiAction`] which, when dispatched, will call the server function `S`.
#[track_caller]
pub fn new() -> Self {
Self {
inner: ArcMultiAction::new(|input: &S| {
S::run_on_client(input.clone())
}),
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
}
}
}
impl<S> Deref for ArcServerMultiAction<S>
where
S: ServerFn + 'static,
S::Output: 'static,
{
type Target = ArcMultiAction<S, Result<S::Output, S::Error>>;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl<S> Clone for ArcServerMultiAction<S>
where
S: ServerFn + 'static,
S::Output: 'static,
{
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: self.defined_at,
}
}
}
impl<S> Default for ArcServerMultiAction<S>
where
S: ServerFn + Clone + Send + Sync + 'static,
S::Output: Send + Sync + 'static,
S::Error: Send + Sync + 'static,
{
fn default() -> Self {
Self::new()
}
}
impl<S> DefinedAt for ArcServerMultiAction<S>
where
S: ServerFn + 'static,
S::Output: '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
}
}
}
/// A [`MultiAction`] that can be used to call a server function.
pub struct ServerMultiAction<S>
where
S: ServerFn + 'static,
S::Output: 'static,
{
inner: MultiAction<S, Result<S::Output, S::Error>>,
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: &'static Location<'static>,
}
impl<S> From<ServerMultiAction<S>>
for MultiAction<S, Result<S::Output, S::Error>>
where
S: ServerFn + 'static,
S::Output: 'static,
{
fn from(value: ServerMultiAction<S>) -> Self {
value.inner
}
}
impl<S> ServerMultiAction<S>
where
S: ServerFn + Send + Sync + Clone + 'static,
S::Output: Send + Sync + 'static,
S::Error: Send + Sync + 'static,
{
/// Creates a new [`MultiAction`] which, when dispatched, will call the server function `S`.
pub fn new() -> Self {
Self {
inner: MultiAction::new(|input: &S| {
S::run_on_client(input.clone())
}),
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
}
}
}
impl<S> Clone for ServerMultiAction<S>
where
S: ServerFn + 'static,
S::Output: 'static,
{
fn clone(&self) -> Self {
*self
}
}
impl<S> Copy for ServerMultiAction<S>
where
S: ServerFn + 'static,
S::Output: 'static,
{
}
impl<S> Deref for ServerMultiAction<S>
where
S: ServerFn + 'static,
S::Output: 'static,
S::Error: 'static,
{
type Target = MultiAction<S, Result<S::Output, S::Error>>;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl<S> Default for ServerMultiAction<S>
where
S: ServerFn + Clone + Send + Sync + 'static,
S::Output: Send + Sync + 'static,
S::Error: Send + Sync + 'static,
{
fn default() -> Self {
Self::new()
}
}
impl<S> DefinedAt for ServerMultiAction<S>
where
S: ServerFn + 'static,
S::Output: '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
}
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos_server/src/lib.rs | leptos_server/src/lib.rs | //! Utilities for communicating between the server and the client with Leptos.
#![deny(missing_docs)]
#![forbid(unsafe_code)]
mod action;
pub use action::*;
use std::borrow::Borrow;
mod local_resource;
pub use local_resource::*;
mod multi_action;
pub use multi_action::*;
mod once_resource;
pub use once_resource::*;
mod resource;
pub use resource::*;
mod shared;
use base64::{engine::general_purpose::STANDARD_NO_PAD, DecodeError, Engine};
/// Re-export of the `codee` crate.
pub use codee;
pub use shared::*;
/// Encodes data into a string.
pub trait IntoEncodedString {
/// Encodes the data.
fn into_encoded_string(self) -> String;
}
/// Decodes data from a string.
pub trait FromEncodedStr {
/// The decoded data.
type DecodedType<'a>: Borrow<Self>;
/// The type of an error encountered during decoding.
type DecodingError;
/// Decodes the string.
fn from_encoded_str(
data: &str,
) -> Result<Self::DecodedType<'_>, Self::DecodingError>;
}
impl IntoEncodedString for String {
fn into_encoded_string(self) -> String {
self
}
}
impl FromEncodedStr for str {
type DecodedType<'a> = &'a str;
type DecodingError = ();
fn from_encoded_str(
data: &str,
) -> Result<Self::DecodedType<'_>, Self::DecodingError> {
Ok(data)
}
}
impl IntoEncodedString for Vec<u8> {
fn into_encoded_string(self) -> String {
STANDARD_NO_PAD.encode(self)
}
}
impl FromEncodedStr for [u8] {
type DecodedType<'a> = Vec<u8>;
type DecodingError = DecodeError;
fn from_encoded_str(
data: &str,
) -> Result<Self::DecodedType<'_>, Self::DecodingError> {
STANDARD_NO_PAD.decode(data)
}
}
#[cfg(feature = "tachys")]
mod view_implementations {
use crate::Resource;
use reactive_graph::traits::Read;
use std::future::Future;
use tachys::{
html::attribute::{any_attribute::AnyAttribute, Attribute},
hydration::Cursor,
reactive_graph::{RenderEffectState, Suspend, SuspendState},
ssr::StreamBuilder,
view::{
add_attr::AddAnyAttr, Position, PositionState, Render, RenderHtml,
},
};
impl<T, Ser> Render for Resource<T, Ser>
where
T: Render + Send + Sync + Clone,
Ser: Send + 'static,
{
type State = RenderEffectState<SuspendState<T>>;
fn build(self) -> Self::State {
(move || Suspend::new(async move { self.await })).build()
}
fn rebuild(self, state: &mut Self::State) {
(move || Suspend::new(async move { self.await })).rebuild(state)
}
}
impl<T, Ser> AddAnyAttr for Resource<T, Ser>
where
T: RenderHtml + Send + Sync + Clone,
Ser: Send + 'static,
{
type Output<SomeNewAttr: Attribute> = Box<
dyn FnMut() -> Suspend<
<T as AddAnyAttr>::Output<
<SomeNewAttr::CloneableOwned as Attribute>::CloneableOwned,
>,
>
+ Send
>;
fn add_any_attr<NewAttr: Attribute>(
self,
attr: NewAttr,
) -> Self::Output<NewAttr>
where
Self::Output<NewAttr>: RenderHtml,
{
(move || Suspend::new(async move { self.await })).add_any_attr(attr)
}
}
impl<T, Ser> RenderHtml for Resource<T, Ser>
where
T: RenderHtml + Send + Sync + Clone,
Ser: Send + 'static,
{
type AsyncOutput = Option<T>;
type Owned = Self;
const MIN_LENGTH: usize = 0;
fn dry_resolve(&mut self) {
self.read();
}
fn resolve(self) -> impl Future<Output = Self::AsyncOutput> + Send {
(move || Suspend::new(async move { self.await })).resolve()
}
fn to_html_with_buf(
self,
buf: &mut String,
position: &mut Position,
escape: bool,
mark_branches: bool,
extra_attrs: Vec<AnyAttribute>,
) {
(move || Suspend::new(async move { self.await })).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,
{
(move || Suspend::new(async move { self.await }))
.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 || Suspend::new(async move { self.await }))
.hydrate::<FROM_SERVER>(cursor, position)
}
fn into_owned(self) -> Self::Owned {
self
}
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos_server/src/serializers.rs | leptos_server/src/serializers.rs | use core::str::FromStr;
use serde::{de::DeserializeOwned, Serialize};
pub trait SerializableData<Ser: Serializer>: Sized {
type SerErr;
type DeErr;
fn ser(&self) -> Result<String, Self::SerErr>;
fn de(data: &str) -> Result<Self, Self::DeErr>;
}
pub trait Serializer {}
/// A [`Serializer`] that serializes using [`ToString`] and deserializes
/// using [`FromStr`](core::str::FromStr).
pub struct Str;
impl Serializer for Str {}
impl<T> SerializableData<Str> for T
where
T: ToString + FromStr,
{
type SerErr = ();
type DeErr = <T as FromStr>::Err;
fn ser(&self) -> Result<String, Self::SerErr> {
Ok(self.to_string())
}
fn de(data: &str) -> Result<Self, Self::DeErr> {
T::from_str(data)
}
}
/// A [`Serializer`] that serializes using [`serde_json`].
pub struct SerdeJson;
impl Serializer for SerdeJson {}
impl<T> SerializableData<SerdeJson> for T
where
T: DeserializeOwned + Serialize,
{
type SerErr = serde_json::Error;
type DeErr = serde_json::Error;
fn ser(&self) -> Result<String, Self::SerErr> {
serde_json::to_string(&self)
}
fn de(data: &str) -> Result<Self, Self::DeErr> {
serde_json::from_str(data)
}
}
#[cfg(feature = "miniserde")]
mod miniserde {
use super::{SerializableData, Serializer};
use miniserde::{json, Deserialize, Serialize};
/// A [`Serializer`] that serializes and deserializes using [`miniserde`].
pub struct Miniserde;
impl Serializer for Miniserde {}
impl<T> SerializableData<Miniserde> for T
where
T: Deserialize + Serialize,
{
type SerErr = ();
type DeErr = miniserde::Error;
fn ser(&self) -> Result<String, Self::SerErr> {
Ok(json::to_string(&self))
}
fn de(data: &str) -> Result<Self, Self::DeErr> {
json::from_str(data)
}
}
}
#[cfg(feature = "miniserde")]
pub use miniserde::*;
#[cfg(feature = "serde-lite")]
mod serde_lite {
use super::{SerializableData, Serializer};
use serde_lite::{Deserialize, Serialize};
use thiserror::Error;
#[derive(Error, Debug)]
pub enum SerdeLiteError {
#[error("serde_lite error {0:?}")]
SerdeLite(serde_lite::Error),
#[error("serde_json error {0:?}")]
SerdeJson(serde_json::Error),
}
impl From<serde_lite::Error> for SerdeLiteError {
fn from(value: serde_lite::Error) -> Self {
SerdeLiteError::SerdeLite(value)
}
}
impl From<serde_json::Error> for SerdeLiteError {
fn from(value: serde_json::Error) -> Self {
SerdeLiteError::SerdeJson(value)
}
}
/// A [`Serializer`] that serializes and deserializes using [`serde_lite`].
pub struct SerdeLite;
impl Serializer for SerdeLite {}
impl<T> SerializableData<SerdeLite> for T
where
T: Deserialize + Serialize,
{
type SerErr = SerdeLiteError;
type DeErr = SerdeLiteError;
fn ser(&self) -> Result<String, Self::SerErr> {
let intermediate = self.serialize()?;
Ok(serde_json::to_string(&intermediate)?)
}
fn de(data: &str) -> Result<Self, Self::DeErr> {
let intermediate = serde_json::from_str(data)?;
Ok(Self::deserialize(&intermediate)?)
}
}
}
#[cfg(feature = "serde-lite")]
pub use serde_lite::*;
#[cfg(feature = "rkyv")]
mod rkyv {
use super::{SerializableData, Serializer};
use base64::{engine::general_purpose::STANDARD_NO_PAD, Engine as _};
use rkyv::{
de::deserializers::SharedDeserializeMap,
ser::serializers::AllocSerializer,
validation::validators::DefaultValidator, Archive, CheckBytes,
Deserialize, Serialize,
};
use std::{error::Error, sync::Arc};
use thiserror::Error;
/// A [`Serializer`] that serializes and deserializes using [`rkyv`].
pub struct Rkyv;
impl Serializer for Rkyv {}
#[derive(Error, Debug)]
pub enum RkyvError {
#[error("rkyv error {0:?}")]
Rkyv(Arc<dyn Error>),
#[error("base64 error {0:?}")]
Base64Decode(base64::DecodeError),
}
impl From<Arc<dyn Error>> for RkyvError {
fn from(value: Arc<dyn Error>) -> Self {
RkyvError::Rkyv(value)
}
}
impl From<base64::DecodeError> for RkyvError {
fn from(value: base64::DecodeError) -> Self {
RkyvError::Base64Decode(value)
}
}
impl<T> SerializableData<Rkyv> for T
where
T: Serialize<AllocSerializer<1024>>,
T: Archive,
T::Archived: for<'b> CheckBytes<DefaultValidator<'b>>
+ Deserialize<T, SharedDeserializeMap>,
{
type SerErr = RkyvError;
type DeErr = RkyvError;
fn ser(&self) -> Result<String, Self::SerErr> {
let bytes = rkyv::to_bytes::<T, 1024>(self)
.map_err(|e| Arc::new(e) as Arc<dyn Error>)?;
Ok(STANDARD_NO_PAD.encode(bytes))
}
fn de(data: &str) -> Result<Self, Self::DeErr> {
let bytes = STANDARD_NO_PAD.decode(data.as_bytes())?;
Ok(rkyv::from_bytes::<T>(&bytes)
.map_err(|e| Arc::new(e) as Arc<dyn Error>)?)
}
}
}
#[cfg(feature = "rkyv")]
pub use rkyv::*;
#[cfg(feature = "serde-wasm-bindgen")]
mod serde_wasm_bindgen {
use super::{SerializableData, Serializer};
use serde::{de::DeserializeOwned, Serialize};
/// A [`Serializer`] that serializes using [`serde_json`] and deserializes using
/// [`serde-wasm-bindgen`].
pub struct SerdeWasmBindgen;
impl Serializer for SerdeWasmBindgen {}
impl<T> SerializableData<SerdeWasmBindgen> for T
where
T: DeserializeOwned + Serialize,
{
type SerErr = serde_json::Error;
type DeErr = wasm_bindgen::JsValue;
fn ser(&self) -> Result<String, Self::SerErr> {
serde_json::to_string(&self)
}
fn de(data: &str) -> Result<Self, Self::DeErr> {
let json = js_sys::JSON::parse(data)?;
serde_wasm_bindgen::from_value(json).map_err(Into::into)
}
}
}
#[cfg(feature = "serde-wasm-bindgen")]
pub use serde_wasm_bindgen::*;
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos_server/src/shared.rs | leptos_server/src/shared.rs | use crate::{FromEncodedStr, IntoEncodedString};
#[cfg(feature = "rkyv")]
use codee::binary::RkyvCodec;
#[cfg(feature = "serde-wasm-bindgen")]
use codee::string::JsonSerdeWasmCodec;
#[cfg(feature = "miniserde")]
use codee::string::MiniserdeCodec;
#[cfg(feature = "serde-lite")]
use codee::SerdeLite;
use codee::{
string::{FromToStringCodec, JsonSerdeCodec},
Decoder, Encoder,
};
use std::{
fmt::{Debug, Display},
hash::Hash,
marker::PhantomData,
ops::{Deref, DerefMut},
};
/// A smart pointer that allows you to share identical, synchronously-loaded data between the
/// server and the client.
///
/// If this constructed on the server, it serializes its value into the shared context. If it is
/// constructed on the client during hydration, it reads its value from the shared context. If
/// it it constructed on the client at any other time, it simply runs on the client.
#[derive(Debug)]
pub struct SharedValue<T, Ser = JsonSerdeCodec> {
value: T,
ser: PhantomData<Ser>,
}
impl<T, Ser> SharedValue<T, Ser> {
/// Returns the inner value.
pub fn into_inner(self) -> T {
self.value
}
}
impl<T> SharedValue<T, JsonSerdeCodec>
where
JsonSerdeCodec: Encoder<T> + Decoder<T>,
<JsonSerdeCodec as Encoder<T>>::Error: Debug,
<JsonSerdeCodec as Decoder<T>>::Error: Debug,
<JsonSerdeCodec as Encoder<T>>::Encoded: IntoEncodedString,
<JsonSerdeCodec as Decoder<T>>::Encoded: FromEncodedStr,
<<JsonSerdeCodec as codee::Decoder<T>>::Encoded as FromEncodedStr>::DecodingError:
Debug,
{
/// Wraps the initial value.
///
/// If this is on the server, the function will be invoked and the value serialized. When it runs
/// on the client, it will be deserialized without running the function again.
///
/// This uses the [`JsonSerdeCodec`] encoding.
pub fn new(initial: impl FnOnce() -> T) -> Self {
SharedValue::new_with_encoding(initial)
}
}
impl<T> SharedValue<T, FromToStringCodec>
where
FromToStringCodec: Encoder<T> + Decoder<T>,
<FromToStringCodec as Encoder<T>>::Error: Debug,
<FromToStringCodec as Decoder<T>>::Error: Debug,
<FromToStringCodec as Encoder<T>>::Encoded: IntoEncodedString,
<FromToStringCodec as Decoder<T>>::Encoded: FromEncodedStr,
<<FromToStringCodec as codee::Decoder<T>>::Encoded as FromEncodedStr>::DecodingError:
Debug,
{
/// Wraps the initial value.
///
/// If this is on the server, the function will be invoked and the value serialized. When it runs
/// on the client, it will be deserialized without running the function again.
///
/// This uses the [`FromToStringCodec`] encoding.
pub fn new_str(initial: impl FnOnce() -> T) -> Self {
SharedValue::new_with_encoding(initial)
}
}
#[cfg(feature = "serde-lite")]
#[cfg_attr(docsrs, doc(cfg(feature = "serde-lite")))]
impl<T> SharedValue<T, SerdeLite<JsonSerdeCodec>>
where
SerdeLite<JsonSerdeCodec>: Encoder<T> + Decoder<T>,
<SerdeLite<JsonSerdeCodec> as Encoder<T>>::Error: Debug,
<SerdeLite<JsonSerdeCodec> as Decoder<T>>::Error: Debug,
<SerdeLite<JsonSerdeCodec> as Encoder<T>>::Encoded: IntoEncodedString,
<SerdeLite<JsonSerdeCodec> as Decoder<T>>::Encoded: FromEncodedStr,
<<SerdeLite<JsonSerdeCodec> as codee::Decoder<T>>::Encoded as FromEncodedStr>::DecodingError:
Debug,
{
/// Wraps the initial value.
///
/// If this is on the server, the function will be invoked and the value serialized. When it runs
/// on the client, it will be deserialized without running the function again.
///
/// This uses the [`SerdeLite`] encoding.
pub fn new_serde_lite(initial: impl FnOnce() -> T) -> Self {
SharedValue::new_with_encoding(initial)
}
}
#[cfg(feature = "serde-wasm-bindgen")]
#[cfg_attr(docsrs, doc(cfg(feature = "serde-wasm-bindgen")))]
impl<T> SharedValue<T, JsonSerdeWasmCodec>
where
JsonSerdeWasmCodec: Encoder<T> + Decoder<T>,
<JsonSerdeWasmCodec as Encoder<T>>::Error: Debug,
<JsonSerdeWasmCodec as Decoder<T>>::Error: Debug,
<JsonSerdeWasmCodec as Encoder<T>>::Encoded: IntoEncodedString,
<JsonSerdeWasmCodec as Decoder<T>>::Encoded: FromEncodedStr,
<<JsonSerdeWasmCodec as codee::Decoder<T>>::Encoded as FromEncodedStr>::DecodingError:
Debug,
{
/// Wraps the initial value.
///
/// If this is on the server, the function will be invoked and the value serialized. When it runs
/// on the client, it will be deserialized without running the function again.
///
/// This uses the [`JsonSerdeWasmCodec`] encoding.
pub fn new_serde_wb(initial: impl FnOnce() -> T) -> Self {
SharedValue::new_with_encoding(initial)
}
}
#[cfg(feature = "miniserde")]
#[cfg_attr(docsrs, doc(cfg(feature = "miniserde")))]
impl<T> SharedValue<T, MiniserdeCodec>
where
MiniserdeCodec: Encoder<T> + Decoder<T>,
<MiniserdeCodec as Encoder<T>>::Error: Debug,
<MiniserdeCodec as Decoder<T>>::Error: Debug,
<MiniserdeCodec as Encoder<T>>::Encoded: IntoEncodedString,
<MiniserdeCodec as Decoder<T>>::Encoded: FromEncodedStr,
<<MiniserdeCodec as codee::Decoder<T>>::Encoded as FromEncodedStr>::DecodingError:
Debug,
{
/// Wraps the initial value.
///
/// If this is on the server, the function will be invoked and the value serialized. When it runs
/// on the client, it will be deserialized without running the function again.
///
/// This uses the [`MiniserdeCodec`] encoding.
pub fn new_miniserde(initial: impl FnOnce() -> T) -> Self {
SharedValue::new_with_encoding(initial)
}
}
#[cfg(feature = "rkyv")]
#[cfg_attr(docsrs, doc(cfg(feature = "rkyv")))]
impl<T> SharedValue<T, RkyvCodec>
where
RkyvCodec: Encoder<T> + Decoder<T>,
<RkyvCodec as Encoder<T>>::Error: Debug,
<RkyvCodec as Decoder<T>>::Error: Debug,
<RkyvCodec as Encoder<T>>::Encoded: IntoEncodedString,
<RkyvCodec as Decoder<T>>::Encoded: FromEncodedStr,
<<RkyvCodec as codee::Decoder<T>>::Encoded as FromEncodedStr>::DecodingError:
Debug,
{
/// Wraps the initial value.
///
/// If this is on the server, the function will be invoked and the value serialized. When it runs
/// on the client, it will be deserialized without running the function again.
///
/// This uses the [`RkyvCodec`] encoding.
pub fn new_rkyv(initial: impl FnOnce() -> T) -> Self {
SharedValue::new_with_encoding(initial)
}
}
impl<T, Ser> SharedValue<T, Ser>
where
Ser: Encoder<T> + Decoder<T>,
<Ser as Encoder<T>>::Error: Debug,
<Ser as Decoder<T>>::Error: Debug,
<Ser as Encoder<T>>::Encoded: IntoEncodedString,
<Ser as Decoder<T>>::Encoded: FromEncodedStr,
<<Ser as codee::Decoder<T>>::Encoded as FromEncodedStr>::DecodingError:
Debug,
{
/// Wraps the initial value.
///
/// If this is on the server, the function will be invoked and the value serialized. When it runs
/// on the client, it will be deserialized without running the function again.
///
/// This uses `Ser` as an encoding.
pub fn new_with_encoding(initial: impl FnOnce() -> T) -> Self {
let value: T;
#[cfg(feature = "hydration")]
{
use reactive_graph::owner::Owner;
use std::borrow::Borrow;
let sc = Owner::current_shared_context();
let id = sc.as_ref().map(|sc| sc.next_id()).unwrap_or_default();
let serialized = sc.as_ref().and_then(|sc| sc.read_data(&id));
let hydrating =
sc.as_ref().map(|sc| sc.during_hydration()).unwrap_or(false);
value = if hydrating {
let value = match serialized {
None => {
#[cfg(feature = "tracing")]
tracing::error!("couldn't deserialize");
None
}
Some(data) => {
match <Ser as Decoder<T>>::Encoded::from_encoded_str(
&data,
) {
#[allow(unused_variables)] // used in tracing
Err(e) => {
#[cfg(feature = "tracing")]
tracing::error!(
"couldn't deserialize from {data:?}: {e:?}"
);
None
}
Ok(encoded) => {
let decoded = Ser::decode(encoded.borrow());
#[cfg(feature = "tracing")]
let decoded = decoded
.inspect_err(|e| tracing::error!("{e:?}"));
decoded.ok()
}
}
}
};
value.unwrap_or_else(initial)
} else {
let init = initial();
#[cfg(feature = "ssr")]
if let Some(sc) = sc {
if sc.get_is_hydrating() {
match Ser::encode(&init)
.map(IntoEncodedString::into_encoded_string)
{
Ok(value) => sc.write_async(
id,
Box::pin(async move { value }),
),
#[allow(unused_variables)] // used in tracing
Err(e) => {
#[cfg(feature = "tracing")]
tracing::error!("couldn't serialize: {e:?}");
}
}
}
}
init
}
}
#[cfg(not(feature = "hydration"))]
{
value = initial();
}
Self {
value,
ser: PhantomData,
}
}
}
impl<T, Ser> Deref for SharedValue<T, Ser> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.value
}
}
impl<T, Ser> DerefMut for SharedValue<T, Ser> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.value
}
}
impl<T, Ser> PartialEq for SharedValue<T, Ser>
where
T: PartialEq,
{
fn eq(&self, other: &Self) -> bool {
self.value == other.value
}
}
impl<T, Ser> Eq for SharedValue<T, Ser> where T: Eq {}
impl<T, Ser> Display for SharedValue<T, Ser>
where
T: Display,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.value)
}
}
impl<T, Ser> Hash for SharedValue<T, Ser>
where
T: Hash,
{
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.value.hash(state);
}
}
impl<T, Ser> PartialOrd for SharedValue<T, Ser>
where
T: PartialOrd,
{
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
self.value.partial_cmp(&other.value)
}
}
impl<T, Ser> Ord for SharedValue<T, Ser>
where
T: Ord,
{
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.value.cmp(&other.value)
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos_server/src/action.rs | leptos_server/src/action.rs | use reactive_graph::{
actions::{Action, ArcAction},
owner::use_context,
traits::DefinedAt,
};
use server_fn::{
error::{FromServerFnError, ServerFnUrlError},
ServerFn,
};
use std::{ops::Deref, panic::Location, sync::Arc};
/// An error that can be caused by a server action.
///
/// This is used for propagating errors from the server to the client when JS/WASM are not
/// supported.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ServerActionError {
path: Arc<str>,
err: Arc<str>,
}
impl ServerActionError {
/// Creates a new error associated with the given path.
pub fn new(path: &str, err: &str) -> Self {
Self {
path: path.into(),
err: err.into(),
}
}
/// The path with which this error is associated.
pub fn path(&self) -> &str {
&self.path
}
/// The error message.
pub fn err(&self) -> &str {
&self.err
}
}
/// An [`ArcAction`] that can be used to call a server function.
pub struct ArcServerAction<S>
where
S: ServerFn + 'static,
S::Output: 'static,
{
inner: ArcAction<S, Result<S::Output, S::Error>>,
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: &'static Location<'static>,
}
impl<S> ArcServerAction<S>
where
S: ServerFn + Clone + Send + Sync + 'static,
S::Output: Send + Sync + 'static,
S::Error: Send + Sync + 'static,
S::Error: FromServerFnError,
{
/// Creates a new [`ArcAction`] that will call the server function `S` when dispatched.
#[track_caller]
pub fn new() -> Self {
let err = use_context::<ServerActionError>().and_then(|error| {
(error.path() == S::PATH)
.then(|| ServerFnUrlError::<S::Error>::decode_err(error.err()))
.map(Err)
});
Self {
inner: ArcAction::new_with_value(err, |input: &S| {
S::run_on_client(input.clone())
}),
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
}
}
}
impl<S> Deref for ArcServerAction<S>
where
S: ServerFn + 'static,
S::Output: 'static,
{
type Target = ArcAction<S, Result<S::Output, S::Error>>;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl<S> Clone for ArcServerAction<S>
where
S: ServerFn + 'static,
S::Output: 'static,
{
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: self.defined_at,
}
}
}
impl<S> Default for ArcServerAction<S>
where
S: ServerFn + Clone + Send + Sync + 'static,
S::Output: Send + Sync + 'static,
S::Error: Send + Sync + 'static,
{
fn default() -> Self {
Self::new()
}
}
impl<S> DefinedAt for ArcServerAction<S>
where
S: ServerFn + 'static,
S::Output: 'static,
{
fn defined_at(&self) -> Option<&'static Location<'static>> {
#[cfg(any(debug_assertions, leptos_debuginfo))]
{
Some(self.defined_at)
}
#[cfg(not(any(debug_assertions, leptos_debuginfo)))]
{
None
}
}
}
/// An [`Action`] that can be used to call a server function.
pub struct ServerAction<S>
where
S: ServerFn + 'static,
S::Output: 'static,
{
inner: Action<S, Result<S::Output, S::Error>>,
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: &'static Location<'static>,
}
impl<S> ServerAction<S>
where
S: ServerFn + Send + Sync + Clone + 'static,
S::Output: Send + Sync + 'static,
S::Error: Send + Sync + 'static,
{
/// Creates a new [`Action`] that will call the server function `S` when dispatched.
pub fn new() -> Self {
let err = use_context::<ServerActionError>().and_then(|error| {
(error.path() == S::PATH)
.then(|| ServerFnUrlError::<S::Error>::decode_err(error.err()))
.map(Err)
});
Self {
inner: Action::new_with_value(err, |input: &S| {
S::run_on_client(input.clone())
}),
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
}
}
}
impl<S> Clone for ServerAction<S>
where
S: ServerFn + 'static,
S::Output: 'static,
{
fn clone(&self) -> Self {
*self
}
}
impl<S> Copy for ServerAction<S>
where
S: ServerFn + 'static,
S::Output: 'static,
{
}
impl<S> Deref for ServerAction<S>
where
S: ServerFn + Clone + Send + Sync + 'static,
S::Output: Send + Sync + 'static,
S::Error: Send + Sync + 'static,
{
type Target = Action<S, Result<S::Output, S::Error>>;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl<S> From<ServerAction<S>> for Action<S, Result<S::Output, S::Error>>
where
S: ServerFn + 'static,
S::Output: 'static,
{
fn from(value: ServerAction<S>) -> Self {
value.inner
}
}
impl<S> Default for ServerAction<S>
where
S: ServerFn + Clone + Send + Sync + 'static,
S::Output: Send + Sync + 'static,
S::Error: Send + Sync + 'static,
{
fn default() -> Self {
Self::new()
}
}
impl<S> DefinedAt for ServerAction<S>
where
S: ServerFn + 'static,
S::Output: '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
}
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos_server/src/local_resource.rs | leptos_server/src/local_resource.rs | use reactive_graph::{
computed::{
suspense::LocalResourceNotifier, ArcAsyncDerived, AsyncDerived,
AsyncDerivedFuture,
},
graph::{
AnySource, AnySubscriber, ReactiveNode, Source, Subscriber,
ToAnySource, ToAnySubscriber,
},
owner::use_context,
send_wrapper_ext::SendOption,
signal::{
guards::{AsyncPlain, Mapped, ReadGuard},
ArcRwSignal, RwSignal,
},
traits::{
DefinedAt, IsDisposed, Notify, ReadUntracked, Track, UntrackableGuard,
Update, With, Write,
},
};
use std::{
future::{pending, Future, IntoFuture},
ops::{Deref, DerefMut},
panic::Location,
};
/// A reference-counted resource that only loads its data locally on the client.
pub struct ArcLocalResource<T> {
data: ArcAsyncDerived<T>,
refetch: ArcRwSignal<usize>,
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: &'static Location<'static>,
}
impl<T> Clone for ArcLocalResource<T> {
fn clone(&self) -> Self {
Self {
data: self.data.clone(),
refetch: self.refetch.clone(),
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: self.defined_at,
}
}
}
impl<T> Deref for ArcLocalResource<T> {
type Target = ArcAsyncDerived<T>;
fn deref(&self) -> &Self::Target {
&self.data
}
}
impl<T> ArcLocalResource<T> {
/// Creates the resource.
///
/// This will only begin loading data if you are on the client (i.e., if you do not have the
/// `ssr` feature activated).
#[track_caller]
pub fn new<Fut>(fetcher: impl Fn() -> Fut + 'static) -> Self
where
T: 'static,
Fut: Future<Output = T> + 'static,
{
let fetcher = move || {
let fut = fetcher();
async move {
// in SSR mode, this will simply always be pending
// if we try to read from it, we will trigger Suspense automatically to fall back
// so this will never need to return anything
if cfg!(feature = "ssr") {
pending().await
} else {
// LocalResources that are immediately available can cause a hydration error,
// because the future *looks* like it is already ready (and therefore would
// already have been rendered to html on the server), but in fact was ignored
// on the server. the simplest way to avoid this is to ensure that we always
// wait a tick before resolving any value for a localresource.
any_spawner::Executor::tick().await;
fut.await
}
}
};
let refetch = ArcRwSignal::new(0);
Self {
data: if cfg!(feature = "ssr") {
ArcAsyncDerived::new_mock(fetcher)
} else {
let refetch = refetch.clone();
ArcAsyncDerived::new_unsync(move || {
refetch.track();
fetcher()
})
},
refetch,
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
}
}
/// Re-runs the async function.
pub fn refetch(&self) {
*self.refetch.write() += 1;
}
/// Synchronously, reactively reads the current value of the resource and applies the function
/// `f` to its value if it is `Some(_)`.
#[track_caller]
pub fn map<U>(&self, f: impl FnOnce(&T) -> U) -> Option<U>
where
T: 'static,
{
self.data.try_with(|n| n.as_ref().map(f))?
}
}
impl<T, E> ArcLocalResource<Result<T, E>>
where
T: 'static,
E: Clone + 'static,
{
/// Applies the given function when a resource that returns `Result<T, E>`
/// has resolved and loaded an `Ok(_)`, rather than requiring nested `.map()`
/// calls over the `Option<Result<_, _>>` returned by the resource.
///
/// This is useful when used with features like server functions, in conjunction
/// with `<ErrorBoundary/>` and `<Suspense/>`, when these other components are
/// left to handle the `None` and `Err(_)` states.
#[track_caller]
pub fn and_then<U>(&self, f: impl FnOnce(&T) -> U) -> Option<Result<U, E>> {
self.map(|data| data.as_ref().map(f).map_err(|e| e.clone()))
}
}
impl<T> IntoFuture for ArcLocalResource<T>
where
T: Clone + 'static,
{
type Output = T;
type IntoFuture = AsyncDerivedFuture<T>;
fn into_future(self) -> Self::IntoFuture {
if let Some(mut notifier) = use_context::<LocalResourceNotifier>() {
notifier.notify();
} else if cfg!(feature = "ssr") {
panic!(
"Reading from a LocalResource outside Suspense in `ssr` mode \
will cause the response to hang, because LocalResources are \
always pending on the server."
);
}
self.data.into_future()
}
}
impl<T> DefinedAt for ArcLocalResource<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 ArcLocalResource<T>
where
T: 'static,
{
fn notify(&self) {
self.data.notify()
}
}
impl<T> Write for ArcLocalResource<T>
where
T: 'static,
{
type Value = Option<T>;
fn try_write(&self) -> Option<impl UntrackableGuard<Target = Self::Value>> {
self.data.try_write()
}
fn try_write_untracked(
&self,
) -> Option<impl DerefMut<Target = Self::Value>> {
self.data.try_write_untracked()
}
}
impl<T> ReadUntracked for ArcLocalResource<T>
where
T: 'static,
{
type Value =
ReadGuard<Option<T>, Mapped<AsyncPlain<SendOption<T>>, Option<T>>>;
fn try_read_untracked(&self) -> Option<Self::Value> {
if let Some(mut notifier) = use_context::<LocalResourceNotifier>() {
notifier.notify();
}
self.data.try_read_untracked()
}
}
impl<T: 'static> IsDisposed for ArcLocalResource<T> {
#[inline(always)]
fn is_disposed(&self) -> bool {
false
}
}
impl<T: 'static> ToAnySource for ArcLocalResource<T> {
fn to_any_source(&self) -> AnySource {
self.data.to_any_source()
}
}
impl<T: 'static> ToAnySubscriber for ArcLocalResource<T> {
fn to_any_subscriber(&self) -> AnySubscriber {
self.data.to_any_subscriber()
}
}
impl<T> Source for ArcLocalResource<T> {
fn add_subscriber(&self, subscriber: AnySubscriber) {
self.data.add_subscriber(subscriber)
}
fn remove_subscriber(&self, subscriber: &AnySubscriber) {
self.data.remove_subscriber(subscriber);
}
fn clear_subscribers(&self) {
self.data.clear_subscribers();
}
}
impl<T> ReactiveNode for ArcLocalResource<T> {
fn mark_dirty(&self) {
self.data.mark_dirty();
}
fn mark_check(&self) {
self.data.mark_check();
}
fn mark_subscribers_check(&self) {
self.data.mark_subscribers_check();
}
fn update_if_necessary(&self) -> bool {
self.data.update_if_necessary()
}
}
impl<T> Subscriber for ArcLocalResource<T> {
fn add_source(&self, source: AnySource) {
self.data.add_source(source);
}
fn clear_sources(&self, subscriber: &AnySubscriber) {
self.data.clear_sources(subscriber);
}
}
/// A resource that only loads its data locally on the client.
pub struct LocalResource<T> {
data: AsyncDerived<T>,
refetch: RwSignal<usize>,
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: &'static Location<'static>,
}
impl<T> Deref for LocalResource<T> {
type Target = AsyncDerived<T>;
fn deref(&self) -> &Self::Target {
&self.data
}
}
impl<T> Clone for LocalResource<T> {
fn clone(&self) -> Self {
*self
}
}
impl<T> Copy for LocalResource<T> {}
impl<T> LocalResource<T> {
/// Creates the resource.
///
/// This will only begin loading data if you are on the client (i.e., if you do not have the
/// `ssr` feature activated).
#[track_caller]
pub fn new<Fut>(fetcher: impl Fn() -> Fut + 'static) -> Self
where
T: 'static,
Fut: Future<Output = T> + 'static,
{
let fetcher = move || {
let fut = fetcher();
async move {
// in SSR mode, this will simply always be pending
// if we try to read from it, we will trigger Suspense automatically to fall back
// so this will never need to return anything
if cfg!(feature = "ssr") {
pending().await
} else {
// LocalResources that are immediately available can cause a hydration error,
// because the future *looks* like it is already ready (and therefore would
// already have been rendered to html on the server), but in fact was ignored
// on the server. the simplest way to avoid this is to ensure that we always
// wait a tick before resolving any value for a localresource.
any_spawner::Executor::tick().await;
fut.await
}
}
};
let refetch = RwSignal::new(0);
Self {
data: if cfg!(feature = "ssr") {
AsyncDerived::new_mock(fetcher)
} else {
AsyncDerived::new_unsync_threadsafe_storage(move || {
refetch.track();
fetcher()
})
},
refetch,
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
}
}
/// Re-runs the async function.
pub fn refetch(&self) {
self.refetch.try_update(|n| *n += 1);
}
/// Synchronously, reactively reads the current value of the resource and applies the function
/// `f` to its value if it is `Some(_)`.
#[track_caller]
pub fn map<U>(&self, f: impl FnOnce(&T) -> U) -> Option<U>
where
T: 'static,
{
self.data.try_with(|n| n.as_ref().map(f))?
}
}
impl<T, E> LocalResource<Result<T, E>>
where
T: 'static,
E: Clone + 'static,
{
/// Applies the given function when a resource that returns `Result<T, E>`
/// has resolved and loaded an `Ok(_)`, rather than requiring nested `.map()`
/// calls over the `Option<Result<_, _>>` returned by the resource.
///
/// This is useful when used with features like server functions, in conjunction
/// with `<ErrorBoundary/>` and `<Suspense/>`, when these other components are
/// left to handle the `None` and `Err(_)` states.
#[track_caller]
pub fn and_then<U>(&self, f: impl FnOnce(&T) -> U) -> Option<Result<U, E>> {
self.map(|data| data.as_ref().map(f).map_err(|e| e.clone()))
}
}
impl<T> IntoFuture for LocalResource<T>
where
T: Clone + 'static,
{
type Output = T;
type IntoFuture = AsyncDerivedFuture<T>;
fn into_future(self) -> Self::IntoFuture {
if let Some(mut notifier) = use_context::<LocalResourceNotifier>() {
notifier.notify();
} else if cfg!(feature = "ssr") {
panic!(
"Reading from a LocalResource outside Suspense in `ssr` mode \
will cause the response to hang, because LocalResources are \
always pending on the server."
);
}
self.data.into_future()
}
}
impl<T> DefinedAt for LocalResource<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 LocalResource<T>
where
T: 'static,
{
fn notify(&self) {
self.data.notify()
}
}
impl<T> Write for LocalResource<T>
where
T: 'static,
{
type Value = Option<T>;
fn try_write(&self) -> Option<impl UntrackableGuard<Target = Self::Value>> {
self.data.try_write()
}
fn try_write_untracked(
&self,
) -> Option<impl DerefMut<Target = Self::Value>> {
self.data.try_write_untracked()
}
}
impl<T> ReadUntracked for LocalResource<T>
where
T: 'static,
{
type Value =
ReadGuard<Option<T>, Mapped<AsyncPlain<SendOption<T>>, Option<T>>>;
fn try_read_untracked(&self) -> Option<Self::Value> {
if let Some(mut notifier) = use_context::<LocalResourceNotifier>() {
notifier.notify();
}
self.data.try_read_untracked()
}
}
impl<T: 'static> IsDisposed for LocalResource<T> {
fn is_disposed(&self) -> bool {
self.data.is_disposed()
}
}
impl<T: 'static> ToAnySource for LocalResource<T>
where
T: 'static,
{
fn to_any_source(&self) -> AnySource {
self.data.to_any_source()
}
}
impl<T: 'static> ToAnySubscriber for LocalResource<T>
where
T: 'static,
{
fn to_any_subscriber(&self) -> AnySubscriber {
self.data.to_any_subscriber()
}
}
impl<T> Source for LocalResource<T>
where
T: 'static,
{
fn add_subscriber(&self, subscriber: AnySubscriber) {
self.data.add_subscriber(subscriber)
}
fn remove_subscriber(&self, subscriber: &AnySubscriber) {
self.data.remove_subscriber(subscriber);
}
fn clear_subscribers(&self) {
self.data.clear_subscribers();
}
}
impl<T> ReactiveNode for LocalResource<T>
where
T: 'static,
{
fn mark_dirty(&self) {
self.data.mark_dirty();
}
fn mark_check(&self) {
self.data.mark_check();
}
fn mark_subscribers_check(&self) {
self.data.mark_subscribers_check();
}
fn update_if_necessary(&self) -> bool {
self.data.update_if_necessary()
}
}
impl<T> Subscriber for LocalResource<T>
where
T: 'static,
{
fn add_source(&self, source: AnySource) {
self.data.add_source(source);
}
fn clear_sources(&self, subscriber: &AnySubscriber) {
self.data.clear_sources(subscriber);
}
}
impl<T: 'static> From<ArcLocalResource<T>> for LocalResource<T> {
fn from(arc: ArcLocalResource<T>) -> Self {
Self {
data: arc.data.into(),
refetch: arc.refetch.into(),
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: arc.defined_at,
}
}
}
impl<T: 'static> From<LocalResource<T>> for ArcLocalResource<T> {
fn from(local: LocalResource<T>) -> Self {
Self {
data: local.data.into(),
refetch: local.refetch.into(),
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: local.defined_at,
}
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/sso_auth_axum/src/lib.rs | projects/sso_auth_axum/src/lib.rs | pub mod auth;
pub mod error_template;
#[cfg(feature = "ssr")]
pub mod fallback;
pub mod sign_in_sign_up;
#[cfg(feature = "ssr")]
pub mod state;
use leptos::{leptos_dom::helpers::TimeoutHandle, *};
use leptos_meta::*;
use leptos_router::*;
use sign_in_sign_up::*;
#[cfg(feature = "ssr")]
mod ssr_imports {
pub use crate::auth::ssr_imports::{AuthSession, SqlRefreshToken};
pub use leptos::{use_context, ServerFnError};
pub use oauth2::{reqwest::async_http_client, TokenResponse};
pub use sqlx::SqlitePool;
pub fn pool() -> Result<SqlitePool, ServerFnError> {
use_context::<SqlitePool>()
.ok_or_else(|| ServerFnError::new("Pool missing."))
}
pub fn auth() -> Result<AuthSession, ServerFnError> {
use_context::<AuthSession>()
.ok_or_else(|| ServerFnError::new("Auth session missing."))
}
}
#[derive(Clone, Debug)]
pub struct Email(RwSignal<Option<String>>);
#[derive(Clone, Debug)]
pub struct ExpiresIn(RwSignal<u64>);
#[server]
pub async fn refresh_token(email: String) -> Result<u64, ServerFnError> {
use crate::{auth::User, state::AppState};
use ssr_imports::*;
let pool = pool()?;
let oauth_client = expect_context::<AppState>().client;
let user = User::get_from_email(&email, &pool)
.await
.ok_or(ServerFnError::new("User not found"))?;
let refresh_secret = sqlx::query_as::<_, SqlRefreshToken>(
"SELECT secret FROM google_refresh_tokens WHERE user_id = ?",
)
.bind(user.id)
.fetch_one(&pool)
.await?
.secret;
let token_response = oauth_client
.exchange_refresh_token(&oauth2::RefreshToken::new(refresh_secret))
.request_async(async_http_client)
.await?;
let access_token = token_response.access_token().secret();
let expires_in = token_response.expires_in().unwrap().as_secs();
let refresh_secret = token_response.refresh_token().unwrap().secret();
sqlx::query("DELETE FROM google_tokens WHERE user_id == ?")
.bind(user.id)
.execute(&pool)
.await?;
sqlx::query(
"INSERT OR REPLACE INTO google_tokens (user_id,access_secret,refresh_secret) \
VALUES (?,?,?)",
)
.bind(user.id)
.bind(access_token)
.bind(refresh_secret)
.execute(&pool)
.await?;
Ok(expires_in)
}
#[component]
pub fn App() -> impl IntoView {
provide_meta_context();
let email = RwSignal::new(None::<String>);
let rw_expires_in = RwSignal::new(0);
provide_context(Email(email));
provide_context(ExpiresIn(rw_expires_in));
let display_email =
move || email.get().unwrap_or(String::from("No email to display"));
let refresh_token = create_server_action::<RefreshToken>();
create_effect(move |handle: Option<Option<TimeoutHandle>>| {
// If this effect is called, try to cancel the previous handle.
if let Some(prev_handle) = handle.flatten() {
prev_handle.clear();
};
// if expires_in isn't 0, then set a timeout that rerfresh a minute short of the refresh.
let expires_in = rw_expires_in.get();
if expires_in != 0 && email.get_untracked().is_some() {
let handle = set_timeout_with_handle(
move || {
refresh_token.dispatch(RefreshToken {
email: email.get_untracked().unwrap(),
})
},
std::time::Duration::from_secs(
// Google tokens last 3599 seconds, so we'll get a refresh token every 14 seconds.
expires_in.checked_sub(3545).unwrap_or_default(),
),
)
.unwrap();
Some(handle)
} else {
None
}
});
create_effect(move |_| {
if let Some(Ok(expires_in)) = refresh_token.value().get() {
rw_expires_in.set(expires_in);
}
});
view! {
<Stylesheet id="leptos" href="/pkg/sso_auth_axum.css"/>
<Link rel="shortcut icon" type_="image/ico" href="/favicon.ico"/>
<Title text="SSO Auth Axum"/>
<Router>
<main>
<Routes>
<Route path="" view=move || {
view!{
{display_email}
<Show when=move || email.get().is_some() fallback=||view!{<SignIn/>}>
<LogOut/>
</Show>
}
}/>
<Route path="g_auth" view=||view!{<HandleGAuth/>}/>
</Routes>
</main>
</Router>
}
}
#[cfg(feature = "hydrate")]
#[wasm_bindgen::prelude::wasm_bindgen]
pub fn hydrate() {
_ = console_log::init_with_level(log::Level::Debug);
console_error_panic_hook::set_once();
leptos::mount_to_body(App);
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/sso_auth_axum/src/state.rs | projects/sso_auth_axum/src/state.rs | use axum::extract::FromRef;
use leptos::LeptosOptions;
use sqlx::SqlitePool;
/// This takes advantage of Axum's SubStates feature by deriving FromRef. This is the only way to have more than one
/// item in Axum's State. Leptos requires you to have leptosOptions in your State struct for the leptos route handlers
#[derive(FromRef, Debug, Clone)]
pub struct AppState {
pub leptos_options: LeptosOptions,
pub pool: SqlitePool,
pub client: oauth2::basic::BasicClient,
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/sso_auth_axum/src/auth.rs | projects/sso_auth_axum/src/auth.rs | use serde::{Deserialize, Serialize};
use std::collections::HashSet;
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct User {
pub id: i64,
pub email: String,
pub permissions: HashSet<String>,
}
impl Default for User {
fn default() -> Self {
let permissions = HashSet::new();
Self {
id: -1,
email: "example@example.com".into(),
permissions,
}
}
}
#[cfg(feature = "ssr")]
pub mod ssr_imports {
use super::User;
pub use axum_session_auth::{
Authentication, HasPermission, SessionSqlitePool,
};
pub use sqlx::SqlitePool;
use std::collections::HashSet;
pub type AuthSession = axum_session_auth::AuthSession<
User,
i64,
SessionSqlitePool,
SqlitePool,
>;
use async_trait::async_trait;
impl User {
pub async fn get(id: i64, pool: &SqlitePool) -> Option<Self> {
let sqluser = sqlx::query_as::<_, SqlUser>(
"SELECT * FROM users WHERE id = ?",
)
.bind(id)
.fetch_one(pool)
.await
.ok()?;
//lets just get all the tokens the user can use, we will only use the full permissions if modifying them.
let sql_user_perms = sqlx::query_as::<_, SqlPermissionTokens>(
"SELECT token FROM user_permissions WHERE user_id = ?;",
)
.bind(id)
.fetch_all(pool)
.await
.ok()?;
Some(sqluser.into_user(Some(sql_user_perms)))
}
pub async fn get_from_email(
email: &str,
pool: &SqlitePool,
) -> Option<Self> {
let sqluser = sqlx::query_as::<_, SqlUser>(
"SELECT * FROM users WHERE email = ?",
)
.bind(email)
.fetch_one(pool)
.await
.ok()?;
//lets just get all the tokens the user can use, we will only use the full permissions if modifying them.
let sql_user_perms = sqlx::query_as::<_, SqlPermissionTokens>(
"SELECT token FROM user_permissions WHERE user_id = ?;",
)
.bind(sqluser.id)
.fetch_all(pool)
.await
.ok()?;
Some(sqluser.into_user(Some(sql_user_perms)))
}
}
#[derive(sqlx::FromRow, Clone)]
pub struct SqlPermissionTokens {
pub token: String,
}
#[derive(sqlx::FromRow, Clone)]
pub struct SqlCsrfToken {
pub csrf_token: String,
}
#[async_trait]
impl Authentication<User, i64, SqlitePool> for User {
async fn load_user(
userid: i64,
pool: Option<&SqlitePool>,
) -> Result<User, anyhow::Error> {
let pool = pool.unwrap();
User::get(userid, pool)
.await
.ok_or_else(|| anyhow::anyhow!("Cannot get user"))
}
fn is_authenticated(&self) -> bool {
true
}
fn is_active(&self) -> bool {
true
}
fn is_anonymous(&self) -> bool {
false
}
}
#[async_trait]
impl HasPermission<SqlitePool> for User {
async fn has(&self, perm: &str, _pool: &Option<&SqlitePool>) -> bool {
self.permissions.contains(perm)
}
}
#[derive(sqlx::FromRow, Clone)]
pub struct SqlUser {
pub id: i64,
pub email: String,
}
#[derive(sqlx::FromRow, Clone)]
pub struct SqlRefreshToken {
pub secret: String,
}
impl SqlUser {
pub fn into_user(
self,
sql_user_perms: Option<Vec<SqlPermissionTokens>>,
) -> User {
User {
id: self.id,
email: self.email,
permissions: if let Some(user_perms) = sql_user_perms {
user_perms
.into_iter()
.map(|x| x.token)
.collect::<HashSet<String>>()
} else {
HashSet::<String>::new()
},
}
}
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/sso_auth_axum/src/sign_in_sign_up.rs | projects/sso_auth_axum/src/sign_in_sign_up.rs | use super::*;
#[cfg(feature = "ssr")]
pub mod ssr_imports {
pub use crate::{
auth::{ssr_imports::SqlCsrfToken, User},
state::AppState,
};
pub use oauth2::{
reqwest::async_http_client, AuthorizationCode, CsrfToken, Scope,
TokenResponse,
};
pub use serde_json::Value;
}
#[server]
pub async fn google_sso() -> Result<String, ServerFnError> {
use crate::ssr_imports::*;
use ssr_imports::*;
let oauth_client = expect_context::<AppState>().client;
let pool = pool()?;
// We get the authorization URL and CSRF_TOKEN
let (authorize_url, csrf_token) = oauth_client
.authorize_url(CsrfToken::new_random)
.add_scope(Scope::new("openid".to_string()))
.add_scope(Scope::new("email".to_string()))
// required for google auth refresh token to be part of the response.
.add_extra_param("access_type", "offline")
.add_extra_param("prompt", "consent")
.url();
let url = authorize_url.to_string();
leptos::logging::log!("{url:?}");
// Store the CSRF_TOKEN in our sqlite db.
sqlx::query("INSERT INTO csrf_tokens (csrf_token) VALUES (?)")
.bind(csrf_token.secret())
.execute(&pool)
.await
.map(|_| ())?;
// Send the url to the client.
Ok(url)
}
#[component]
pub fn SignIn() -> impl IntoView {
let g_auth = Action::<GoogleSso, _>::server();
create_effect(move |_| {
if let Some(Ok(redirect)) = g_auth.value().get() {
window().location().set_href(&redirect).unwrap();
}
});
view! {
<div style="
display:flex;
flex-direction: column;
justify-content: center;
align-items: center;
">
<div> {"Sign Up Sign In"} </div>
<button style="display:flex;" on:click=move|_| g_auth.dispatch(GoogleSso{})>
<svg style="width:2rem;" version="1.1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48 48" xmlns:xlink="http://www.w3.org/1999/xlink" style="display: block;">
<path fill="#EA4335" d="M24 9.5c3.54 0 6.71 1.22 9.21 3.6l6.85-6.85C35.9 2.38 30.47 0 24 0 14.62 0 6.51 5.38 2.56 13.22l7.98 6.19C12.43 13.72 17.74 9.5 24 9.5z"></path>
<path fill="#4285F4" d="M46.98 24.55c0-1.57-.15-3.09-.38-4.55H24v9.02h12.94c-.58 2.96-2.26 5.48-4.78 7.18l7.73 6c4.51-4.18 7.09-10.36 7.09-17.65z"></path>
<path fill="#FBBC05" d="M10.53 28.59c-.48-1.45-.76-2.99-.76-4.59s.27-3.14.76-4.59l-7.98-6.19C.92 16.46 0 20.12 0 24c0 3.88.92 7.54 2.56 10.78l7.97-6.19z"></path>
<path fill="#34A853" d="M24 48c6.48 0 11.93-2.13 15.89-5.81l-7.73-6c-2.15 1.45-4.92 2.3-8.16 2.3-6.26 0-11.57-4.22-13.47-9.91l-7.98 6.19C6.51 42.62 14.62 48 24 48z"></path>
<path fill="none" d="M0 0h48v48H0z"></path>
</svg>
<span style="margin-left:0.5rem;">"Sign in with Google"</span>
</button>
</div>
}
}
#[server]
pub async fn handle_g_auth_redirect(
provided_csrf: String,
code: String,
) -> Result<(String, u64), ServerFnError> {
use crate::ssr_imports::*;
use ssr_imports::*;
let oauth_client = expect_context::<AppState>().client;
let pool = pool()?;
let auth_session = auth()?;
// If there's no match we'll return an error.
let _ = sqlx::query_as::<_, SqlCsrfToken>(
"SELECT csrf_token FROM csrf_tokens WHERE csrf_token = ?",
)
.bind(provided_csrf)
.fetch_one(&pool)
.await
.map_err(|err| ServerFnError::new(format!("CSRF_TOKEN error : {err:?}")))?;
let token_response = oauth_client
.exchange_code(AuthorizationCode::new(code.clone()))
.request_async(async_http_client)
.await?;
leptos::logging::log!("{:?}", &token_response);
let access_token = token_response.access_token().secret();
let expires_in = token_response.expires_in().unwrap().as_secs();
let refresh_secret = token_response.refresh_token().unwrap().secret();
let user_info_url = "https://www.googleapis.com/oauth2/v3/userinfo";
let client = reqwest::Client::new();
let response = client
.get(user_info_url)
.bearer_auth(access_token)
.send()
.await?;
let email = if response.status().is_success() {
let response_json: Value = response.json().await?;
leptos::logging::log!("{response_json:?}");
response_json["email"]
.as_str()
.expect("email to parse to string")
.to_string()
} else {
return Err(ServerFnError::new(format!(
"Response from google has status of {}",
response.status()
)));
};
let user = if let Some(user) = User::get_from_email(&email, &pool).await {
user
} else {
sqlx::query("INSERT INTO users (email) VALUES (?)")
.bind(&email)
.execute(&pool)
.await?;
User::get_from_email(&email, &pool).await.unwrap()
};
auth_session.login_user(user.id);
sqlx::query("DELETE FROM google_tokens WHERE user_id == ?")
.bind(user.id)
.execute(&pool)
.await?;
sqlx::query(
"INSERT INTO google_tokens (user_id,access_secret,refresh_secret) \
VALUES (?,?,?)",
)
.bind(user.id)
.bind(access_token)
.bind(refresh_secret)
.execute(&pool)
.await?;
Ok((user.email, expires_in as u64))
}
#[derive(Params, Debug, PartialEq, Clone)]
pub struct OAuthParams {
pub code: Option<String>,
pub state: Option<String>,
}
#[component]
pub fn HandleGAuth() -> impl IntoView {
let handle_g_auth_redirect = Action::<HandleGAuthRedirect, _>::server();
let query = use_query::<OAuthParams>();
let navigate = leptos_router::use_navigate();
let rw_email = expect_context::<Email>().0;
let rw_expires_in = expect_context::<ExpiresIn>().0;
create_effect(move |_| {
if let Some(Ok((email, expires_in))) =
handle_g_auth_redirect.value().get()
{
rw_email.set(Some(email));
rw_expires_in.set(expires_in);
navigate("/", NavigateOptions::default());
}
});
create_effect(move |_| {
if let Ok(OAuthParams { code, state }) = query.get_untracked() {
handle_g_auth_redirect.dispatch(HandleGAuthRedirect {
provided_csrf: state.unwrap(),
code: code.unwrap(),
});
} else {
leptos::logging::log!("error parsing oauth params");
}
});
view! {}
}
#[server]
pub async fn logout() -> Result<(), ServerFnError> {
use crate::ssr_imports::*;
let auth = auth()?;
auth.logout_user();
leptos_axum::redirect("/");
Ok(())
}
#[component]
pub fn LogOut() -> impl IntoView {
let log_out = create_server_action::<Logout>();
view! {
<button on:click=move|_|log_out.dispatch(Logout{})>{"log out"}</button>
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/sso_auth_axum/src/error_template.rs | projects/sso_auth_axum/src/error_template.rs | use leptos::{view, Errors, For, IntoView, RwSignal, SignalGet, View};
// A basic function to display errors served by the error boundaries. Feel free to do more complicated things
// here than just displaying them
pub fn error_template(errors: RwSignal<Errors>) -> View {
view! {
<h1>"Errors"</h1>
<For
// a function that returns the items we're iterating over; a signal is fine
each=move || errors.get()
// a unique key for each item as a reference
key=|(key, _)| key.clone()
// renders each item to a view
children= move | (_, error)| {
let error_string = error.to_string();
view! {
<p>"Error: " {error_string}</p>
}
}
/>
}
.into_view()
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/sso_auth_axum/src/main.rs | projects/sso_auth_axum/src/main.rs | use crate::ssr_imports::*;
use axum::{
body::Body as AxumBody,
extract::{Path, State},
http::Request,
response::IntoResponse,
routing::get,
Router,
};
use axum_session::{Key, SessionConfig, SessionLayer, SessionStore};
use axum_session_auth::{AuthConfig, AuthSessionLayer};
use leptos::{get_configuration, logging::log, provide_context, view};
use leptos_axum::{
generate_route_list, handle_server_fns_with_context, LeptosRoutes,
};
use sqlx::sqlite::SqlitePoolOptions;
use sso_auth_axum::{
auth::*, fallback::file_and_error_handler, state::AppState,
};
async fn server_fn_handler(
State(app_state): State<AppState>,
auth_session: AuthSession,
path: Path<String>,
request: Request<AxumBody>,
) -> impl IntoResponse {
log!("{:?}", path);
handle_server_fns_with_context(
move || {
provide_context(app_state.clone());
provide_context(auth_session.clone());
provide_context(app_state.pool.clone());
},
request,
)
.await
}
pub async fn leptos_routes_handler(
auth_session: AuthSession,
State(app_state): State<AppState>,
axum::extract::State(option): axum::extract::State<leptos::LeptosOptions>,
request: Request<AxumBody>,
) -> axum::response::Response {
let handler = leptos_axum::render_app_async_with_context(
option.clone(),
move || {
provide_context(app_state.clone());
provide_context(auth_session.clone());
provide_context(app_state.pool.clone());
},
move || view! { <sso_auth_axum::App/> },
);
handler(request).await.into_response()
}
#[tokio::main]
async fn main() {
simple_logger::init_with_level(log::Level::Info)
.expect("couldn't initialize logging");
let pool = SqlitePoolOptions::new()
.connect("sqlite:sso.db")
.await
.expect("Could not make pool.");
// Auth section
let session_config = SessionConfig::default()
.with_table_name("sessions_table")
.with_key(Key::generate())
.with_database_key(Key::generate());
// .with_security_mode(SecurityMode::PerSession); // FIXME did this disappear?
let auth_config = AuthConfig::<i64>::default();
let session_store = SessionStore::<SessionSqlitePool>::new(
Some(pool.clone().into()),
session_config,
)
.await
.unwrap();
sqlx::migrate!()
.run(&pool)
.await
.expect("could not run SQLx migrations");
// Setting this to None means we'll be using cargo-leptos and its env vars
let conf = get_configuration(None).unwrap();
let leptos_options = conf.leptos_options;
let addr = leptos_options.site_addr;
let routes = generate_route_list(sso_auth_axum::App);
// We create our client using provided environment variables.
let client = oauth2::basic::BasicClient::new(
oauth2::ClientId::new(
std::env::var("G_AUTH_CLIENT_ID")
.expect("G_AUTH_CLIENT_ID Env var to be set."),
),
Some(oauth2::ClientSecret::new(
std::env::var("G_AUTH_SECRET")
.expect("G_AUTH_SECRET Env var to be set"),
)),
oauth2::AuthUrl::new(
"https://accounts.google.com/o/oauth2/v2/auth".to_string(),
)
.unwrap(),
Some(
oauth2::TokenUrl::new(
"https://oauth2.googleapis.com/token".to_string(),
)
.unwrap(),
),
)
.set_redirect_uri(
oauth2::RedirectUrl::new(
std::env::var("REDIRECT_URL")
.expect("REDIRECT_URL Env var to be set"),
)
.unwrap(),
);
let app_state = AppState {
leptos_options,
pool: pool.clone(),
client,
};
// build our application with a route
let app = Router::new()
.route(
"/api/*fn_name",
get(server_fn_handler).post(server_fn_handler),
)
.leptos_routes_with_handler(routes, get(leptos_routes_handler))
.fallback(file_and_error_handler)
.layer(
AuthSessionLayer::<User, i64, SessionSqlitePool, SqlitePool>::new(
Some(pool.clone()),
)
.with_config(auth_config),
)
.layer(SessionLayer::new(session_store))
.with_state(app_state);
// run our app with hyper
// `axum::Server` is a re-export of `hyper::Server`
let listener = tokio::net::TcpListener::bind(&addr).await.unwrap();
log!("listening on http://{}", &addr);
axum::serve(listener, app.into_make_service())
.await
.unwrap();
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/sso_auth_axum/src/fallback.rs | projects/sso_auth_axum/src/fallback.rs | use crate::error_template::error_template;
use axum::{
body::Body,
extract::State,
http::{Request, Response, StatusCode, Uri},
response::{IntoResponse, Response as AxumResponse},
};
use leptos::prelude::*;
use tower::ServiceExt;
use tower_http::services::ServeDir;
pub async fn file_and_error_handler(
uri: Uri,
State(options): State<LeptosOptions>,
req: Request<Body>,
) -> AxumResponse {
let root = options.site_root.clone();
let res = get_static_file(uri.clone(), &root).await.unwrap();
if res.status() == StatusCode::OK {
res.into_response()
} else {
leptos::logging::log!("{:?}:{}", res.status(), uri);
let handler =
leptos_axum::render_app_to_stream(options.to_owned(), || {
error_template(RwSignal::new(leptos::Errors::default()))
});
handler(req).await.into_response()
}
}
async fn get_static_file(
uri: Uri,
root: &str,
) -> Result<Response<Body>, (StatusCode, String)> {
let req = Request::builder()
.uri(uri.clone())
.body(Body::empty())
.unwrap();
// `ServeDir` implements `tower::Service` so we can call it with `tower::ServiceExt::oneshot`
// This path is relative to the cargo root
match ServeDir::new(root).oneshot(req).await {
Ok(res) => Ok(res.into_response()),
Err(err) => Err((
StatusCode::INTERNAL_SERVER_ERROR,
format!("Something went wrong: {}", err),
)),
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/login_with_token_csr_only/api-boundary/src/lib.rs | projects/login_with_token_csr_only/api-boundary/src/lib.rs | use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
pub struct Credentials {
pub email: String,
pub password: String,
}
#[derive(Clone, Serialize, Deserialize)]
pub struct UserInfo {
pub email: String,
}
#[derive(Clone, Serialize, Deserialize)]
pub struct ApiToken {
pub token: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Error {
pub message: String,
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/login_with_token_csr_only/server/src/adapters.rs | projects/login_with_token_csr_only/server/src/adapters.rs | use crate::{application::*, Error};
use api_boundary as json;
use axum::{
http::StatusCode,
response::{IntoResponse, Json, Response},
};
use thiserror::Error;
impl From<InvalidEmailAddress> for json::Error {
fn from(_: InvalidEmailAddress) -> Self {
Self {
message: "Invalid email address".to_string(),
}
}
}
impl From<InvalidPassword> for json::Error {
fn from(err: InvalidPassword) -> Self {
let InvalidPassword::TooShort(min_len) = err;
Self {
message: format!("Invalid password (min. length = {min_len})"),
}
}
}
impl From<CreateUserError> for json::Error {
fn from(err: CreateUserError) -> Self {
let message = match err {
CreateUserError::UserExists => "User already exits".to_string(),
};
Self { message }
}
}
impl From<LoginError> for json::Error {
fn from(err: LoginError) -> Self {
let message = match err {
LoginError::InvalidEmailOrPassword => {
"Invalid email or password".to_string()
}
};
Self { message }
}
}
impl From<LogoutError> for json::Error {
fn from(err: LogoutError) -> Self {
let message = match err {
LogoutError::NotLoggedIn => "No user is logged in".to_string(),
};
Self { message }
}
}
impl From<AuthError> for json::Error {
fn from(err: AuthError) -> Self {
let message = match err {
AuthError::NotAuthorized => "Not authorized".to_string(),
};
Self { message }
}
}
impl From<CredentialParsingError> for json::Error {
fn from(err: CredentialParsingError) -> Self {
match err {
CredentialParsingError::EmailAddress(err) => err.into(),
CredentialParsingError::Password(err) => err.into(),
}
}
}
#[derive(Debug, Error)]
pub enum CredentialParsingError {
#[error(transparent)]
EmailAddress(#[from] InvalidEmailAddress),
#[error(transparent)]
Password(#[from] InvalidPassword),
}
impl TryFrom<json::Credentials> for Credentials {
type Error = CredentialParsingError;
fn try_from(
json::Credentials { email, password }: json::Credentials,
) -> Result<Self, Self::Error> {
let email: EmailAddress = email.parse()?;
let password = Password::try_from(password)?;
Ok(Self { email, password })
}
}
impl IntoResponse for Error {
fn into_response(self) -> Response {
let (code, value) = match self {
Self::Logout(err) => {
(StatusCode::BAD_REQUEST, json::Error::from(err))
}
Self::Login(err) => {
(StatusCode::BAD_REQUEST, json::Error::from(err))
}
Self::Credentials(err) => {
(StatusCode::BAD_REQUEST, json::Error::from(err))
}
Self::CreateUser(err) => {
(StatusCode::BAD_REQUEST, json::Error::from(err))
}
Self::Auth(err) => {
(StatusCode::UNAUTHORIZED, json::Error::from(err))
}
};
(code, Json(value)).into_response()
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/login_with_token_csr_only/server/src/application.rs | projects/login_with_token_csr_only/server/src/application.rs | use mailparse::addrparse;
use pwhash::bcrypt;
use std::{collections::HashMap, str::FromStr};
use thiserror::Error;
use uuid::Uuid;
#[derive(Default)]
pub struct AppState {
users: HashMap<EmailAddress, Password>,
tokens: HashMap<Uuid, EmailAddress>,
}
impl AppState {
pub fn create_user(
&mut self,
credentials: Credentials,
) -> Result<(), CreateUserError> {
let Credentials { email, password } = credentials;
let user_exists = self.users.contains_key(&email);
if user_exists {
return Err(CreateUserError::UserExists);
}
self.users.insert(email, password);
Ok(())
}
pub fn login(
&mut self,
email: EmailAddress,
password: &str,
) -> Result<Uuid, LoginError> {
let valid_credentials = self
.users
.get(&email)
.map(|hashed_password| hashed_password.verify(password))
.unwrap_or(false);
if !valid_credentials {
Err(LoginError::InvalidEmailOrPassword)
} else {
let token = Uuid::new_v4();
self.tokens.insert(token, email);
Ok(token)
}
}
pub fn logout(&mut self, token: &str) -> Result<(), LogoutError> {
let token = token
.parse::<Uuid>()
.map_err(|_| LogoutError::NotLoggedIn)?;
self.tokens.remove(&token);
Ok(())
}
pub fn authorize_user(
&self,
token: &str,
) -> Result<CurrentUser, AuthError> {
token
.parse::<Uuid>()
.map_err(|_| AuthError::NotAuthorized)
.and_then(|token| {
self.tokens
.get(&token)
.cloned()
.map(|email| CurrentUser { email, token })
.ok_or(AuthError::NotAuthorized)
})
}
}
#[derive(Debug, Error)]
pub enum CreateUserError {
#[error("The user already exists")]
UserExists,
}
#[derive(Debug, Error)]
pub enum LoginError {
#[error("Invalid email or password")]
InvalidEmailOrPassword,
}
#[derive(Debug, Error)]
pub enum LogoutError {
#[error("You are not logged in")]
NotLoggedIn,
}
#[derive(Debug, Error)]
pub enum AuthError {
#[error("You are not authorized")]
NotAuthorized,
}
pub struct Credentials {
pub email: EmailAddress,
pub password: Password,
}
#[derive(Clone, Eq, PartialEq, Hash)]
pub struct EmailAddress(String);
#[derive(Debug, Error)]
#[error("The given email address is invalid")]
pub struct InvalidEmailAddress;
impl FromStr for EmailAddress {
type Err = InvalidEmailAddress;
fn from_str(s: &str) -> Result<Self, Self::Err> {
addrparse(s)
.ok()
.and_then(|parsed| parsed.extract_single_info())
.map(|single_info| Self(single_info.addr))
.ok_or(InvalidEmailAddress)
}
}
impl EmailAddress {
pub fn into_string(self) -> String {
self.0
}
}
#[derive(Clone)]
pub struct CurrentUser {
pub email: EmailAddress,
#[allow(dead_code)] // possibly a lint regression, this is used at line 65
pub token: Uuid,
}
const MIN_PASSWORD_LEN: usize = 3;
pub struct Password(String);
impl Password {
pub fn verify(&self, password: &str) -> bool {
bcrypt::verify(password, &self.0)
}
}
#[derive(Debug, Error)]
pub enum InvalidPassword {
#[error("Password is too short (min. length is {0})")]
TooShort(usize),
}
impl TryFrom<String> for Password {
type Error = InvalidPassword;
fn try_from(p: String) -> Result<Self, Self::Error> {
if p.len() < MIN_PASSWORD_LEN {
return Err(InvalidPassword::TooShort(MIN_PASSWORD_LEN));
}
let hashed = bcrypt::hash(&p).unwrap();
Ok(Self(hashed))
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/login_with_token_csr_only/server/src/main.rs | projects/login_with_token_csr_only/server/src/main.rs | use api_boundary as json;
use axum::{
extract::State,
http::Method,
response::Json,
routing::{get, post},
Router,
};
use axum_extra::TypedHeader;
use headers::{authorization::Bearer, Authorization};
use parking_lot::RwLock;
use std::{env, net::SocketAddr, sync::Arc};
use tokio::net::TcpListener;
use tower_http::cors::{Any, CorsLayer};
mod adapters;
mod application;
use self::application::*;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
if let Err(err) = env::var("RUST_LOG") {
match err {
env::VarError::NotPresent => {
env::set_var("RUST_LOG", "debug");
}
env::VarError::NotUnicode(_) => {
return Err(anyhow::anyhow!(
"The value of 'RUST_LOG' does not contain valid unicode \
data."
));
}
}
}
env_logger::init();
let shared_state = Arc::new(RwLock::new(AppState::default()));
let cors_layer = CorsLayer::new()
.allow_methods([Method::GET, Method::POST])
.allow_origin(Any);
let app = Router::new()
.route("/login", post(login))
.route("/logout", post(logout))
.route("/users", post(create_user))
.route("/users", get(get_user_info))
.route_layer(cors_layer)
.with_state(shared_state);
let addr = "0.0.0.0:3000".parse::<SocketAddr>()?;
log::info!("Start listening on http://{addr}");
let listener = TcpListener::bind(addr).await?;
axum::serve(listener, app.into_make_service()).await?;
Ok(())
}
type Result<T> = std::result::Result<Json<T>, Error>;
/// API error
#[derive(thiserror::Error, Debug)]
#[non_exhaustive]
enum Error {
#[error(transparent)]
CreateUser(#[from] CreateUserError),
#[error(transparent)]
Login(#[from] LoginError),
#[error(transparent)]
Logout(#[from] LogoutError),
#[error(transparent)]
Auth(#[from] AuthError),
#[error(transparent)]
Credentials(#[from] adapters::CredentialParsingError),
}
async fn create_user(
State(state): State<Arc<RwLock<AppState>>>,
Json(credentials): Json<json::Credentials>,
) -> Result<()> {
let credentials = Credentials::try_from(credentials)?;
state.write().create_user(credentials)?;
Ok(Json(()))
}
async fn login(
State(state): State<Arc<RwLock<AppState>>>,
Json(credentials): Json<json::Credentials>,
) -> Result<json::ApiToken> {
let json::Credentials { email, password } = credentials;
log::debug!("{email} tries to login");
let email = email.parse().map_err(|_|
// Here we don't want to leak detailed info.
LoginError::InvalidEmailOrPassword)?;
let token = state
.write()
.login(email, &password)
.map(|s| s.to_string())?;
Ok(Json(json::ApiToken { token }))
}
async fn logout(
State(state): State<Arc<RwLock<AppState>>>,
TypedHeader(auth): TypedHeader<Authorization<Bearer>>,
) -> Result<()> {
state.write().logout(auth.token())?;
Ok(Json(()))
}
async fn get_user_info(
State(state): State<Arc<RwLock<AppState>>>,
TypedHeader(auth): TypedHeader<Authorization<Bearer>>,
) -> Result<json::UserInfo> {
let user = state.read().authorize_user(auth.token())?;
let CurrentUser { email, .. } = user;
Ok(Json(json::UserInfo {
email: email.into_string(),
}))
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/login_with_token_csr_only/client/src/lib.rs | projects/login_with_token_csr_only/client/src/lib.rs | use api_boundary::*;
use gloo_storage::{LocalStorage, Storage};
use leptos::prelude::*;
use leptos_router::*;
mod api;
mod components;
mod pages;
use self::{components::*, pages::*};
const DEFAULT_API_URL: &str = "/api";
const API_TOKEN_STORAGE_KEY: &str = "api-token";
#[component]
pub fn App() -> impl IntoView {
// -- signals -- //
let authorized_api = RwSignal::new(None::<api::AuthorizedApi>);
let user_info = RwSignal::new(None::<UserInfo>);
let logged_in = Signal::derive(move || authorized_api.get().is_some());
// -- actions -- //
let fetch_user_info = create_action(move |_| async move {
match authorized_api.get() {
Some(api) => match api.user_info().await {
Ok(info) => {
user_info.update(|i| *i = Some(info));
}
Err(err) => {
log::error!("Unable to fetch user info: {err}")
}
},
None => {
log::error!("Unable to fetch user info: not logged in")
}
}
});
let logout = create_action(move |_| async move {
match authorized_api.get() {
Some(api) => match api.logout().await {
Ok(_) => {
authorized_api.update(|a| *a = None);
user_info.update(|i| *i = None);
}
Err(err) => {
log::error!("Unable to logout: {err}")
}
},
None => {
log::error!("Unable to logout user: not logged in")
}
}
});
// -- callbacks -- //
let on_logout = move |_| {
logout.dispatch(());
};
// -- init API -- //
let unauthorized_api = api::UnauthorizedApi::new(DEFAULT_API_URL);
if let Ok(token) = LocalStorage::get(API_TOKEN_STORAGE_KEY) {
let api = api::AuthorizedApi::new(DEFAULT_API_URL, token);
authorized_api.update(|a| *a = Some(api));
fetch_user_info.dispatch(());
}
log::debug!("User is logged in: {}", logged_in.get_untracked());
// -- effects -- //
create_effect(move |_| {
log::debug!("API authorization state changed");
match authorized_api.get() {
Some(api) => {
log::debug!(
"API is now authorized: save token in LocalStorage"
);
LocalStorage::set(API_TOKEN_STORAGE_KEY, api.token())
.expect("LocalStorage::set");
}
None => {
log::debug!(
"API is no longer authorized: delete token from \
LocalStorage"
);
LocalStorage::delete(API_TOKEN_STORAGE_KEY);
}
}
});
view! {
<Router>
<NavBar logged_in on_logout/>
<main>
<Routes>
<Route
path=Page::Home.path()
view=move || {
view! { <Home user_info=user_info.into()/> }
}
/>
<Route
path=Page::Login.path()
view=move || {
view! {
<Login
api=unauthorized_api
on_success=move |api| {
log::info!("Successfully logged in");
authorized_api.update(|v| *v = Some(api));
let navigate = use_navigate();
navigate(Page::Home.path(), Default::default());
fetch_user_info.dispatch(());
}
/>
}
}
/>
<Route
path=Page::Register.path()
view=move || {
view! { <Register api=unauthorized_api/> }
}
/>
</Routes>
</main>
</Router>
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/login_with_token_csr_only/client/src/api.rs | projects/login_with_token_csr_only/client/src/api.rs | use api_boundary::*;
use gloo_net::http::{Request, RequestBuilder, Response};
use serde::de::DeserializeOwned;
use thiserror::Error;
#[derive(Clone, Copy)]
pub struct UnauthorizedApi {
url: &'static str,
}
#[derive(Clone)]
pub struct AuthorizedApi {
url: &'static str,
token: ApiToken,
}
impl UnauthorizedApi {
pub const fn new(url: &'static str) -> Self {
Self { url }
}
pub async fn register(&self, credentials: &Credentials) -> Result<()> {
let url = format!("{}/users", self.url);
let response = Request::post(&url).json(credentials)?.send().await?;
into_json(response).await
}
pub async fn login(
&self,
credentials: &Credentials,
) -> Result<AuthorizedApi> {
let url = format!("{}/login", self.url);
let response = Request::post(&url).json(credentials)?.send().await?;
let token = into_json(response).await?;
Ok(AuthorizedApi::new(self.url, token))
}
}
impl AuthorizedApi {
pub const fn new(url: &'static str, token: ApiToken) -> Self {
Self { url, token }
}
fn auth_header_value(&self) -> String {
format!("Bearer {}", self.token.token)
}
async fn send<T>(&self, req: RequestBuilder) -> Result<T>
where
T: DeserializeOwned,
{
let response = req
.header("Authorization", &self.auth_header_value())
.send()
.await?;
into_json(response).await
}
pub async fn logout(&self) -> Result<()> {
let url = format!("{}/logout", self.url);
self.send(Request::post(&url)).await
}
pub async fn user_info(&self) -> Result<UserInfo> {
let url = format!("{}/users", self.url);
self.send(Request::get(&url)).await
}
pub fn token(&self) -> &ApiToken {
&self.token
}
}
type Result<T> = std::result::Result<T, Error>;
#[derive(Debug, Error)]
pub enum Error {
#[error(transparent)]
Fetch(#[from] gloo_net::Error),
#[error("{0:?}")]
Api(api_boundary::Error),
}
impl From<api_boundary::Error> for Error {
fn from(e: api_boundary::Error) -> Self {
Self::Api(e)
}
}
async fn into_json<T>(response: Response) -> Result<T>
where
T: DeserializeOwned,
{
// ensure we've got 2xx status
if response.ok() {
Ok(response.json().await?)
} else {
Err(response.json::<api_boundary::Error>().await?.into())
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/login_with_token_csr_only/client/src/main.rs | projects/login_with_token_csr_only/client/src/main.rs | use client::*;
use leptos::prelude::*;
pub fn main() {
_ = console_log::init_with_level(log::Level::Debug);
console_error_panic_hook::set_once();
mount_to_body(|| view! { <App/> })
}
| 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.