Compare commits

..

4 Commits

Author SHA1 Message Date
Greg Johnston
95eb6b1bd9 remove unnecessary Props imports 2023-04-07 13:54:51 -04:00
Greg Johnston
e81f14a794 oops 2023-04-07 13:49:00 -04:00
Greg Johnston
0e8125abde cargo fmt 2023-04-07 13:43:32 -04:00
Greg Johnston
8bb2ee4569 feat: make __Props imports unnecessary (closes #746) 2023-04-07 13:40:19 -04:00
112 changed files with 1020 additions and 3327 deletions

View File

@@ -6,7 +6,6 @@
[![crates.io](https://img.shields.io/crates/v/leptos.svg)](https://crates.io/crates/leptos)
[![docs.rs](https://docs.rs/leptos/badge.svg)](https://docs.rs/leptos)
[![Discord](https://img.shields.io/discord/1031524867910148188?color=%237289DA&label=discord)](https://discord.gg/YdRAhS7eQB)
[![Matrix](https://img.shields.io/badge/Matrix-leptos-grey?logo=matrix&labelColor=white&logoColor=black)](https://matrix.to/#/#leptos:matrix.org)
# Leptos
@@ -66,9 +65,9 @@ Here are some resources for learning more about Leptos:
## `nightly` Note
Most of the examples assume youre using `nightly` version of Rust. For this, you can either set your toolchain globally or on per-project basis.
Most of the examples assume youre using `nightly` Rust.
To set `nightly` as a default toolchain for all projects (and add the ability to compile Rust to WebAssembly, if you havent already):
To set up your Rust toolchain using `nightly` (and add the ability to compile Rust to WebAssembly, if you havent already)
```
rustup toolchain install nightly
@@ -76,14 +75,6 @@ rustup default nightly
rustup target add wasm32-unknown-unknown
```
If you'd like to use `nightly` only in your Leptos project however, add [`rust-toolchain.toml`](https://rust-lang.github.io/rustup/overrides.html#the-toolchain-file) file with the following content:
```toml
[toolchain]
channel = "nightly"
targets = ["wasm32-unknown-unknown"]
```
If youre on `stable`, note the following:
1. You need to enable the `"stable"` flag in `Cargo.toml`: `leptos = { version = "0.2", features = ["stable"] }`

View File

@@ -10,8 +10,8 @@ fn leptos_deep_creation(b: &mut Bencher) {
create_scope(runtime, |cx| {
let signal = create_rw_signal(cx, 0);
let mut memos = Vec::<Memo<usize>>::new();
for _ in 0..1000usize {
let prev = memos.last().copied();
for i in 0..1000usize {
let prev = memos.get(i.saturating_sub(1)).copied();
if let Some(prev) = prev {
memos.push(create_memo(cx, move |_| prev.get() + 1));
} else {
@@ -34,8 +34,9 @@ fn leptos_deep_update(b: &mut Bencher) {
create_scope(runtime, |cx| {
let signal = create_rw_signal(cx, 0);
let mut memos = Vec::<Memo<usize>>::new();
for _ in 0..1000usize {
if let Some(prev) = memos.last().copied() {
for i in 0..1000usize {
let prev = memos.get(i.saturating_sub(1)).copied();
if let Some(prev) = prev {
memos.push(create_memo(cx, move |_| prev.get() + 1));
} else {
memos.push(create_memo(cx, move |_| signal.get() + 1));
@@ -241,8 +242,9 @@ fn l021_deep_creation(b: &mut Bencher) {
create_scope(runtime, |cx| {
let signal = create_rw_signal(cx, 0);
let mut memos = Vec::<Memo<usize>>::new();
for _ in 0..1000usize {
if let Some(prev) = memos.last().copied() {
for i in 0..1000usize {
let prev = memos.get(i.saturating_sub(1)).copied();
if let Some(prev) = prev {
memos.push(create_memo(cx, move |_| prev.get() + 1));
} else {
memos.push(create_memo(cx, move |_| signal.get() + 1));
@@ -264,8 +266,9 @@ fn l021_deep_update(b: &mut Bencher) {
create_scope(runtime, |cx| {
let signal = create_rw_signal(cx, 0);
let mut memos = Vec::<Memo<usize>>::new();
for _ in 0..1000usize {
if let Some(prev) = memos.last().copied() {
for i in 0..1000usize {
let prev = memos.get(i.saturating_sub(1)).copied();
if let Some(prev) = prev {
memos.push(create_memo(cx, move |_| prev.get() + 1));
} else {
memos.push(create_memo(cx, move |_| signal.get() + 1));
@@ -441,8 +444,9 @@ fn sycamore_deep_creation(b: &mut Bencher) {
let d = create_scope(|cx| {
let signal = create_signal(cx, 0);
let mut memos = Vec::<&ReadSignal<usize>>::new();
for _ in 0..1000usize {
if let Some(prev) = memos.last().copied() {
for i in 0..1000usize {
let prev = memos.get(i.saturating_sub(1)).copied();
if let Some(prev) = prev {
memos.push(create_memo(cx, move || *prev.get() + 1));
} else {
memos.push(create_memo(cx, move || *signal.get() + 1));
@@ -461,8 +465,9 @@ fn sycamore_deep_update(b: &mut Bencher) {
let d = create_scope(|cx| {
let signal = create_signal(cx, 0);
let mut memos = Vec::<&ReadSignal<usize>>::new();
for _ in 0..1000usize {
if let Some(prev) = memos.last().copied() {
for i in 0..1000usize {
let prev = memos.get(i.saturating_sub(1)).copied();
if let Some(prev) = prev {
memos.push(create_memo(cx, move || *prev.get() + 1));
} else {
memos.push(create_memo(cx, move || *signal.get() + 1));

View File

@@ -27,12 +27,11 @@
- [Params and Queries](./router/18_params_and_queries.md)
- [`<A/>`](./router/19_a.md)
- [`<Form/>`](./router/20_form.md)
- [Interlude: Styling](./interlude_styling.md)
- [Interlude: Styling — CSS, Tailwind, Style.rs, and more]()
- [Metadata]()
- [Server Side Rendering](./ssr/README.md)
- [SSR]()
- [Models of SSR]()
- [`cargo-leptos`]()
- [The Life of a Page Load](./ssr/21_life_cycle.md)
- [Async Rendering and SSR “Modes”](./ssr/22_ssr_modes.md)
- [Hydration Footguns]()
- [Request/Response]()
- [Extractors]()

View File

@@ -26,11 +26,11 @@ let b = create_resource(cx, count2, |count| async move { load_b(count).await });
view! { cx,
<h1>"My Data"</h1>
{move || match (a.read(cx), b.read(cx)) {
_ => view! { cx, <p>"Loading..."</p> }.into_view(cx),
(Some(a), Some(b)) => view! { cx,
<ShowA a/>
<ShowA b/>
}.into_view(cx),
_ => view! { cx, <p>"Loading..."</p> }.into_view(cx)
}.into_view(cx)
}}
}
```

View File

@@ -1,112 +0,0 @@
# Interlude: Styling
Anyone creating a website or application soon runs into the question of styling. For a small app, a single CSS file is probably plenty to style your user interface. But as an application grows, many developers find that plain CSS becomes increasingly hard to manage.
Some frontend frameworks (like Angular, Vue, and Svelte) provide built-in ways to scope your CSS to particular components, making it easier to manage styles across a whole application without styles meant to modify one small component having a global effect. Other frameworks (like React or Solid) dont provide built-in CSS scoping, but rely on libraries in the ecosystem to do it for them. Leptos is in this latter camp: the framework itself has no opinions about CSS at all, but provides a few tools and primitives that allow others to build styling libraries.
Here are a few different approaches to styling your Leptos app, other than plain CSS.
## TailwindCSS: Utility-first CSS
[TailwindCSS](https://tailwindcss.com/) is a popular utility-first CSS library. It allows you to style your application by using inline utility classes, with a custom CLI tool that scans your files for Tailwind class names and bundles the necessary CSS.
This allows you to write components like this:
```rust
#[component]
fn Home(cx: Scope) -> impl IntoView {
let (count, set_count) = create_signal(cx, 0);
view! { cx,
<main class="my-0 mx-auto max-w-3xl text-center">
<h2 class="p-6 text-4xl">"Welcome to Leptos with Tailwind"</h2>
<p class="px-10 pb-10 text-left">"Tailwind will scan your Rust files for Tailwind class names and compile them into a CSS file."</p>
<button
class="bg-sky-600 hover:bg-sky-700 px-5 py-3 text-white rounded-lg"
on:click=move |_| set_count.update(|count| *count += 1)
>
{move || if count() == 0 {
"Click me!".to_string()
} else {
count().to_string()
}}
</button>
</main>
}
}
```
It can be a little complicated to set up the Tailwind integration at first, but you can check out our two examples of how to use Tailwind with a [client-side-rendered `trunk` application](https://github.com/leptos-rs/leptos/tree/main/examples/tailwind_csr_trunk) or with a [server-rendered `cargo-leptos` application](https://github.com/leptos-rs/leptos/tree/main/examples/tailwind). `cargo-leptos` also has some [built-in Tailwind support](https://github.com/leptos-rs/cargo-leptos#site-parameters) that you can use as an alternative to Tailwinds CLI.
## Stylers: Compile-time CSS Extraction
[Stylers](https://github.com/abishekatp/stylers) is a compile-time scoped CSS library that lets you declare scoped CSS in the body of your component. Stylers will extract this CSS at compile time into CSS files that you can then import into your app, which means that it doesnt add anything to the WASM binary size of your application.
This allows you to write components like this:
```rust
use stylers::style;
#[component]
pub fn App(cx: Scope) -> impl IntoView {
let styler_class = style! { "App",
#two{
color: blue;
}
div.one{
color: red;
content: raw_str(r#"\hello"#);
font: "1.3em/1.2" Arial, Helvetica, sans-serif;
}
div {
border: 1px solid black;
margin: 25px 50px 75px 100px;
background-color: lightblue;
}
h2 {
color: purple;
}
@media only screen and (max-width: 1000px) {
h3 {
background-color: lightblue;
color: blue
}
}
};
view! { cx, class = styler_class,
<div class="one">
<h1 id="two">"Hello"</h1>
<h2>"World"</h2>
<h2>"and"</h2>
<h3>"friends!"</h3>
</div>
}
}
```
## Styled: Runtime CSS Scoping
[Styled](https://github.com/eboody/styled) is a runtime scoped CSS library that integrates well with Leptos. It lets you declare scoped CSS in the body of your component function, and then applies those styles at runtime.
```rust
use styled::style;
#[component]
pub fn MyComponent(cx: Scope) -> impl IntoView {
let styles = style!(
div {
background-color: red;
color: white;
}
);
styled::view! { cx, styles,
<div>"This text should be red with white text."</div>
}
}
```
## Contributions Welcome
Leptos no opinions on how you style your website or app, but were very happy to provide support to any tools youre trying to create to make it easier. If youre working on a CSS or styling approach that youd like to add to this list, please let us know!

View File

@@ -1,43 +0,0 @@
# The Life of a Page Load
Before we get into the weeds it might be helpful to have a higher-level overview. What exactly happens between the moment you type in the URL of a server-rendered Leptos app, and the moment you click a button and a counter increases?
Im assuming some basic knowledge of how the Internet works here, and wont get into the weeds about HTTP or whatever. Instead, Ill try to show how different parts of the Leptos APIs map onto each part of the process.
This description also starts from the premise that your app is being compiled for two separate targets:
1. A server version, often running on Actix or Axum, compiled with the Leptos `ssr` feature
2. A browser version, compiled to WebAssembly (WASM) with the Leptos `hydrate` feature
The [`cargo-leptos`](https://github.com/leptos-rs/cargo-leptos) build tool exists to coordinate the process of compiling your app for these two different targets.
## On the Server
- Your browser makes a `GET` request for that URL to your server. At this point, the browser knows almost nothing about the page thats going to be rendered. (The question “How does the browser know where to ask for the page?” is an interesting one, but out of the scope of this tutorial!)
- The server receives that request, and checks whether it has a way to handle a `GET` request at that path. This is what the `.leptos_routes()` methods in [`leptos_axum`](https://docs.rs/leptos_axum/0.2.5/leptos_axum/trait.LeptosRoutes.html) and [`leptos_actix`](https://docs.rs/leptos_actix/0.2.5/leptos_actix/trait.LeptosRoutes.html) are for. When the server starts up, these methods walk over the routing structure you provide in `<Routes/>`, generating a list of all possible routes your app can handle and telling the servers router “for each of these routes, if you get a request... hand it off to Leptos.”
- The server sees that this route can be handled by Leptos. So it renders your root component (often called something like `<App/>`), providing it with the URL thats being requested and some other data like the HTTP headers and request metadata.
- Your application runs once on the server, building up an HTML version of the component tree that will be rendered at that route. (Theres more to be said here about resources and `<Suspense/>` in the next chapter.)
- The server returns this HTML page, also injecting information on how to load the version of your app that has been compiled to WASM so that it can run in the browser.
> The HTML page thats returned is essentially your app, “dehydrated” or “freeze-dried”: it is HTML without any of the reactivity or event listeners youve added. The browser will “rehydrate” this HTML page by adding the reactive system and attaching event listeners to that server-rendered HTML. Hence the two feature flags that apply to the two halves of this process: `ssr` on the server for “server-side rendering”, and `hydrate` in the browser for that process of rehydration.
## In the Browser
- The browser receives this HTML page from the server. It immediately goes back to the server to begin loading the JS and WASM necessary to run the interactive, client side version of the app.
- In the meantime, it renders the HTML version.
- When the WASM version has reloaded, it does the same route-matching process that the server did. Because the `<Routes/>` component is identical on the server and in the client, the browser version will read the URL and render the same page that was already returned by the server.
- During this initial “hydration” phase, the WASM version of your app doesnt re-create the DOM nodes that make up your application. Instead, it walks over the existing HTML tree, “picking up” existing elements and adding the necessary interactivity.
> Note that there are some trade-offs here. Before this hydration process is complete, the page will _appear_ interactive but wont actually respond to interactions. For example, if you have a counter button and click it before WASM has loaded, the count will not increment, because the necessary event listeners and reactivity have not been added yet. Well look at some ways to build in “graceful degradation” in future chapters.
## Client-Side Navigation
The next step is very important. Imagine that the user now clicks a link to navigate to another page in your application.
The browser will _not_ make another round trip to the server, reloading the full page as it would for navigating between plain HTML pages or an application that uses server rendering (for example with PHP) but without a client-side half.
Instead, the WASM version of your app will load the new page, right there in the browser, without requesting another page from the server. Essentially, your app upgrades itself from a server-loaded “multi-page app” into a browser-rendered “single-page app.” This yields the best of both worlds: a fast initial load time due to the server-rendered HTML, and fast secondary navigations because of the client-side routing.
Some of what will be described in the following chapters—like the interactions between server functions, resources, and `<Suspense/>`—may seem overly complicated. You might find yourself asking, “If my page is being rendered to HTML on the server, why cant I just `.await` this on the server? If I can just call library X in a server function, why cant I call it in my component?” The reason is pretty simple: to enable the upgrade from server rendering to client rendering, everything in your application must be able to run either on the server or in the browser.
This is not the only way to create a website or web framework, of course. But its the most common way, and we happen to think its quite a good way, to create the smoothest possible experience for your users.

View File

@@ -1,122 +0,0 @@
# Async Rendering and SSR “Modes”
Server-rendering a page that uses only synchronous data is pretty simple: You just walk down the component tree, rendering each element to an HTML string. But this is a pretty big caveat: it doesnt answer the question of what we should do with pages that includes asynchronous data, i.e., the sort of stuff that would be rendered under a `<Suspense/>` node on the client.
When a page loads async data that it needs to render, what should we do? Should we wait for all the async data to load, and then render everything at once? (Lets call this “async” rendering) Should we go all the way in the opposite direction, just sending the HTML we have immediately down to the client and letting the client load the resources and fill them in? (Lets call this “synchronous” rendering) Or is there some middle-ground solution that somehow beats them both? (Hint: There is.)
If youve ever listened to streaming music or watched a video online, Im sure you realize that HTTP supports streaming, allowing a single connection to send chunks of data one after another without waiting for the full content to load. You may not realize that browsers are also really good at rendering partial HTML pages. Taken together, this means that you can actually enhance your users experience by **streaming HTML**: and this is something that Leptos supports out of the box, with no configuration at all. And theres actually more than one way to stream HTML: you can stream the chunks of HTML that make up your page in order, like frames of a video, or you can stream them... well, out of order.
Let me say a little more about what I mean.
Leptos supports all four different of these different ways to render HTML that includes asynchronous data.
## Synchronous Rendering
1. **Synchronous**: Serve an HTML shell that includes `fallback` for any `<Suspense/>`. Load data on the client using `create_local_resource`, replacing `fallback` once resources are 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.
- No ability to include data from async resources in the `<title>` or other `<meta>` tags, hurting SEO and things like social media link previews.
If youre using server-side rendering, the synchronous mode is almost never what you actually want, from a performance perspective. This is because it misses out on an important optimization. If youre loading async resources during server rendering, you can actually begin loading the data on the server. Rather than waiting for the client to receive the HTML response, then loading its JS + WASM, _then_ realize it needs the resources and begin loading them, server rendering can actually begin loading the resources when the client first makes the response. In this sense, during server rendering an async resource is like a `Future` that begins loading on the server and resolves on the client. As long as the resources are actually serializable, this will always lead to a faster total load time.
> This is why [`create_resource`](https://docs.rs/leptos/latest/leptos/fn.create_resource.html) requires resources data to be serializable by default, and why you need to explicitly use [`create_local_resource`](https://docs.rs/leptos/latest/leptos/fn.create_local_resource.html) for any async data that is not serializable and should therefore only be loaded in the browser itself. Creating a local resource when you could create a serializable resource is always a deoptimization.
## Async Rendering
<video controls>
<source src="https://github.com/leptos-rs/leptos/blob/main/docs/video/async.mov?raw=true" type="video/mp4">
</video>
2. **`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. The page is totally blank until everything is loaded.
## In-Order Streaming
<video controls>
<source src="https://github.com/leptos-rs/leptos/blob/main/docs/video/in-order.mov?raw=true" type="video/mp4">
</video>
3. **In-order streaming**: Walk through the component tree, rendering HTML until you hit a `<Suspense/>`. Send down all the HTML youve got so far as a chunk in the stream, wait for all the resources accessed under the `<Suspense/>` to load, then render it to HTML and keep walking until you hit another `<Suspense/>` or the end of the page.
- _Pros_: Rather than a blank screen, shows at least _something_ before the data are ready.
- _Cons_
- Loads the shell more slowly than synchronous rendering (or out-of-order streaming) because it needs to pause at every `<Suspense/>`.
- Unable to show fallback states for `<Suspense/>`.
- Cant begin hydration until the entire page has loaded, so earlier pieces of the page will not be interactive until the suspended chunks have loaded.
## Out-of-Order Streaming
<video controls>
<source src="https://github.com/leptos-rs/leptos/blob/main/docs/video/out-of-order.mov?raw=true" type="video/mp4">
</video>
4. **Out-of-order streaming**: Like synchronous rendering, serve an HTML shell that includes `fallback` for any `<Suspense/>`. But load data on the **server**, streaming it down to the client as it resolves, and streaming down HTML for `<Suspense/>` nodes, which is swapped in to replace the fallback.
- _Pros_: Combines the best of **synchronous** and **`async`**.
- Fast initial response/TTFB because it immediately sends the whole synchronous shell
- Fast total time because resources begin loading on the server.
- Able to show the fallback loading state and dynamically replace it, instead of showing blank sections for un-loaded data.
- _Cons_: Requires JavaScript to be enabled for suspended fragments to appear in correct order. (This small chunk of JS streamed down in a `<script>` tag alongside the `<template>` tag that contains the rendered `<Suspense/>` fragment, so it does not need to load any additional JS files.)
## Using SSR Modes
Because it offers the best blend of performance characteristics, Leptos defaults to out-of-order streaming. But its really simple to opt into these different modes. You do it by adding an `ssr` property onto one or more of your `<Route/>` components, like in the [`ssr_modes` example](https://github.com/leptos-rs/leptos/blob/main/examples/ssr_modes/src/app.rs).
```rust
<Routes>
// Well load the home page with out-of-order streaming and <Suspense/>
<Route path="" view=|cx| view! { cx, <HomePage/> }/>
// We'll load the posts with async rendering, so they can set
// the title and metadata *after* loading the data
<Route
path="/post/:id"
view=|cx| view! { cx, <Post/> }
ssr=SsrMode::Async
/>
</Routes>
```
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 in-order, and then out-of-order. (This probably makes sense if you think about it for a few minutes.)
## Blocking Resources
Any Leptos versions later than `0.2.5` (i.e., git main and `0.3.x` or later) introduce a new resource primitive with `create_blocking_resource`. A blocking resource still loads asynchronously like any other `async`/`.await` in Rust; it doesnt block a server thread or anything. Instead, reading from a blocking resource under a `<Suspense/>` blocks the HTML _stream_ from returning anything, including its initial synchronous shell, until that `<Suspense/>` has resolved.
Now from a performance perspective, this is not ideal. None of the synchronous shell for your page will load until that resource is ready. However, rendering nothing means that you can do things like set the `<title>` or `<meta>` tags in your `<head>` in actual HTML. This sounds a lot like `async` rendering, but theres one big difference: if you have multiple `<Suspense/>` sections, you can block on _one_ of them but still render a placeholder and then stream in the other.
For example, think about a blog post. For SEO and for social sharing, I definitely want my blog posts title and metadata in the initial HTML `<head>`. But I really dont care whether comments have loaded yet or not; Id like to load those as lazily as possible.
With blocking resources, I can do something like this:
```rust
#[component]
pub fn BlogPost(cx: Scope) -> impl IntoView {
let post_data = create_blocking_resource(cx, /* load blog post */);
let comment_data = create_resource(cx, /* load blog post */);
view! { cx,
<Suspense fallback=|| ()>
{move || {
post_data.with(cx, |data| {
view! { cx,
<Title text=data.title/>
<Meta name="description" content=data.excerpt/>
<article>
/* render the post content */
</article>
}
})
}}
</Suspense>
<Suspense fallback=|| "Loading comments...">
/* render comment data here */
</Suspense>
}
}
```
The first `<Suspense/>`, with the body of the blog post, will block my HTML stream, because it reads from a blocking resource. The second `<Suspense/>`, with the comments, will not block the stream. Blocking resources gave me exactly the power and granularity I needed to optimize my page for SEO and user experience.

View File

@@ -1,21 +0,0 @@
# Server Side Rendering
So far, everything weve written has been rendered almost entirely in the browser. When we create an app using Trunk, its served using a local development server. If you build it for production and deploy it, its served by whatever server or CDN youre using. In either case, whats served is an HTML page with
1. the URL of your Leptos app, which has been compiled to WebAssembly (WASM)
2. the URL of the JavaScript used to initialized this WASM blob
3. an empty `<body>` element
When the JS and WASM have loaded, Leptos will render your app into the `<body>`. This means that nothing appears on the screen until JS/WASM have loaded and run. This has some drawbacks:
1. It increases load time, as your users screen is blank until additional resources have been downloaded.
2. Its bad for SEO, as load times are longer and the HTML you serve has no meaningful content.
3. Its broken for users for whom JS/WASM dont load for some reason (e.g., theyre on a train and just went into a tunnel before WASM finished loading; theyre using an older device that doesnt support WASM; they have JavaScript or WASM turned off for some reason; etc.)
These downsides apply across the web ecosystem, but especially to WASM apps.
So what do you do if you want to return more than just an empty `<body>` tag? Use “server-side rendering.”
Whole books could be (and probably have been) written about this topic, but at its core, its really simple: rather than returning an empty `<body>` tag, return an initial HTML page that reflects the actual starting state of your app or site, so that while JS/WASM are loading, and until they load, the user can access the plain HTML version.
The rest of this section will cover this topic in some detail!

View File

@@ -15,7 +15,7 @@ covered some of this in the material on [components and props](./03_components.m
Basically if you want the parent to communicate to the child, you can pass a
[`ReadSignal`](https://docs.rs/leptos/latest/leptos/struct.ReadSignal.html), a
[`Signal`](https://docs.rs/leptos/latest/leptos/struct.Signal.html), or even a
[`MaybeSignal`](https://docs.rs/leptos/latest/leptos/enum.MaybeSignal.html) as a prop.
[`MaybeSignal`](https://docs.rs/leptos/latest/leptos/struct.MaybeSignal.html) as a prop.
But what about the other direction? How can a child send notifications about events
or state changes back up to the parent?

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -3,10 +3,6 @@ name = "counter"
version = "0.1.0"
edition = "2021"
[profile.release]
codegen-units = 1
lto = true
[dependencies]
leptos = { path = "../../leptos" }
console_log = "1"
@@ -16,4 +12,5 @@ console_error_panic_hook = "0.1.7"
[dev-dependencies]
wasm-bindgen = "0.2"
wasm-bindgen-test = "0.3.0"
web-sys = "0.3"
web-sys ="0.3"

View File

@@ -6,10 +6,6 @@ edition = "2021"
[lib]
crate-type = ["cdylib", "rlib"]
[profile.release]
codegen-units = 1
lto = true
[dependencies]
actix-files = { version = "0.6", optional = true }
actix-web = { version = "4", optional = true, features = ["macros"] }

View File

@@ -3,10 +3,6 @@ name = "counter_without_macros"
version = "0.1.0"
edition = "2021"
[profile.release]
codegen-units = 1
lto = true
[dependencies]
leptos = { path = "../../leptos", features = ["stable"] }
console_log = "1"
@@ -14,10 +10,4 @@ log = "0.4"
console_error_panic_hook = "0.1.7"
[dev-dependencies]
wasm-bindgen = "0.2.84"
wasm-bindgen-test = "0.3.34"
pretty_assertions = "1.3.0"
[dev-dependencies.web-sys]
features = ["HtmlElement", "XPathResult"]
version = "0.3.61"
wasm-bindgen-test = "0.3.0"

View File

@@ -1,10 +1,3 @@
[env]
CARGO_MAKE_WASM_TEST_ARGS = "--headless --chrome"
[tasks.post-test]
command = "cargo"
args = ["make", "wasm-pack-test"]
[tasks.build]
command = "cargo"
args = ["+stable", "build-all-features"]

View File

@@ -3,5 +3,3 @@
This example is the same like the `counter` but it's written without using macros and can be build with stable Rust.
To run it, just issue the `trunk serve --open` command in the example root. This will build the app, run it, and open a new browser to serve it.
Issue the `cargo make test-flow` command to run unit and wasm tests.

View File

@@ -0,0 +1,58 @@
use wasm_bindgen_test::*;
wasm_bindgen_test_configure!(run_in_browser);
use counter_without_macros as counter;
use leptos::*;
use web_sys::HtmlElement;
#[wasm_bindgen_test]
fn inc() {
mount_to_body(|cx| {
counter::view(
cx,
counter::Props {
initial_value: 0,
step: 1,
},
)
});
let document = leptos::document();
let div = document.query_selector("div").unwrap().unwrap();
let clear = div
.first_child()
.unwrap()
.dyn_into::<HtmlElement>()
.unwrap();
let dec = clear
.next_sibling()
.unwrap()
.dyn_into::<HtmlElement>()
.unwrap();
let text = dec
.next_sibling()
.unwrap()
.dyn_into::<HtmlElement>()
.unwrap();
let inc = text
.next_sibling()
.unwrap()
.dyn_into::<HtmlElement>()
.unwrap();
inc.click();
inc.click();
assert_eq!(text.text_content(), Some("Value: 2!".to_string()));
dec.click();
dec.click();
dec.click();
dec.click();
assert_eq!(text.text_content(), Some("Value: -2!".to_string()));
clear.click();
assert_eq!(text.text_content(), Some("Value: 0!".to_string()));
}

View File

@@ -1,86 +0,0 @@
use counter_without_macros::counter;
use leptos::*;
use pretty_assertions::assert_eq;
use wasm_bindgen::JsCast;
use wasm_bindgen_test::*;
use web_sys::HtmlElement;
wasm_bindgen_test_configure!(run_in_browser);
#[wasm_bindgen_test]
fn should_increment_counter() {
open_counter();
click_increment();
click_increment();
assert_eq!(see_text(), Some("Value: 2!".to_string()));
}
#[wasm_bindgen_test]
fn should_decrement_counter() {
open_counter();
click_decrement();
click_decrement();
assert_eq!(see_text(), Some("Value: -2!".to_string()));
}
#[wasm_bindgen_test]
fn should_clear_counter() {
open_counter();
click_increment();
click_increment();
click_clear();
assert_eq!(see_text(), Some("Value: 0!".to_string()));
}
fn open_counter() {
remove_existing_counter();
mount_to_body(move |cx| counter(cx, 0, 1));
}
fn remove_existing_counter() {
if let Some(counter) =
leptos::document().query_selector("body div").unwrap()
{
counter.remove();
}
}
fn click_clear() {
click_text("Clear");
}
fn click_decrement() {
click_text("-1");
}
fn click_increment() {
click_text("+1");
}
fn click_text(text: &str) {
find_by_text(text).click();
}
fn see_text() -> Option<String> {
find_by_text("Value: ").text_content()
}
fn find_by_text(text: &str) -> HtmlElement {
let xpath = format!("//*[text()='{}']", text);
let document = leptos::document();
document
.evaluate(&xpath, &document)
.unwrap()
.iterate_next()
.unwrap()
.unwrap()
.dyn_into::<HtmlElement>()
.unwrap()
}

View File

@@ -3,10 +3,6 @@ name = "error_boundary"
version = "0.1.0"
edition = "2021"
[profile.release]
codegen-units = 1
lto = true
[dependencies]
leptos = { path = "../../leptos" }
console_log = "1"

View File

@@ -28,6 +28,8 @@ thiserror = "1.0.38"
wasm-bindgen = "0.2"
[features]
default = ["csr"]
csr = ["leptos/csr", "leptos_meta/csr", "leptos_router/csr"]
hydrate = ["leptos/hydrate", "leptos_meta/hydrate", "leptos_router/hydrate"]
ssr = [
"dep:axum",
@@ -42,7 +44,7 @@ ssr = [
[package.metadata.cargo-all-features]
denylist = ["axum", "tower", "tower-http", "tokio", "leptos_axum"]
skip_feature_sets = [["ssr", "hydrate"]]
skip_feature_sets = [["csr", "ssr"], ["csr", "hydrate"], ["ssr", "hydrate"]]
[package.metadata.leptos]
# The name used by wasm-bindgen/cargo-leptos for the JS/WASM bundle. Defaults to the crate name

View File

@@ -3,18 +3,15 @@ name = "fetch"
version = "0.1.0"
edition = "2021"
[profile.release]
codegen-units = 1
lto = true
[dependencies]
anyhow = "1.0.58"
leptos = { path = "../../leptos" }
reqwasm = "0.5"
reqwasm = "0.5.0"
serde = { version = "1", features = ["derive"] }
log = "0.4"
console_log = "1"
console_error_panic_hook = "0.1"
thiserror = "1"
console_error_panic_hook = "0.1.7"
[dev-dependencies]
wasm-bindgen-test = "0.3"
wasm-bindgen-test = "0.3.0"

View File

@@ -1,50 +1,38 @@
use anyhow::Result;
use leptos::*;
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 FetchError {
#[error("Please request more than zero cats.")]
NonZeroCats,
#[error("Error loading data from serving.")]
Request,
#[error("Error deserializaing cat data from request.")]
Json
}
async fn fetch_cats(count: u32) -> Result<Vec<String>, FetchError> {
async fn fetch_cats(count: u32) -> Result<Vec<String>> {
if count > 0 {
// make the request
let res = reqwasm::http::Request::get(&format!(
"https://api.thecatapi.com/v1/images/search?limit={count}",
))
.send()
.await
.map_err(|_| FetchError::Request)?
.await?
// convert it to JSON
.json::<Vec<Cat>>()
.await
.map_err(|_| FetchError::Json)?
.await?
// extract the URL field for each cat
.into_iter()
.map(|cat| cat.url)
.collect::<Vec<_>>();
Ok(res)
} else {
Err(FetchError::NonZeroCats)
Ok(vec![])
}
}
pub fn fetch_example(cx: Scope) -> impl IntoView {
let (cat_count, set_cat_count) = create_signal::<u32>(cx, 0);
let (cat_count, set_cat_count) = create_signal::<u32>(cx, 1);
// we use local_resource here because
// 1) our error type isn't serializable/deserializable
// 1) anyhow::Result isn't serializable/deserializable
// 2) we're not doing server-side rendering in this example anyway
// (during SSR, create_resource will begin loading on the server and resolve on the client)
let cats = create_local_resource(cx, cat_count, fetch_cats);
@@ -54,7 +42,7 @@ pub fn fetch_example(cx: Scope) -> impl IntoView {
errors.with(|errors| {
errors
.iter()
.map(|(_, e)| view! { cx, <li>{e.to_string()}</li> })
.map(|(_, e)| view! { cx, <li>{e.to_string()}</li>})
.collect::<Vec<_>>()
})
};
@@ -72,12 +60,11 @@ pub fn fetch_example(cx: Scope) -> impl IntoView {
// and by using the ErrorBoundary fallback to catch Err(_)
// so we'll just implement our happy path and let the framework handle the rest
let cats_view = move || {
cats.read(cx).map(|data| {
data.map(|data| {
data.iter()
.map(|s| view! { cx, <span>{s}</span> })
.collect::<Vec<_>>()
})
cats.with(cx, |data| {
data.iter()
.flatten()
.map(|cat| view! { cx, <img src={cat}/> })
.collect::<Vec<_>>()
})
};
@@ -85,9 +72,8 @@ pub fn fetch_example(cx: Scope) -> impl IntoView {
<div>
<label>
"How many cats would you like?"
<input
type="number"
prop:value=move || cat_count.get().to_string()
<input type="number"
prop:value={move || cat_count.get().to_string()}
on:input=move |ev| {
let val = event_target_value(&ev).parse::<u32>().unwrap_or(0);
set_cat_count(val);
@@ -95,9 +81,7 @@ pub fn fetch_example(cx: Scope) -> impl IntoView {
/>
</label>
<ErrorBoundary fallback>
<Transition fallback=move || {
view! { cx, <div>"Loading (Suspense Fallback)..."</div> }
}>
<Transition fallback=move || view! { cx, <div>"Loading (Suspense Fallback)..."</div>}>
{cats_view}
</Transition>
</ErrorBoundary>

View File

@@ -6,10 +6,6 @@ edition = "2021"
[lib]
crate-type = ["cdylib", "rlib"]
[profile.release]
codegen-units = 1
lto = true
[dependencies]
actix-files = { version = "0.6", optional = true }
actix-web = { version = "4", optional = true, features = ["macros"] }

View File

@@ -6,10 +6,6 @@ edition = "2021"
[lib]
crate-type = ["cdylib", "rlib"]
[profile.release]
codegen-units = 1
lto = true
[dependencies]
console_log = "1.0.0"
console_error_panic_hook = "0.1.7"

View File

@@ -1,10 +1,6 @@
[workspace]
members = ["client", "api-boundary", "server"]
[profile.release]
codegen-units = 1
lto = true
[patch.crates-io]
leptos = { path = "../../leptos" }
leptos_router = { path = "../../router" }

View File

@@ -3,10 +3,6 @@ name = "parent-child"
version = "0.1.0"
edition = "2021"
[profile.release]
codegen-units = 1
lto = true
[dependencies]
leptos = { path = "../../leptos" }
console_log = "1"

View File

@@ -3,10 +3,6 @@ name = "router"
version = "0.1.0"
edition = "2021"
[profile.release]
codegen-units = 1
lto = true
[dependencies]
console_log = "1"
log = "0.4"

View File

@@ -3,7 +3,17 @@
<head>
<link data-trunk rel="rust" data-wasm-opt="z"/>
<link data-trunk rel="icon" type="image/ico" href="/public/favicon.ico"/>
<link data-trunk rel="css" href="style.css"/>
<style>
a[aria-current] {
font-weight: bold;
}
.contact, .contact-list {
border: 1px solid #c0c0c0;
border-radius: 3px;
padding: 1rem;
}
</style>
</head>
<body></body>
</html>
</html>

View File

@@ -27,12 +27,7 @@ pub fn RouterExample(cx: Scope) -> impl IntoView {
<A href="redirect-home">"Redirect to Home"</A>
</nav>
<main>
<AnimatedRoutes
outro="slideOut"
intro="slideIn"
outro_back="slideOutBack"
intro_back="slideInBack"
>
<Routes>
<ContactRoutes/>
<Route
path="about"
@@ -46,7 +41,7 @@ pub fn RouterExample(cx: Scope) -> impl IntoView {
path="redirect-home"
view=move |cx| view! { cx, <Redirect path="/"/> }
/>
</AnimatedRoutes>
</Routes>
</main>
</Router>
}
@@ -107,11 +102,7 @@ pub fn ContactList(cx: Scope) -> impl IntoView {
<Suspense fallback=move || view! { cx, <p>"Loading contacts..."</p> }>
{move || view! { cx, <ul>{contacts}</ul>}}
</Suspense>
<AnimatedOutlet
class="outlet"
outro="fadeOut"
intro="fadeIn"
/>
<Outlet/>
</div>
}
}

View File

@@ -1,95 +0,0 @@
a[aria-current] {
font-weight: bold;
}
.outlet {
border: 1px dotted grey;
}
.contact, .contact-list {
border: 1px solid #c0c0c0;
border-radius: 3px;
padding: 1rem;
}
.fadeIn {
animation: 0.5s fadeIn forwards;
}
.fadeOut {
animation: 0.5s fadeOut forwards;
}
@keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
@keyframes fadeOut {
from {
opacity: 1;
}
to {
opacity: 0;
}
}
.slideIn {
animation: 0.125s slideIn forwards;
}
.slideOut {
animation: 0.125s slideOut forwards;
}
@keyframes slideIn {
from {
transform: translate(100vw, 0);
}
to {
transform: translate(0px, 0px);
}
}
@keyframes slideOut {
from {
transform: translate(0px, 0px);
}
to {
transform: translate(-100vw, 0);
}
}
.slideInBack {
animation: 0.125s slideInBack forwards;
}
.slideOutBack {
animation: 0.125s slideOutBack forwards;
}
@keyframes slideInBack {
from {
transform: translate(-100vw, 0);
}
to {
transform: translate(0px, 0px);
}
}
@keyframes slideOutBack {
from {
transform: translate(0px, 0px);
}
to {
transform: translate(100vw, 0);
}
}

View File

@@ -43,6 +43,8 @@ bcrypt = { version = "0.14", optional = true }
async-trait = { version = "0.1.64", optional = true }
[features]
default = ["csr"]
csr = ["leptos/csr", "leptos_meta/csr", "leptos_router/csr"]
hydrate = ["leptos/hydrate", "leptos_meta/hydrate", "leptos_router/hydrate"]
ssr = [
"dep:axum",
@@ -63,7 +65,7 @@ ssr = [
[package.metadata.cargo-all-features]
denylist = ["axum", "tower", "tower-http", "tokio", "sqlx", "leptos_axum"]
skip_feature_sets = [["ssr", "hydrate"]]
skip_feature_sets = [["csr", "ssr"], ["csr", "hydrate"], ["ssr", "hydrate"]]
[package.metadata.leptos]
# The name used by wasm-bindgen/cargo-leptos for the JS/WASM bundle. Defaults to the crate name

View File

@@ -1,15 +1,12 @@
{
"nodes": {
"flake-utils": {
"inputs": {
"systems": "systems"
},
"locked": {
"lastModified": 1681202837,
"narHash": "sha256-H+Rh19JDwRtpVPAWp64F+rlEtxUWBAQW28eAi3SRSzg=",
"lastModified": 1676283394,
"narHash": "sha256-XX2f9c3iySLCw54rJ/CZs+ZK6IQy7GXNY4nSOyu2QG4=",
"owner": "numtide",
"repo": "flake-utils",
"rev": "cfacdce06f30d2b68473a46042957675eebb3401",
"rev": "3db36a8b464d0c4532ba1c7dda728f4576d6d073",
"type": "github"
},
"original": {
@@ -19,15 +16,12 @@
}
},
"flake-utils_2": {
"inputs": {
"systems": "systems_2"
},
"locked": {
"lastModified": 1681202837,
"narHash": "sha256-H+Rh19JDwRtpVPAWp64F+rlEtxUWBAQW28eAi3SRSzg=",
"lastModified": 1659877975,
"narHash": "sha256-zllb8aq3YO3h8B/U0/J1WBgAL8EX5yWf5pMj3G0NAmc=",
"owner": "numtide",
"repo": "flake-utils",
"rev": "cfacdce06f30d2b68473a46042957675eebb3401",
"rev": "c0e246b9b83f637f4681389ecabcb2681b4f3af0",
"type": "github"
},
"original": {
@@ -67,11 +61,11 @@
]
},
"locked": {
"lastModified": 1681525152,
"narHash": "sha256-KzI+ILcmU03iFWtB+ysPqtNmp8TP8v1BBReTuPP8MJY=",
"lastModified": 1677292251,
"narHash": "sha256-D+6q5Z2MQn3UFJtqsM5/AvVHi3NXKZTIMZt1JGq/spA=",
"owner": "oxalica",
"repo": "rust-overlay",
"rev": "b6f8d87208336d7cb85003b2e439fc707c38f92a",
"rev": "34cdbf6ad480ce13a6a526f57d8b9e609f3d65dc",
"type": "github"
},
"original": {
@@ -79,36 +73,6 @@
"repo": "rust-overlay",
"type": "github"
}
},
"systems": {
"locked": {
"lastModified": 1681028828,
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
"owner": "nix-systems",
"repo": "default",
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
"type": "github"
},
"original": {
"owner": "nix-systems",
"repo": "default",
"type": "github"
}
},
"systems_2": {
"locked": {
"lastModified": 1681028828,
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
"owner": "nix-systems",
"repo": "default",
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
"type": "github"
},
"original": {
"owner": "nix-systems",
"repo": "default",
"type": "github"
}
}
},
"root": "root",

View File

@@ -36,10 +36,6 @@ ssr = [
"leptos_router/ssr",
]
[package.metadata.cargo-all-features]
denylist = ["actix-files", "actix-web", "leptos_actix"]
skip_feature_sets = [["ssr", "hydrate"]]
[package.metadata.leptos]
# The name used by wasm-bindgen/cargo-leptos for the JS/WASM bundle. Defaults to the crate name
output-name = "ssr_modes"

View File

@@ -39,10 +39,6 @@ ssr = [
"dep:leptos_axum",
]
[package.metadata.cargo-all-features]
denylist = ["axum", "tower", "tower-http", "tokio", "sqlx", "leptos_axum"]
skip_feature_sets = [["ssr", "hydrate"]]
[package.metadata.leptos]
# The name used by wasm-bindgen/cargo-leptos for the JS/WASM bundle. Defaults to the crate name
output-name = "ssr_modes"

View File

@@ -1,23 +1,19 @@
# Leptos Todo App Sqlite
# Leptos Todo App Sqlite
This example creates a basic todo app with an Actix backend that uses Leptos' server functions to call sqlx from the client and seamlessly run it on the server.
## Client Side Rendering
This example cannot be built as a trunk standalone CSR-only app. Only the server may directly connect to the database.
To run it as a Client Side App, you can issue `trunk serve --open` in the root. This will build the entire
app into one CSR bundle. Make sure you have trunk installed with `cargo install trunk`.
## Server Side Rendering with cargo-leptos
cargo-leptos is now the easiest and most featureful way to build server side rendered apps with hydration. It provides automatic recompilation of client and server code, wasm optimisation, CSS minification, and more! Check out more about it [here](https://github.com/akesson/cargo-leptos)
1. Install cargo-leptos
```bash
cargo install --locked cargo-leptos
```
```
2. Build the site in watch mode, recompiling on file changes
```bash
cargo leptos watch
```
@@ -25,30 +21,24 @@ cargo leptos watch
Open browser on [http://localhost:3000/](http://localhost:3000/)
3. When ready to deploy, run
```bash
cargo leptos build --release
```
## Server Side Rendering without cargo-leptos
To run it as a server side app with hydration, you'll need to have wasm-pack installed.
0. Edit the `[package.metadata.leptos]` section and set `site-root` to `"."`. You'll also want to change the path of the `<StyleSheet / >` component in the root component to point towards the CSS file in the root. This tells leptos that the WASM/JS files generated by wasm-pack are available at `./pkg` and that the CSS files are no longer processed by cargo-leptos. Building to alternative folders is not supported at this time. You'll also want to edit the call to `get_configuration()` to pass in `Some(Cargo.toml)`, so that Leptos will read the settings instead of cargo-leptos. If you do so, your file/folder names cannot include dashes.
1. Install wasm-pack
```bash
cargo install wasm-pack
```
2. Build the Webassembly used to hydrate the HTML from the server
```bash
wasm-pack build --target=web --debug --no-default-features --features=hydrate
```
3. Run the server to serve the Webassembly, JS, and HTML
3. Run the server to serve the Webassembly, JS, and HTML
```bash
cargo run --no-default-features --features=ssr
```

View File

@@ -18,7 +18,6 @@ cfg_if! {
_ = GetTodos::register();
_ = AddTodo::register();
_ = DeleteTodo::register();
_ = FormDataHandler::register();
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, sqlx::FromRow)]
@@ -107,24 +106,6 @@ pub async fn delete_todo(id: u16) -> Result<(), ServerFnError> {
.map_err(|e| ServerFnError::ServerError(e.to_string()))
}
#[derive(Serialize, Deserialize, Debug, Clone, Default)]
pub struct FormData {
hi: String
}
#[server(FormDataHandler, "/api")]
pub async fn form_data(cx: Scope) -> Result<FormData, ServerFnError> {
use axum::extract::FromRequest;
let req = use_context::<leptos_axum::LeptosRequest<axum::body::Body>>(cx).and_then(|req| req.take_request()).unwrap();
if req.method() == http::Method::POST {
let form = axum::Form::from_request(req, &()).await.map_err(|e| ServerFnError::ServerError(e.to_string()))?;
Ok(form.0)
} else {
Err(ServerFnError::ServerError("wrong form fields submitted".to_string()))
}
}
#[component]
pub fn TodoApp(cx: Scope) -> impl IntoView {
//let id = use_context::<String>(cx);
@@ -145,23 +126,6 @@ pub fn TodoApp(cx: Scope) -> impl IntoView {
<Todos/>
</ErrorBoundary>
}/> //Route
<Route path="weird" methods=&[Method::Get, Method::Post]
ssr=SsrMode::Async
view=|cx| {
let res = create_resource(cx, || (), move |_| async move {
form_data(cx).await
});
view! { cx,
<Suspense fallback=|| ()>
<pre>
{move || {
res.with(cx, |body| format!("{body:#?}"))
}}
</pre>
</Suspense>
}
}
/>
</Routes>
</main>
</Router>
@@ -183,10 +147,6 @@ pub fn Todos(cx: Scope) -> impl IntoView {
view! {
cx,
<form method="POST" action="/weird">
<input type="text" name="hi" value="John"/>
<input type="submit"/>
</form>
<div>
<MultiActionForm action=add_todo>
<label>

View File

@@ -3,10 +3,6 @@ name = "todomvc"
version = "0.1.0"
edition = "2021"
[profile.release]
codegen-units = 1
lto = true
[dependencies]
leptos = { path = "../../leptos", default-features = false }
log = "0.4"
@@ -25,6 +21,3 @@ default = ["csr"]
csr = ["leptos/csr"]
hydrate = ["leptos/hydrate"]
ssr = ["leptos/ssr"]
[package.metadata.cargo-all-features]
skip_feature_sets = [["csr", "ssr"], ["csr", "hydrate"], ["ssr", "hydrate"]]

View File

@@ -201,11 +201,15 @@ pub fn handle_server_fns_with_context(
Encoding::Url | Encoding::Cbor => body,
Encoding::GetJSON | Encoding::GetCBOR => query,
};
let res = match (server_fn.trait_obj)(cx, data).await {
match (server_fn.trait_obj)(cx, data).await {
Ok(serialized) => {
let res_options =
use_context::<ResponseOptions>(cx).unwrap();
// clean up the scope, which we only needed to run the server fn
disposer.dispose();
runtime.dispose();
let mut res: HttpResponseBuilder;
let mut res_parts = res_options.0.write();
@@ -264,11 +268,7 @@ pub fn handle_server_fns_with_context(
serde_json::to_string(&e)
.unwrap_or_else(|_| e.to_string()),
),
};
// clean up the scope
disposer.dispose();
runtime.dispose();
res
}
} else {
HttpResponse::BadRequest().body(format!(
"Could not find a server function at the route {:?}. \
@@ -298,7 +298,6 @@ pub fn handle_server_fns_with_context(
/// ```
/// use actix_web::{App, HttpServer};
/// use leptos::*;
/// use leptos_router::Method;
/// use std::{env, net::SocketAddr};
///
/// #[component]
@@ -322,7 +321,6 @@ pub fn handle_server_fns_with_context(
/// leptos_actix::render_app_to_stream(
/// leptos_options.to_owned(),
/// |cx| view! { cx, <MyApp/> },
/// Method::Get,
/// ),
/// )
/// })
@@ -342,12 +340,11 @@ pub fn handle_server_fns_with_context(
pub fn render_app_to_stream<IV>(
options: LeptosOptions,
app_fn: impl Fn(leptos::Scope) -> IV + Clone + 'static,
method: Method,
) -> Route
where
IV: IntoView,
{
render_app_to_stream_with_context(options, |_cx| {}, app_fn, method)
render_app_to_stream_with_context(options, |_cx| {}, app_fn)
}
/// Returns an Actix [Route](actix_web::Route) that listens for a `GET` request and tries
@@ -366,7 +363,6 @@ where
/// ```
/// use actix_web::{App, HttpServer};
/// use leptos::*;
/// use leptos_router::Method;
/// use std::{env, net::SocketAddr};
///
/// #[component]
@@ -390,7 +386,6 @@ where
/// leptos_actix::render_app_to_stream_in_order(
/// leptos_options.to_owned(),
/// |cx| view! { cx, <MyApp/> },
/// Method::Get,
/// ),
/// )
/// })
@@ -410,17 +405,11 @@ where
pub fn render_app_to_stream_in_order<IV>(
options: LeptosOptions,
app_fn: impl Fn(leptos::Scope) -> IV + Clone + 'static,
method: Method,
) -> Route
where
IV: IntoView,
{
render_app_to_stream_in_order_with_context(
options,
|_cx| {},
app_fn,
method,
)
render_app_to_stream_in_order_with_context(options, |_cx| {}, app_fn)
}
/// Returns an Actix [Route](actix_web::Route) that listens for a `GET` request and tries
@@ -437,7 +426,6 @@ where
/// ```
/// use actix_web::{App, HttpServer};
/// use leptos::*;
/// use leptos_router::Method;
/// use std::{env, net::SocketAddr};
///
/// #[component]
@@ -461,7 +449,6 @@ where
/// leptos_actix::render_app_async(
/// leptos_options.to_owned(),
/// |cx| view! { cx, <MyApp/> },
/// Method::Get,
/// ),
/// )
/// })
@@ -481,12 +468,11 @@ where
pub fn render_app_async<IV>(
options: LeptosOptions,
app_fn: impl Fn(leptos::Scope) -> IV + Clone + 'static,
method: Method,
) -> Route
where
IV: IntoView,
{
render_app_async_with_context(options, |_cx| {}, app_fn, method)
render_app_async_with_context(options, |_cx| {}, app_fn)
}
/// Returns an Actix [Route](actix_web::Route) that listens for a `GET` request and tries
@@ -505,12 +491,11 @@ pub fn render_app_to_stream_with_context<IV>(
options: LeptosOptions,
additional_context: impl Fn(leptos::Scope) + 'static + Clone + Send,
app_fn: impl Fn(leptos::Scope) -> IV + Clone + 'static,
method: Method,
) -> Route
where
IV: IntoView,
{
let handler = move |req: HttpRequest| {
web::get().to(move |req: HttpRequest| {
let options = options.clone();
let app_fn = app_fn.clone();
let additional_context = additional_context.clone();
@@ -528,14 +513,7 @@ where
stream_app(&options, app, res_options, additional_context).await
}
};
match method {
Method::Get => web::get().to(handler),
Method::Post => web::post().to(handler),
Method::Put => web::put().to(handler),
Method::Delete => web::delete().to(handler),
Method::Patch => web::patch().to(handler),
}
})
}
/// Returns an Actix [Route](actix_web::Route) that listens for a `GET` request and tries
@@ -554,12 +532,11 @@ pub fn render_app_to_stream_in_order_with_context<IV>(
options: LeptosOptions,
additional_context: impl Fn(leptos::Scope) + 'static + Clone + Send,
app_fn: impl Fn(leptos::Scope) -> IV + Clone + 'static,
method: Method,
) -> Route
where
IV: IntoView,
{
let handler = move |req: HttpRequest| {
web::get().to(move |req: HttpRequest| {
let options = options.clone();
let app_fn = app_fn.clone();
let additional_context = additional_context.clone();
@@ -578,14 +555,7 @@ where
stream_app_in_order(&options, app, res_options, additional_context)
.await
}
};
match method {
Method::Get => web::get().to(handler),
Method::Post => web::post().to(handler),
Method::Put => web::put().to(handler),
Method::Delete => web::delete().to(handler),
Method::Patch => web::patch().to(handler),
}
})
}
/// Returns an Actix [Route](actix_web::Route) that listens for a `GET` request and tries
@@ -605,12 +575,11 @@ pub fn render_app_async_with_context<IV>(
options: LeptosOptions,
additional_context: impl Fn(leptos::Scope) + 'static + Clone + Send,
app_fn: impl Fn(leptos::Scope) -> IV + Clone + 'static,
method: Method,
) -> Route
where
IV: IntoView,
{
let handler = move |req: HttpRequest| {
web::get().to(move |req: HttpRequest| {
let options = options.clone();
let app_fn = app_fn.clone();
let additional_context = additional_context.clone();
@@ -634,14 +603,7 @@ where
)
.await
}
};
match method {
Method::Get => web::get().to(handler),
Method::Post => web::post().to(handler),
Method::Put => web::put().to(handler),
Method::Delete => web::delete().to(handler),
Method::Patch => web::patch().to(handler),
}
})
}
/// Returns an Actix [Route](actix_web::Route) that listens for a `GET` request and tries
@@ -892,7 +854,7 @@ async fn render_app_async_helper(
/// as an argument so it can walk you app tree. This version is tailored to generated Actix compatible paths.
pub fn generate_route_list<IV>(
app_fn: impl FnOnce(leptos::Scope) -> IV + 'static,
) -> Vec<RouteListing>
) -> Vec<(String, SsrMode)>
where
IV: IntoView + 'static,
{
@@ -901,16 +863,11 @@ where
// Empty strings screw with Actix pathing, they need to be "/"
routes = routes
.into_iter()
.map(|listing| {
let path = listing.path();
if path.is_empty() {
return RouteListing::new(
"/".to_string(),
listing.mode(),
listing.methods(),
);
.map(|(s, mode)| {
if s.is_empty() {
return ("/".to_string(), mode);
}
RouteListing::new(listing.path(), listing.mode(), listing.methods())
(s, mode)
})
.collect();
@@ -920,19 +877,14 @@ where
// Match `:some_word` but only capture `some_word` in the groups to replace with `{some_word}`
let capture_re = Regex::new(r":((?:[^.,/]+)+)[^/]?").unwrap();
let routes = routes
let routes: Vec<(String, SsrMode)> = routes
.into_iter()
.map(|listing| {
let path = wildcard_re
.replace_all(listing.path(), "{tail:.*}")
.to_string();
let path = capture_re.replace_all(&path, "{$1}").to_string();
RouteListing::new(path, listing.mode(), listing.methods())
})
.collect::<Vec<_>>();
.map(|(s, m)| (wildcard_re.replace_all(&s, "{tail:.*}").to_string(), m))
.map(|(s, m)| (capture_re.replace_all(&s, "{$1}").to_string(), m))
.collect();
if routes.is_empty() {
vec![RouteListing::new("/", Default::default(), [Method::Get])]
vec![("/".to_string(), Default::default())]
} else {
routes
}
@@ -949,7 +901,7 @@ pub trait LeptosRoutes {
fn leptos_routes<IV>(
self,
options: LeptosOptions,
paths: Vec<RouteListing>,
paths: Vec<(String, SsrMode)>,
app_fn: impl Fn(leptos::Scope) -> IV + Clone + Send + 'static,
) -> Self
where
@@ -974,7 +926,7 @@ pub trait LeptosRoutes {
fn leptos_routes_with_context<IV>(
self,
options: LeptosOptions,
paths: Vec<RouteListing>,
paths: Vec<(String, SsrMode)>,
additional_context: impl Fn(leptos::Scope) + 'static + Clone + Send,
app_fn: impl Fn(leptos::Scope) -> IV + Clone + Send + 'static,
) -> Self
@@ -996,7 +948,7 @@ where
fn leptos_routes<IV>(
self,
options: LeptosOptions,
paths: Vec<RouteListing>,
paths: Vec<(String, SsrMode)>,
app_fn: impl Fn(leptos::Scope) -> IV + Clone + Send + 'static,
) -> Self
where
@@ -1036,7 +988,7 @@ where
fn leptos_routes_with_context<IV>(
self,
options: LeptosOptions,
paths: Vec<RouteListing>,
paths: Vec<(String, SsrMode)>,
additional_context: impl Fn(leptos::Scope) + 'static + Clone + Send,
app_fn: impl Fn(leptos::Scope) -> IV + Clone + Send + 'static,
) -> Self
@@ -1044,39 +996,29 @@ where
IV: IntoView + 'static,
{
let mut router = self;
for listing in paths.iter() {
let path = listing.path();
let mode = listing.mode();
for method in listing.methods() {
router = router.route(
path,
match mode {
SsrMode::OutOfOrder => {
render_app_to_stream_with_context(
options.clone(),
additional_context.clone(),
app_fn.clone(),
method,
)
}
SsrMode::InOrder => {
render_app_to_stream_in_order_with_context(
options.clone(),
additional_context.clone(),
app_fn.clone(),
method,
)
}
SsrMode::Async => render_app_async_with_context(
for (path, mode) in paths.iter() {
router = router.route(
path,
match mode {
SsrMode::OutOfOrder => render_app_to_stream_with_context(
options.clone(),
additional_context.clone(),
app_fn.clone(),
),
SsrMode::InOrder => {
render_app_to_stream_in_order_with_context(
options.clone(),
additional_context.clone(),
app_fn.clone(),
method,
),
},
);
}
)
}
SsrMode::Async => render_app_async_with_context(
options.clone(),
additional_context.clone(),
app_fn.clone(),
),
},
);
}
router
}

View File

@@ -19,5 +19,4 @@ leptos_integration_utils = { workspace = true }
serde_json = "1"
tokio = { version = "1", features = ["full"] }
parking_lot = "0.12.1"
tokio-util = {version = "0.7.7", features = ["rt"] }
once_cell = "1.17"
tokio-util = {version = "0.7.7", features = ["rt"] }

View File

@@ -14,7 +14,7 @@ use axum::{
HeaderMap, Request, StatusCode,
},
response::IntoResponse,
routing::{delete, get, patch, post, put},
routing::get,
};
use futures::{
channel::mpsc::{Receiver, Sender},
@@ -31,9 +31,13 @@ use leptos::{
use leptos_integration_utils::{build_async_response, html_parts_separated};
use leptos_meta::{generate_head_metadata_separated, MetaContext};
use leptos_router::*;
use once_cell::sync::OnceCell;
use parking_lot::RwLock;
use std::{io, pin::Pin, sync::Arc, thread::available_parallelism};
use std::{
io,
pin::Pin,
sync::{Arc, OnceLock},
thread::available_parallelism,
};
use tokio::task::LocalSet;
use tokio_util::task::LocalPoolHandle;
@@ -319,11 +323,15 @@ async fn handle_server_fns_inner(
Encoding::Url | Encoding::Cbor => &req_parts.body,
Encoding::GetJSON | Encoding::GetCBOR => query,
};
let res = match (server_fn.trait_obj)(cx, data).await {
match (server_fn.trait_obj)(cx, data).await {
Ok(serialized) => {
// If ResponseOptions are set, add the headers and status to the request
let res_options = use_context::<ResponseOptions>(cx);
// clean up the scope, which we only needed to run the server fn
disposer.dispose();
runtime.dispose();
// if this is Accept: application/json then send a serialized JSON response
let accept_header = headers
.get("Accept")
@@ -388,11 +396,7 @@ async fn handle_server_fns_inner(
serde_json::to_string(&e)
.unwrap_or_else(|_| e.to_string()),
)),
};
// clean up the scope
disposer.dispose();
runtime.dispose();
res
}
} else {
Response::builder().status(StatusCode::BAD_REQUEST).body(
Full::from(format!(
@@ -991,12 +995,12 @@ where
/// as an argument so it can walk you app tree. This version is tailored to generate Axum compatible paths.
pub async fn generate_route_list<IV>(
app_fn: impl FnOnce(Scope) -> IV + 'static,
) -> Vec<RouteListing>
) -> Vec<(String, SsrMode)>
where
IV: IntoView + 'static,
{
#[derive(Default, Clone, Debug)]
pub struct Routes(pub Arc<RwLock<Vec<RouteListing>>>);
pub struct Routes(pub Arc<RwLock<Vec<(String, SsrMode)>>>);
let routes = Routes::default();
let routes_inner = routes.clone();
@@ -1020,26 +1024,17 @@ where
// Axum's Router defines Root routes as "/" not ""
let routes = routes
.into_iter()
.map(|listing| {
let path = listing.path();
if path.is_empty() {
RouteListing::new(
"/",
Default::default(),
[leptos_router::Method::Get],
)
.map(|(s, m)| {
if s.is_empty() {
("/".to_string(), m)
} else {
listing
(s, m)
}
})
.collect::<Vec<_>>();
if routes.is_empty() {
vec![RouteListing::new(
"/",
Default::default(),
[leptos_router::Method::Get],
)]
vec![("/".to_string(), Default::default())]
} else {
routes
}
@@ -1051,7 +1046,7 @@ pub trait LeptosRoutes {
fn leptos_routes<IV>(
self,
options: LeptosOptions,
paths: Vec<RouteListing>,
paths: Vec<(String, SsrMode)>,
app_fn: impl Fn(leptos::Scope) -> IV + Clone + Send + 'static,
) -> Self
where
@@ -1060,7 +1055,7 @@ pub trait LeptosRoutes {
fn leptos_routes_with_context<IV>(
self,
options: LeptosOptions,
paths: Vec<RouteListing>,
paths: Vec<(String, SsrMode)>,
additional_context: impl Fn(leptos::Scope) + 'static + Clone + Send,
app_fn: impl Fn(leptos::Scope) -> IV + Clone + Send + 'static,
) -> Self
@@ -1069,7 +1064,7 @@ pub trait LeptosRoutes {
fn leptos_routes_with_handler<H, T>(
self,
paths: Vec<RouteListing>,
paths: Vec<(String, SsrMode)>,
handler: H,
) -> Self
where
@@ -1082,7 +1077,7 @@ impl LeptosRoutes for axum::Router {
fn leptos_routes<IV>(
self,
options: LeptosOptions,
paths: Vec<RouteListing>,
paths: Vec<(String, SsrMode)>,
app_fn: impl Fn(leptos::Scope) -> IV + Clone + Send + 'static,
) -> Self
where
@@ -1094,7 +1089,7 @@ impl LeptosRoutes for axum::Router {
fn leptos_routes_with_context<IV>(
self,
options: LeptosOptions,
paths: Vec<RouteListing>,
paths: Vec<(String, SsrMode)>,
additional_context: impl Fn(leptos::Scope) + 'static + Clone + Send,
app_fn: impl Fn(leptos::Scope) -> IV + Clone + Send + 'static,
) -> Self
@@ -1102,65 +1097,38 @@ impl LeptosRoutes for axum::Router {
IV: IntoView + 'static,
{
let mut router = self;
for listing in paths.iter() {
let path = listing.path();
for method in listing.methods() {
router = router.route(
path,
match listing.mode() {
SsrMode::OutOfOrder => {
let s = render_app_to_stream_with_context(
options.clone(),
additional_context.clone(),
app_fn.clone(),
);
match method {
leptos_router::Method::Get => get(s),
leptos_router::Method::Post => post(s),
leptos_router::Method::Put => put(s),
leptos_router::Method::Delete => delete(s),
leptos_router::Method::Patch => patch(s),
}
}
SsrMode::InOrder => {
let s = render_app_to_stream_in_order_with_context(
options.clone(),
additional_context.clone(),
app_fn.clone(),
);
match method {
leptos_router::Method::Get => get(s),
leptos_router::Method::Post => post(s),
leptos_router::Method::Put => put(s),
leptos_router::Method::Delete => delete(s),
leptos_router::Method::Patch => patch(s),
}
}
SsrMode::Async => {
let s = render_app_async_with_context(
options.clone(),
additional_context.clone(),
app_fn.clone(),
);
match method {
leptos_router::Method::Get => get(s),
leptos_router::Method::Post => post(s),
leptos_router::Method::Put => put(s),
leptos_router::Method::Delete => delete(s),
leptos_router::Method::Patch => patch(s),
}
}
},
);
}
for (path, mode) in paths.iter() {
router = router.route(
path,
match mode {
SsrMode::OutOfOrder => {
get(render_app_to_stream_with_context(
options.clone(),
additional_context.clone(),
app_fn.clone(),
))
}
SsrMode::InOrder => {
get(render_app_to_stream_in_order_with_context(
options.clone(),
additional_context.clone(),
app_fn.clone(),
))
}
SsrMode::Async => get(render_app_async_with_context(
options.clone(),
additional_context.clone(),
app_fn.clone(),
)),
},
);
}
router
}
fn leptos_routes_with_handler<H, T>(
self,
paths: Vec<RouteListing>,
paths: Vec<(String, SsrMode)>,
handler: H,
) -> Self
where
@@ -1168,28 +1136,15 @@ impl LeptosRoutes for axum::Router {
T: 'static,
{
let mut router = self;
for listing in paths.iter() {
for method in listing.methods() {
router = router.route(
listing.path(),
match method {
leptos_router::Method::Get => get(handler.clone()),
leptos_router::Method::Post => post(handler.clone()),
leptos_router::Method::Put => put(handler.clone()),
leptos_router::Method::Delete => {
delete(handler.clone())
}
leptos_router::Method::Patch => patch(handler.clone()),
},
);
}
for (path, _) in paths.iter() {
router = router.route(path, get(handler.clone()));
}
router
}
}
fn get_leptos_pool() -> LocalPoolHandle {
static LOCAL_POOL: OnceCell<LocalPoolHandle> = OnceCell::new();
static LOCAL_POOL: OnceLock<LocalPoolHandle> = OnceLock::new();
LOCAL_POOL
.get_or_init(|| {
tokio_util::task::LocalPoolHandle::new(

View File

@@ -216,14 +216,16 @@ async fn handle_server_fns_inner(
Encoding::GetJSON | Encoding::GetCBOR => &query,
};
let res = match (server_fn.trait_obj)(cx, data)
.await
{
match (server_fn.trait_obj)(cx, data).await {
Ok(serialized) => {
// If ResponseOptions are set, add the headers and status to the request
let res_options =
use_context::<ResponseOptions>(cx);
// clean up the scope, which we only needed to run the server fn
disposer.dispose();
runtime.dispose();
// if this is Accept: application/json then send a serialized JSON response
let accept_header = headers
.get("Accept")
@@ -303,11 +305,7 @@ async fn handle_server_fns_inner(
serde_json::to_string(&e)
.unwrap_or_else(|_| e.to_string()),
)),
};
// clean up the scope
disposer.dispose();
runtime.dispose();
res
}
} else {
Response::builder()
.status(StatusCode::BAD_REQUEST)
@@ -946,12 +944,12 @@ where
/// as an argument so it can walk you app tree. This version is tailored to generate Viz compatible paths.
pub async fn generate_route_list<IV>(
app_fn: impl FnOnce(Scope) -> IV + 'static,
) -> Vec<RouteListing>
) -> Vec<(String, SsrMode)>
where
IV: IntoView + 'static,
{
#[derive(Default, Clone, Debug)]
pub struct Routes(pub Arc<RwLock<Vec<RouteListing>>>);
pub struct Routes(pub Arc<RwLock<Vec<(String, SsrMode)>>>);
let routes = Routes::default();
let routes_inner = routes.clone();
@@ -975,26 +973,17 @@ where
// Viz's Router defines Root routes as "/" not ""
let routes = routes
.into_iter()
.map(|listing| {
let path = listing.path();
if path.is_empty() {
RouteListing::new(
"/",
Default::default(),
[leptos_router::Method::Get],
)
.map(|(s, m)| {
if s.is_empty() {
("/".to_string(), m)
} else {
listing
(s, m)
}
})
.collect::<Vec<_>>();
if routes.is_empty() {
vec![RouteListing::new(
"/",
Default::default(),
[leptos_router::Method::Get],
)]
vec![("/".to_string(), Default::default())]
} else {
routes
}
@@ -1006,7 +995,7 @@ pub trait LeptosRoutes {
fn leptos_routes<IV>(
self,
options: LeptosOptions,
paths: Vec<RouteListing>,
paths: Vec<(String, SsrMode)>,
app_fn: impl Fn(leptos::Scope) -> IV + Clone + Send + Sync + 'static,
) -> Self
where
@@ -1015,7 +1004,7 @@ pub trait LeptosRoutes {
fn leptos_routes_with_context<IV>(
self,
options: LeptosOptions,
paths: Vec<RouteListing>,
paths: Vec<(String, SsrMode)>,
additional_context: impl Fn(leptos::Scope) + Clone + Send + Sync + 'static,
app_fn: impl Fn(leptos::Scope) -> IV + Clone + Send + Sync + 'static,
) -> Self
@@ -1024,7 +1013,7 @@ pub trait LeptosRoutes {
fn leptos_routes_with_handler<H, O>(
self,
paths: Vec<RouteListing>,
paths: Vec<(String, SsrMode)>,
handler: H,
) -> Self
where
@@ -1037,7 +1026,7 @@ impl LeptosRoutes for Router {
fn leptos_routes<IV>(
self,
options: LeptosOptions,
paths: Vec<RouteListing>,
paths: Vec<(String, SsrMode)>,
app_fn: impl Fn(leptos::Scope) -> IV + Clone + Send + Sync + 'static,
) -> Self
where
@@ -1049,93 +1038,52 @@ impl LeptosRoutes for Router {
fn leptos_routes_with_context<IV>(
self,
options: LeptosOptions,
paths: Vec<RouteListing>,
paths: Vec<(String, SsrMode)>,
additional_context: impl Fn(leptos::Scope) + Clone + Send + Sync + 'static,
app_fn: impl Fn(leptos::Scope) -> IV + Clone + Send + Sync + 'static,
) -> Self
where
IV: IntoView + 'static,
{
paths.iter().fold(self, |router, listing| {
let path = listing.path();
let mode = listing.mode();
listing.methods().fold(router, |router, method| match mode {
SsrMode::OutOfOrder => {
let s = render_app_to_stream_with_context(
options.clone(),
additional_context.clone(),
app_fn.clone(),
);
match method {
leptos_router::Method::Get => router.get(path, s),
leptos_router::Method::Post => router.post(path, s),
leptos_router::Method::Put => router.put(path, s),
leptos_router::Method::Delete => router.delete(path, s),
leptos_router::Method::Patch => router.patch(path, s),
}
}
SsrMode::InOrder => {
let s = render_app_to_stream_in_order_with_context(
options.clone(),
additional_context.clone(),
app_fn.clone(),
);
match method {
leptos_router::Method::Get => router.get(path, s),
leptos_router::Method::Post => router.post(path, s),
leptos_router::Method::Put => router.put(path, s),
leptos_router::Method::Delete => router.delete(path, s),
leptos_router::Method::Patch => router.patch(path, s),
}
}
SsrMode::Async => {
let s = render_app_async_with_context(
options.clone(),
additional_context.clone(),
app_fn.clone(),
);
match method {
leptos_router::Method::Get => router.get(path, s),
leptos_router::Method::Post => router.post(path, s),
leptos_router::Method::Put => router.put(path, s),
leptos_router::Method::Delete => router.delete(path, s),
leptos_router::Method::Patch => router.patch(path, s),
}
}
})
paths.iter().fold(self, |router, (path, mode)| match mode {
SsrMode::OutOfOrder => router.get(
path,
render_app_to_stream_with_context(
options.clone(),
additional_context.clone(),
app_fn.clone(),
),
),
SsrMode::InOrder => router.get(
path,
render_app_to_stream_in_order_with_context(
options.clone(),
additional_context.clone(),
app_fn.clone(),
),
),
SsrMode::Async => router.get(
path,
render_app_async_with_context(
options.clone(),
additional_context.clone(),
app_fn.clone(),
),
),
})
}
fn leptos_routes_with_handler<H, O>(
self,
paths: Vec<RouteListing>,
paths: Vec<(String, SsrMode)>,
handler: H,
) -> Self
where
H: Handler<Request, Output = Result<O>> + Clone,
O: IntoResponse + Send + Sync + 'static,
{
paths.iter().fold(self, |router, listing| {
listing
.methods()
.fold(router, |router, method| match method {
leptos_router::Method::Get => {
router.get(listing.path(), handler.clone())
}
leptos_router::Method::Post => {
router.post(listing.path(), handler.clone())
}
leptos_router::Method::Put => {
router.put(listing.path(), handler.clone())
}
leptos_router::Method::Delete => {
router.delete(listing.path(), handler.clone())
}
leptos_router::Method::Patch => {
router.patch(listing.path(), handler.clone())
}
})
})
paths
.iter()
.fold(self, |router, (path, _)| router.get(path, handler.clone()))
}
}

View File

@@ -13,11 +13,11 @@ cfg-if = "1"
leptos_dom = { workspace = true }
leptos_macro = { workspace = true }
leptos_reactive = { workspace = true }
leptos_server = { workspace = true, default-features = false }
leptos_server = { workspace = true }
leptos_config = { workspace = true }
tracing = "0.1"
typed-builder = "0.14"
server_fn = { workspace = true, default-features = false }
server_fn = { workspace = true }
[dev-dependencies]
leptos = { path = ".", default-features = false }
@@ -36,8 +36,6 @@ hydrate = [
"leptos_reactive/hydrate",
"leptos_server/hydrate",
]
default-tls = ["leptos_server/default-tls", "server_fn/default-tls"]
rustls = ["leptos_server/rustls", "server_fn/rustls"]
ssr = [
"leptos_dom/ssr",
"leptos_macro/ssr",
@@ -95,8 +93,4 @@ skip_feature_sets = [
"serde-lite",
"rkyv",
],
[
"default-tls",
"rustls",
],
]

View File

@@ -141,8 +141,6 @@
//! # }
//! ```
mod additional_attributes;
pub use additional_attributes::*;
pub use leptos_config::{self, get_configuration, LeptosOptions};
#[cfg(not(all(
target_arch = "wasm32",
@@ -182,9 +180,7 @@ pub use for_loop::*;
pub use show::*;
mod suspense;
pub use suspense::*;
mod text_prop;
mod transition;
pub use text_prop::TextProp;
#[cfg(debug_assertions)]
#[doc(hidden)]
pub use tracing;
@@ -240,24 +236,3 @@ pub fn component_props_builder<P: Props>(
) -> <P as Props>::Builder {
<P as Props>::builder()
}
#[cfg(all(not(doc), feature = "csr", feature = "ssr"))]
compile_error!(
"You have both `csr` and `ssr` enabled as features, which may cause \
issues like <Suspense/>` failing to work silently. `csr` is enabled by \
default on `leptos`, and can be disabled by adding `default-features = \
false` to your `leptos` dependency."
);
#[cfg(all(not(doc), feature = "hydrate", feature = "ssr"))]
compile_error!(
"You have both `hydrate` and `ssr` enabled as features, which may cause \
issues like <Suspense/>` failing to work silently."
);
#[cfg(all(not(doc), feature = "hydrate", feature = "csr"))]
compile_error!(
"You have both `hydrate` and `csr` enabled as features, which may cause \
issues. `csr` is enabled by default on `leptos`, and can be disabled by \
adding `default-features = false` to your `leptos` dependency."
);

View File

@@ -1,43 +0,0 @@
use std::{fmt::Debug, rc::Rc};
/// Describes a value that is either a static or a reactive string, i.e.,
/// a [String], a [&str], or a reactive `Fn() -> String`.
#[derive(Clone)]
pub struct TextProp(Rc<dyn Fn() -> String>);
impl TextProp {
/// Accesses the current value of the property.
#[inline(always)]
pub fn get(&self) -> String {
(self.0)()
}
}
impl Debug for TextProp {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("TextProp").finish()
}
}
impl From<String> for TextProp {
fn from(s: String) -> Self {
TextProp(Rc::new(move || s.clone()))
}
}
impl From<&str> for TextProp {
fn from(s: &str) -> Self {
let s = s.to_string();
TextProp(Rc::new(move || s.clone()))
}
}
impl<F> From<F> for TextProp
where
F: Fn() -> String + 'static,
{
#[inline(always)]
fn from(s: F) -> Self {
TextProp(Rc::new(s))
}
}

View File

@@ -135,7 +135,6 @@ impl Mountable for ComponentRepr {
};
}
#[inline]
fn get_closing_node(&self) -> web_sys::Node {
self.closing.node.clone()
}
@@ -157,21 +156,17 @@ impl IntoView for ComponentRepr {
impl ComponentRepr {
/// Creates a new [`Component`].
#[inline(always)]
pub fn new(name: impl Into<Cow<'static, str>>) -> Self {
Self::new_with_id_concrete(name.into(), HydrationCtx::id())
Self::new_with_id(name, HydrationCtx::id())
}
/// Creates a new [`Component`] with the given hydration ID.
#[inline(always)]
pub fn new_with_id(
name: impl Into<Cow<'static, str>>,
id: HydrationKey,
) -> Self {
Self::new_with_id_concrete(name.into(), id)
}
let name = name.into();
fn new_with_id_concrete(name: Cow<'static, str>, id: HydrationKey) -> Self {
let markers = (
Comment::new(Cow::Owned(format!("</{name}>")), &id, true),
#[cfg(debug_assertions)]

View File

@@ -139,15 +139,13 @@ where
/// Creates a new dynamic child which will re-render whenever it's
/// signal dependencies change.
#[track_caller]
#[inline(always)]
pub fn new(child_fn: CF) -> Self {
Self::new_with_id(HydrationCtx::id(), child_fn)
}
#[doc(hidden)]
#[track_caller]
#[inline(always)]
pub const fn new_with_id(id: HydrationKey, child_fn: CF) -> Self {
pub fn new_with_id(id: HydrationKey, child_fn: CF) -> Self {
Self { id, child_fn }
}
}
@@ -161,10 +159,8 @@ where
debug_assertions,
instrument(level = "trace", name = "<DynChild />", skip_all)
)]
#[inline]
fn into_view(self, cx: Scope) -> View {
// concrete inner function
#[inline(never)]
fn create_dyn_view(
cx: Scope,
component: DynChildRepr,
@@ -383,7 +379,6 @@ cfg_if! {
}
impl NonViewMarkerSibling for web_sys::Node {
#[cfg_attr(not(debug_assertions), inline(always))]
fn next_non_view_marker_sibling(&self) -> Option<Node> {
cfg_if! {
if #[cfg(debug_assertions)] {
@@ -400,7 +395,6 @@ cfg_if! {
}
}
#[cfg_attr(not(debug_assertions), inline(always))]
fn previous_non_view_marker_sibling(&self) -> Option<Node> {
cfg_if! {
if #[cfg(debug_assertions)] {

View File

@@ -155,7 +155,6 @@ impl Mountable for EachRepr {
};
}
#[inline(always)]
fn get_closing_node(&self) -> web_sys::Node {
self.closing.node.clone()
}
@@ -258,7 +257,6 @@ impl Mountable for EachItem {
}
}
#[inline(always)]
fn get_opening_node(&self) -> web_sys::Node {
#[cfg(debug_assertions)]
return self.opening.node.clone();
@@ -330,8 +328,7 @@ where
T: 'static,
{
/// Creates a new [`Each`] component.
#[inline(always)]
pub const fn new(items_fn: IF, key_fn: KF, each_fn: EF) -> Self {
pub fn new(items_fn: IF, key_fn: KF, each_fn: EF) -> Self {
Self {
items_fn,
each_fn,

View File

@@ -1,23 +1,20 @@
use crate::{HydrationCtx, IntoView};
use cfg_if::cfg_if;
use leptos_reactive::{signal_prelude::*, use_context, RwSignal};
use std::{borrow::Cow, collections::HashMap, error::Error, sync::Arc};
use std::{collections::HashMap, error::Error, sync::Arc};
/// A struct to hold all the possible errors that could be provided by child Views
#[derive(Debug, Clone, Default)]
#[repr(transparent)]
pub struct Errors(HashMap<ErrorKey, Arc<dyn Error + Send + Sync>>);
/// A unique key for an error that occurs at a particular location in the user interface.
#[derive(Debug, Default, Clone, PartialEq, Eq, Hash)]
#[repr(transparent)]
pub struct ErrorKey(Cow<'static, str>);
pub struct ErrorKey(String);
impl<T> From<T> for ErrorKey
where
T: Into<Cow<'static, str>>,
T: Into<String>,
{
#[inline(always)]
fn from(key: T) -> ErrorKey {
ErrorKey(key.into())
}
@@ -27,14 +24,12 @@ impl IntoIterator for Errors {
type Item = (ErrorKey, Arc<dyn Error + Send + Sync>);
type IntoIter = IntoIter;
#[inline(always)]
fn into_iter(self) -> Self::IntoIter {
IntoIter(self.0.into_iter())
}
}
/// An owning iterator over all the errors contained in the [Errors] struct.
#[repr(transparent)]
pub struct IntoIter(
std::collections::hash_map::IntoIter<
ErrorKey,
@@ -45,7 +40,6 @@ pub struct IntoIter(
impl Iterator for IntoIter {
type Item = (ErrorKey, Arc<dyn Error + Send + Sync>);
#[inline(always)]
fn next(
&mut self,
) -> std::option::Option<<Self as std::iter::Iterator>::Item> {
@@ -54,7 +48,6 @@ impl Iterator for IntoIter {
}
/// An iterator over all the errors contained in the [Errors] struct.
#[repr(transparent)]
pub struct Iter<'a>(
std::collections::hash_map::Iter<
'a,
@@ -66,7 +59,6 @@ pub struct Iter<'a>(
impl<'a> Iterator for Iter<'a> {
type Item = (&'a ErrorKey, &'a Arc<dyn Error + Send + Sync>);
#[inline(always)]
fn next(
&mut self,
) -> std::option::Option<<Self as std::iter::Iterator>::Item> {
@@ -80,7 +72,7 @@ where
E: Error + Send + Sync + 'static,
{
fn into_view(self, cx: leptos_reactive::Scope) -> crate::View {
let id = ErrorKey(HydrationCtx::peek().previous.into());
let id = ErrorKey(HydrationCtx::peek().previous);
let errors = use_context::<RwSignal<Errors>>(cx);
match self {
Ok(stuff) => {
@@ -135,7 +127,6 @@ where
}
impl Errors {
/// Returns `true` if there are no errors.
#[inline(always)]
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
@@ -165,7 +156,6 @@ impl Errors {
}
/// An iterator over all the errors, in arbitrary order.
#[inline(always)]
pub fn iter(&self) -> Iter<'_> {
Iter(self.0.iter())
}

View File

@@ -43,20 +43,17 @@ impl From<View> for Fragment {
impl Fragment {
/// Creates a new [`Fragment`] from a [`Vec<Node>`].
#[inline(always)]
pub fn new(nodes: Vec<View>) -> Self {
Self::new_with_id(HydrationCtx::id(), nodes)
}
/// Creates a new [`Fragment`] from a function that returns [`Vec<Node>`].
#[inline(always)]
pub fn lazy(nodes: impl FnOnce() -> Vec<View>) -> Self {
Self::new_with_id(HydrationCtx::id(), nodes())
}
/// Creates a new [`Fragment`] with the given hydration ID from a [`Vec<Node>`].
#[inline(always)]
pub const fn new_with_id(id: HydrationKey, nodes: Vec<View>) -> Self {
pub fn new_with_id(id: HydrationKey, nodes: Vec<View>) -> Self {
Self {
id,
nodes,
@@ -66,13 +63,11 @@ impl Fragment {
}
/// Gives access to the [View] children contained within the fragment.
#[inline(always)]
pub fn as_children(&self) -> &[View] {
&self.nodes
}
/// Returns the fragment's hydration ID.
#[inline(always)]
pub fn id(&self) -> &HydrationKey {
&self.id
}

View File

@@ -40,17 +40,14 @@ impl Default for UnitRepr {
#[cfg(all(target_arch = "wasm32", feature = "web"))]
impl Mountable for UnitRepr {
#[inline(always)]
fn get_mountable_node(&self) -> web_sys::Node {
self.comment.node.clone().unchecked_into()
}
#[inline(always)]
fn get_opening_node(&self) -> web_sys::Node {
self.comment.node.clone().unchecked_into()
}
#[inline(always)]
fn get_closing_node(&self) -> web_sys::Node {
self.comment.node.clone().unchecked_into()
}

View File

@@ -14,7 +14,6 @@ thread_local! {
// Used in template macro
#[doc(hidden)]
#[cfg(all(target_arch = "wasm32", feature = "web"))]
#[inline(always)]
pub fn add_event_helper<E: crate::ev::EventDescriptor + 'static>(
target: &web_sys::Element,
event: E,
@@ -22,9 +21,8 @@ pub fn add_event_helper<E: crate::ev::EventDescriptor + 'static>(
mut event_handler: impl FnMut(E::EventType) + 'static,
) {
let event_name = event.name();
let event_handler = Box::new(event_handler);
if E::BUBBLES {
if event.bubbles() {
add_event_listener(
target,
event.event_delegation_key(),
@@ -49,8 +47,8 @@ pub fn add_event_listener<E>(
target: &web_sys::Element,
key: Cow<'static, str>,
event_name: Cow<'static, str>,
#[cfg(debug_assertions)] mut cb: Box<dyn FnMut(E)>,
#[cfg(not(debug_assertions))] cb: Box<dyn FnMut(E)>,
#[cfg(debug_assertions)] mut cb: impl FnMut(E) + 'static,
#[cfg(not(debug_assertions))] cb: impl FnMut(E) + 'static,
options: &Option<web_sys::AddEventListenerOptions>,
) where
E: FromWasmAbi + 'static,
@@ -58,16 +56,16 @@ pub fn add_event_listener<E>(
cfg_if::cfg_if! {
if #[cfg(debug_assertions)] {
let span = ::tracing::Span::current();
let cb = Box::new(move |e| {
let cb = move |e| {
leptos_reactive::SpecialNonReactiveZone::enter();
let _guard = span.enter();
cb(e);
leptos_reactive::SpecialNonReactiveZone::exit();
});
};
}
}
let cb = Closure::wrap(cb as Box<dyn FnMut(E)>).into_js_value();
let cb = Closure::wrap(Box::new(cb) as Box<dyn FnMut(E)>).into_js_value();
let key = intern(&key);
_ = js_sys::Reflect::set(target, &JsValue::from_str(&key), &cb);
add_delegated_event_listener(&key, event_name, options);
@@ -78,26 +76,26 @@ pub fn add_event_listener<E>(
pub(crate) fn add_event_listener_undelegated<E>(
target: &web_sys::Element,
event_name: &str,
#[cfg(debug_assertions)] mut cb: Box<dyn FnMut(E)>,
#[cfg(not(debug_assertions))] cb: Box<dyn FnMut(E)>,
#[cfg(debug_assertions)] mut cb: impl FnMut(E) + 'static,
#[cfg(not(debug_assertions))] cb: impl FnMut(E) + 'static,
options: &Option<web_sys::AddEventListenerOptions>,
) where
E: FromWasmAbi + 'static,
{
cfg_if::cfg_if! {
if #[cfg(debug_assertions)] {
leptos_reactive::SpecialNonReactiveZone::enter();
let span = ::tracing::Span::current();
let cb = Box::new(move |e| {
leptos_reactive::SpecialNonReactiveZone::enter();
let cb = move |e| {
let _guard = span.enter();
cb(e);
leptos_reactive::SpecialNonReactiveZone::exit();
});
};
leptos_reactive::SpecialNonReactiveZone::exit();
}
}
let event_name = intern(event_name);
let cb = Closure::wrap(cb as Box<dyn FnMut(E)>).into_js_value();
let cb = Closure::wrap(Box::new(cb) as Box<dyn FnMut(E)>).into_js_value();
if let Some(options) = options {
_ = target
.add_event_listener_with_callback_and_add_event_listener_options(

View File

@@ -8,22 +8,23 @@ pub trait EventDescriptor: Clone {
/// The [`web_sys`] event type, such as [`web_sys::MouseEvent`].
type EventType: FromWasmAbi;
/// Indicates if this event bubbles. For example, `click` bubbles,
/// but `focus` does not.
///
/// If this is true, then the event will be delegated globally,
/// otherwise, event listeners will be directly attached to the element.
const BUBBLES: bool;
/// The name of the event, such as `click` or `mouseover`.
fn name(&self) -> Cow<'static, str>;
/// The key used for event delegation.
fn event_delegation_key(&self) -> Cow<'static, str>;
/// Indicates if this event bubbles. For example, `click` bubbles,
/// but `focus` does not.
///
/// If this method returns true, then the event will be delegated globally,
/// otherwise, event listeners will be directly attached to the element.
fn bubbles(&self) -> bool {
true
}
/// Return the options for this type. This is only used when you create a [`Custom`] event
/// handler.
#[inline(always)]
fn options(&self) -> &Option<web_sys::AddEventListenerOptions> {
&None
}
@@ -38,17 +39,17 @@ pub struct undelegated<Ev: EventDescriptor>(pub Ev);
impl<Ev: EventDescriptor> EventDescriptor for undelegated<Ev> {
type EventType = Ev::EventType;
#[inline(always)]
fn name(&self) -> Cow<'static, str> {
self.0.name()
}
#[inline(always)]
fn event_delegation_key(&self) -> Cow<'static, str> {
self.0.event_delegation_key()
}
const BUBBLES: bool = false;
fn bubbles(&self) -> bool {
false
}
}
/// A custom event.
@@ -79,9 +80,10 @@ impl<E: FromWasmAbi> EventDescriptor for Custom<E> {
format!("$$${}", self.name).into()
}
const BUBBLES: bool = false;
fn bubbles(&self) -> bool {
false
}
#[inline(always)]
fn options(&self) -> &Option<web_sys::AddEventListenerOptions> {
&self.options
}
@@ -140,22 +142,24 @@ macro_rules! generate_event_types {
impl EventDescriptor for $event {
type EventType = web_sys::$web_sys_event;
#[inline(always)]
fn name(&self) -> Cow<'static, str> {
stringify!($event).into()
}
#[inline(always)]
fn event_delegation_key(&self) -> Cow<'static, str> {
concat!("$$$", stringify!($event)).into()
}
const BUBBLES: bool = true $(&& generate_event_types!($does_not_bubble))?;
$(
generate_event_types!($does_not_bubble);
)?
}
)*
};
(does_not_bubble) => { false }
(does_not_bubble) => {
fn bubbles(&self) -> bool { false }
}
}
generate_event_types! {

View File

@@ -97,7 +97,6 @@ impl AnimationFrameRequestHandle {
/// Runs the given function between the next repaint using
/// [`Window.requestAnimationFrame`](https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame).
#[cfg_attr(debug_assertions, instrument(level = "trace", skip_all))]
#[inline(always)]
pub fn request_animation_frame(cb: impl FnOnce() + 'static) {
_ = request_animation_frame_with_handle(cb);
}
@@ -106,7 +105,6 @@ pub fn request_animation_frame(cb: impl FnOnce() + 'static) {
/// [`Window.requestAnimationFrame`](https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame),
/// returning a cancelable handle.
#[cfg_attr(debug_assertions, instrument(level = "trace", skip_all))]
#[inline(always)]
pub fn request_animation_frame_with_handle(
cb: impl FnOnce() + 'static,
) -> Result<AnimationFrameRequestHandle, JsValue> {
@@ -120,14 +118,10 @@ pub fn request_animation_frame_with_handle(
}
}
#[inline(never)]
fn raf(cb: JsValue) -> Result<AnimationFrameRequestHandle, JsValue> {
window()
.request_animation_frame(cb.as_ref().unchecked_ref())
.map(AnimationFrameRequestHandle)
}
raf(Closure::once_into_js(cb))
let cb = Closure::once_into_js(cb);
window()
.request_animation_frame(cb.as_ref().unchecked_ref())
.map(AnimationFrameRequestHandle)
}
/// Handle that is generated by [request_idle_callback_with_handle] and can be
@@ -146,7 +140,6 @@ impl IdleCallbackHandle {
/// Queues the given function during an idle period using
/// [`Window.requestIdleCallback`](https://developer.mozilla.org/en-US/docs/Web/API/window/requestIdleCallback).
#[cfg_attr(debug_assertions, instrument(level = "trace", skip_all))]
#[inline(always)]
pub fn request_idle_callback(cb: impl Fn() + 'static) {
_ = request_idle_callback_with_handle(cb);
}
@@ -155,7 +148,6 @@ pub fn request_idle_callback(cb: impl Fn() + 'static) {
/// [`Window.requestIdleCallback`](https://developer.mozilla.org/en-US/docs/Web/API/window/requestIdleCallback),
/// returning a cancelable handle.
#[cfg_attr(debug_assertions, instrument(level = "trace", skip_all))]
#[inline(always)]
pub fn request_idle_callback_with_handle(
cb: impl Fn() + 'static,
) -> Result<IdleCallbackHandle, JsValue> {
@@ -169,16 +161,10 @@ pub fn request_idle_callback_with_handle(
}
}
#[inline(never)]
fn ric(cb: Box<dyn Fn()>) -> Result<IdleCallbackHandle, JsValue> {
let cb = Closure::wrap(cb).into_js_value();
window()
.request_idle_callback(cb.as_ref().unchecked_ref())
.map(IdleCallbackHandle)
}
ric(Box::new(cb))
let cb = Closure::wrap(Box::new(cb) as Box<dyn Fn()>).into_js_value();
window()
.request_idle_callback(cb.as_ref().unchecked_ref())
.map(IdleCallbackHandle)
}
/// Handle that is generated by [set_timeout_with_handle] and can be used to clear the timeout.
@@ -209,7 +195,6 @@ pub fn set_timeout(cb: impl FnOnce() + 'static, duration: Duration) {
debug_assertions,
instrument(level = "trace", skip_all, fields(duration = ?duration))
)]
#[inline(always)]
pub fn set_timeout_with_handle(
cb: impl FnOnce() + 'static,
duration: Duration,
@@ -226,17 +211,13 @@ pub fn set_timeout_with_handle(
}
}
#[inline(never)]
fn st(cb: JsValue, duration: Duration) -> Result<TimeoutHandle, JsValue> {
window()
.set_timeout_with_callback_and_timeout_and_arguments_0(
cb.as_ref().unchecked_ref(),
duration.as_millis().try_into().unwrap_throw(),
)
.map(TimeoutHandle)
}
st(Closure::once_into_js(cb), duration)
let cb = Closure::once_into_js(Box::new(cb) as Box<dyn FnOnce()>);
window()
.set_timeout_with_callback_and_timeout_and_arguments_0(
cb.as_ref().unchecked_ref(),
duration.as_millis().try_into().unwrap_throw(),
)
.map(TimeoutHandle)
}
/// "Debounce" a callback function. This will cause it to wait for a period of `delay`
@@ -262,8 +243,7 @@ pub fn set_timeout_with_handle(
pub fn debounce<T: 'static>(
cx: Scope,
delay: Duration,
#[cfg(debug_assertions)] mut cb: impl FnMut(T) + 'static,
#[cfg(not(debug_assertions))] cb: impl FnMut(T) + 'static,
#[allow(unused_mut)] mut cb: impl FnMut(T) + 'static,
) -> impl FnMut(T) {
use std::{
cell::{Cell, RefCell},
@@ -367,7 +347,6 @@ pub fn set_interval(
debug_assertions,
instrument(level = "trace", skip_all, fields(duration = ?duration))
)]
#[inline(always)]
pub fn set_interval_with_handle(
cb: impl Fn() + 'static,
duration: Duration,
@@ -384,22 +363,13 @@ pub fn set_interval_with_handle(
}
}
#[inline(never)]
fn si(
cb: Box<dyn Fn()>,
duration: Duration,
) -> Result<IntervalHandle, JsValue> {
let cb = Closure::wrap(cb).into_js_value();
window()
.set_interval_with_callback_and_timeout_and_arguments_0(
cb.as_ref().unchecked_ref(),
duration.as_millis().try_into().unwrap_throw(),
)
.map(IntervalHandle)
}
si(Box::new(cb), duration)
let cb = Closure::wrap(Box::new(cb) as Box<dyn Fn()>).into_js_value();
let handle = window()
.set_interval_with_callback_and_timeout_and_arguments_0(
cb.as_ref().unchecked_ref(),
duration.as_millis().try_into().unwrap_throw(),
)?;
Ok(IntervalHandle(handle))
}
/// Adds an event listener to the `Window`.
@@ -407,7 +377,6 @@ pub fn set_interval_with_handle(
debug_assertions,
instrument(level = "trace", skip_all, fields(event_name = %event_name))
)]
#[inline(always)]
pub fn window_event_listener(
event_name: &str,
cb: impl Fn(web_sys::Event) + 'static,
@@ -425,16 +394,11 @@ pub fn window_event_listener(
}
if !is_server() {
#[inline(never)]
fn wel(cb: Box<dyn FnMut(web_sys::Event)>, event_name: &str) {
let cb = Closure::wrap(cb).into_js_value();
_ = window().add_event_listener_with_callback(
event_name,
cb.unchecked_ref(),
);
}
let handler = Box::new(cb) as Box<dyn FnMut(web_sys::Event)>;
wel(Box::new(cb), event_name);
let cb = Closure::wrap(handler).into_js_value();
_ = window()
.add_event_listener_with_callback(event_name, cb.unchecked_ref());
}
}

View File

@@ -75,7 +75,6 @@ pub trait ElementDescriptor: ElementDescriptorBounds {
fn name(&self) -> Cow<'static, str>;
/// Determines if the tag is void, i.e., `<input>` and `<br>`.
#[inline(always)]
fn is_void(&self) -> bool {
false
}
@@ -141,7 +140,6 @@ pub struct AnyElement {
impl std::ops::Deref for AnyElement {
type Target = web_sys::HtmlElement;
#[inline(always)]
fn deref(&self) -> &Self::Target {
#[cfg(all(target_arch = "wasm32", feature = "web"))]
return &self.element;
@@ -152,7 +150,6 @@ impl std::ops::Deref for AnyElement {
}
impl std::convert::AsRef<web_sys::HtmlElement> for AnyElement {
#[inline(always)]
fn as_ref(&self) -> &web_sys::HtmlElement {
#[cfg(all(target_arch = "wasm32", feature = "web"))]
return &self.element;
@@ -167,13 +164,11 @@ impl ElementDescriptor for AnyElement {
self.name.clone()
}
#[inline(always)]
fn is_void(&self) -> bool {
self.is_void
}
#[cfg(not(all(target_arch = "wasm32", feature = "web")))]
#[inline(always)]
fn hydration_id(&self) -> &HydrationKey {
&self.id
}
@@ -259,7 +254,6 @@ impl Custom {
impl std::ops::Deref for Custom {
type Target = web_sys::HtmlElement;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.element
}
@@ -267,7 +261,6 @@ impl std::ops::Deref for Custom {
#[cfg(all(target_arch = "wasm32", feature = "web"))]
impl std::convert::AsRef<web_sys::HtmlElement> for Custom {
#[inline(always)]
fn as_ref(&self) -> &web_sys::HtmlElement {
&self.element
}
@@ -279,7 +272,6 @@ impl ElementDescriptor for Custom {
}
#[cfg(not(all(target_arch = "wasm32", feature = "web")))]
#[inline(always)]
fn hydration_id(&self) -> &HydrationKey {
&self.id
}
@@ -421,7 +413,6 @@ impl<El: ElementDescriptor + 'static> HtmlElement<El> {
#[cfg(debug_assertions)]
/// Adds an optional marker indicating the view macro source.
#[inline(always)]
pub fn with_view_marker(mut self, marker: impl Into<String>) -> Self {
self.view_marker = Some(marker.into());
self
@@ -480,18 +471,15 @@ impl<El: ElementDescriptor + 'static> HtmlElement<El> {
/// Adds an `id` to the element.
#[track_caller]
#[inline(always)]
pub fn id(self, id: impl Into<Cow<'static, str>>) -> Self {
let id = id.into();
#[cfg(all(target_arch = "wasm32", feature = "web"))]
{
#[inline(never)]
fn id_inner(el: &web_sys::HtmlElement, id: &str) {
el.set_attribute(wasm_bindgen::intern("id"), id).unwrap()
}
id_inner(self.element.as_ref(), &id);
self.element
.as_ref()
.set_attribute(wasm_bindgen::intern("id"), &id)
.unwrap();
self
}
@@ -507,7 +495,6 @@ impl<El: ElementDescriptor + 'static> HtmlElement<El> {
}
/// Binds the element reference to [`NodeRef`].
#[inline(always)]
pub fn node_ref(self, node_ref: NodeRef<El>) -> Self
where
Self: Clone,
@@ -590,16 +577,13 @@ impl<El: ElementDescriptor + 'static> HtmlElement<El> {
/// of `body`.
///
/// This method will always return [`None`] on non-wasm CSR targets.
#[inline(always)]
pub fn is_mounted(&self) -> bool {
#[cfg(all(target_arch = "wasm32", feature = "web"))]
{
#[inline(never)]
fn is_mounted_inner(el: &web_sys::HtmlElement) -> bool {
crate::document().body().unwrap().contains(Some(el))
}
is_mounted_inner(self.element.as_ref())
crate::document()
.body()
.unwrap()
.contains(Some(self.element.as_ref()))
}
#[cfg(not(all(target_arch = "wasm32", feature = "web")))]
@@ -608,7 +592,6 @@ impl<El: ElementDescriptor + 'static> HtmlElement<El> {
/// Adds an attribute to this element.
#[track_caller]
#[cfg_attr(all(target_arch = "wasm32", feature = "web"), inline(always))]
pub fn attr(
self,
name: impl Into<Cow<'static, str>>,
@@ -638,7 +621,7 @@ impl<El: ElementDescriptor + 'static> HtmlElement<El> {
}
match attr {
Attribute::String(value) => {
this.attrs.push((name, value));
this.attrs.push((name, value.into()));
}
Attribute::Bool(include) => {
if include {
@@ -647,7 +630,7 @@ impl<El: ElementDescriptor + 'static> HtmlElement<El> {
}
Attribute::Option(_, maybe) => {
if let Some(value) = maybe {
this.attrs.push((name, value));
this.attrs.push((name, value.into()));
}
}
_ => unreachable!(),
@@ -702,7 +685,10 @@ impl<El: ElementDescriptor + 'static> HtmlElement<El> {
}
}
fn classes_inner(self, classes: &str) -> Self {
/// Adds a list of classes separated by ASCII whitespace to an element.
#[track_caller]
pub fn classes(self, classes: impl Into<Cow<'static, str>>) -> Self {
let classes = classes.into();
let mut this = self;
for class in classes.split_ascii_whitespace() {
this = this.class(class.to_string(), true);
@@ -710,13 +696,6 @@ impl<El: ElementDescriptor + 'static> HtmlElement<El> {
this
}
/// Adds a list of classes separated by ASCII whitespace to an element.
#[track_caller]
#[inline(always)]
pub fn classes(self, classes: impl Into<Cow<'static, str>>) -> Self {
self.classes_inner(&classes.into())
}
/// Sets the class on the element as the class signal changes.
#[track_caller]
pub fn dyn_classes<I, C>(
@@ -841,7 +820,6 @@ impl<El: ElementDescriptor + 'static> HtmlElement<El> {
/// Adds an event listener to this element.
#[track_caller]
#[inline(always)]
pub fn on<E: EventDescriptor + 'static>(
self,
event: E,
@@ -864,9 +842,8 @@ impl<El: ElementDescriptor + 'static> HtmlElement<El> {
let event_name = event.name();
let key = event.event_delegation_key();
let event_handler = Box::new(event_handler);
if E::BUBBLES {
if event.bubbles() {
add_event_listener(
self.element.as_ref(),
key,
@@ -945,7 +922,6 @@ impl<El: ElementDescriptor + 'static> HtmlElement<El> {
/// Be very careful when using this method. Always remember to
/// sanitize the input to avoid a cross-site scripting (XSS)
/// vulnerability.
#[inline(always)]
pub fn inner_html(self, html: impl Into<Cow<'static, str>>) -> Self {
let html = html.into();
@@ -969,7 +945,6 @@ impl<El: ElementDescriptor + 'static> HtmlElement<El> {
impl<El: ElementDescriptor> IntoView for HtmlElement<El> {
#[cfg_attr(debug_assertions, instrument(level = "trace", name = "<HtmlElement />", skip_all, fields(tag = %self.element.name())))]
#[cfg_attr(all(target_arch = "wasm32", feature = "web"), inline(always))]
fn into_view(self, _: Scope) -> View {
#[cfg(all(target_arch = "wasm32", feature = "web"))]
{
@@ -1036,7 +1011,6 @@ pub fn custom<El: ElementDescriptor>(cx: Scope, el: El) -> HtmlElement<Custom> {
}
/// Creates a text node.
#[inline(always)]
pub fn text(text: impl Into<Cow<'static, str>>) -> Text {
Text::new(text.into())
}
@@ -1098,7 +1072,6 @@ macro_rules! generate_html_tags {
impl std::ops::Deref for [<$tag:camel $($trailing_)?>] {
type Target = web_sys::$el_type;
#[inline(always)]
fn deref(&self) -> &Self::Target {
#[cfg(all(target_arch = "wasm32", feature = "web"))]
{
@@ -1112,7 +1085,6 @@ macro_rules! generate_html_tags {
}
impl std::convert::AsRef<web_sys::HtmlElement> for [<$tag:camel $($trailing_)?>] {
#[inline(always)]
fn as_ref(&self) -> &web_sys::HtmlElement {
#[cfg(all(target_arch = "wasm32", feature = "web"))]
return &self.element;
@@ -1123,13 +1095,11 @@ macro_rules! generate_html_tags {
}
impl ElementDescriptor for [<$tag:camel $($trailing_)?>] {
#[inline(always)]
fn name(&self) -> Cow<'static, str> {
stringify!($tag).into()
}
#[cfg(not(all(target_arch = "wasm32", feature = "web")))]
#[inline(always)]
fn hydration_id(&self) -> &HydrationKey {
&self.id
}
@@ -1157,7 +1127,6 @@ macro_rules! generate_html_tags {
};
(@void) => {};
(@void void) => {
#[inline(always)]
fn is_void(&self) -> bool {
true
}

View File

@@ -137,7 +137,6 @@ impl<T> IntoView for (Scope, T)
where
T: IntoView,
{
#[inline(always)]
fn into_view(self, _: Scope) -> View {
self.1.into_view(self.0)
}
@@ -374,53 +373,48 @@ struct Comment {
}
impl Comment {
#[inline]
fn new(
content: impl Into<Cow<'static, str>>,
id: &HydrationKey,
closing: bool,
) -> Self {
Self::new_inner(content.into(), id, closing)
}
let content = content.into();
fn new_inner(
content: Cow<'static, str>,
id: &HydrationKey,
closing: bool,
) -> Self {
cfg_if! {
if #[cfg(not(all(target_arch = "wasm32", feature = "web")))] {
let _ = id;
let _ = closing;
#[cfg(not(all(target_arch = "wasm32", feature = "web")))]
{
let _ = id;
let _ = closing;
}
Self { content }
} else {
let node = COMMENT.with(|comment| comment.clone_node().unwrap());
#[cfg(all(target_arch = "wasm32", feature = "web"))]
let node = COMMENT.with(|comment| comment.clone_node().unwrap());
#[cfg(debug_assertions)]
node.set_text_content(Some(&format!(" {content} ")));
#[cfg(all(debug_assertions, target_arch = "wasm32", feature = "web"))]
node.set_text_content(Some(&format!(" {content} ")));
if HydrationCtx::is_hydrating() {
let id = HydrationCtx::to_string(id, closing);
#[cfg(all(target_arch = "wasm32", feature = "web"))]
{
if HydrationCtx::is_hydrating() {
let id = HydrationCtx::to_string(id, closing);
if let Some(marker) = hydration::get_marker(&id) {
marker.before_with_node_1(&node).unwrap();
if let Some(marker) = hydration::get_marker(&id) {
marker.before_with_node_1(&node).unwrap();
marker.remove();
} else {
crate::warn!(
"component with id {id} not found, ignoring it for \
hydration"
);
}
}
Self {
node,
content,
marker.remove();
} else {
crate::warn!(
"component with id {id} not found, ignoring it for \
hydration"
);
}
}
}
Self {
#[cfg(all(target_arch = "wasm32", feature = "web"))]
node,
content,
}
}
}
@@ -658,7 +652,6 @@ impl View {
///
/// This method will attach an event listener to **all** child
/// [`HtmlElement`] children.
#[inline(always)]
pub fn on<E: ev::EventDescriptor + 'static>(
self,
event: E,
@@ -687,7 +680,7 @@ impl View {
if #[cfg(all(target_arch = "wasm32", feature = "web"))] {
match &self {
Self::Element(el) => {
if E::BUBBLES {
if event.bubbles() {
add_event_listener(&el.element, event.event_delegation_key(), event.name(), event_handler, &None);
} else {
add_event_listener_undelegated(
@@ -926,7 +919,6 @@ macro_rules! impl_into_view_for_tuples {
where
$($ty: IntoView),*
{
#[inline]
fn into_view(self, cx: Scope) -> View {
paste::paste! {
let ($([<$ty:lower>],)*) = self;
@@ -1001,14 +993,12 @@ impl IntoView for String {
debug_assertions,
instrument(level = "trace", name = "#text", skip_all)
)]
#[inline(always)]
fn into_view(self, _: Scope) -> View {
View::Text(Text::new(self.into()))
}
}
impl IntoView for &'static str {
#[inline(always)]
fn into_view(self, _: Scope) -> View {
View::Text(Text::new(self.into()))
}
@@ -1030,7 +1020,6 @@ macro_rules! viewable_primitive {
($($child_type:ty),* $(,)?) => {
$(
impl IntoView for $child_type {
#[inline(always)]
fn into_view(self, _cx: Scope) -> View {
View::Text(Text::new(self.to_string().into()))
}

View File

@@ -1,5 +1,5 @@
use leptos_reactive::Scope;
use std::{borrow::Cow, rc::Rc};
use std::rc::Rc;
#[cfg(all(target_arch = "wasm32", feature = "web"))]
use wasm_bindgen::UnwrapThrowExt;
@@ -11,11 +11,11 @@ use wasm_bindgen::UnwrapThrowExt;
#[derive(Clone)]
pub enum Attribute {
/// A plain string value.
String(Cow<'static, str>),
String(String),
/// A (presumably reactive) function, which will be run inside an effect to do targeted updates to the attribute.
Fn(Scope, Rc<dyn Fn() -> Attribute>),
/// An optional string value, which sets the attribute to the value if `Some` and removes the attribute if `None`.
Option(Scope, Option<Cow<'static, str>>),
Option(Scope, Option<String>),
/// A boolean attribute, which sets the attribute if `true` and removes the attribute if `false`.
Bool(bool),
}
@@ -23,14 +23,9 @@ pub enum Attribute {
impl Attribute {
/// Converts the attribute to its HTML value at that moment, including the attribute name,
/// so it can be rendered on the server.
pub fn as_value_string(
&self,
attr_name: &'static str,
) -> Cow<'static, str> {
pub fn as_value_string(&self, attr_name: &'static str) -> String {
match self {
Attribute::String(value) => {
format!("{attr_name}=\"{value}\"").into()
}
Attribute::String(value) => format!("{attr_name}=\"{value}\""),
Attribute::Fn(_, f) => {
let mut value = f();
while let Attribute::Fn(_, f) = value {
@@ -40,19 +35,23 @@ impl Attribute {
}
Attribute::Option(_, value) => value
.as_ref()
.map(|value| format!("{attr_name}=\"{value}\"").into())
.map(|value| format!("{attr_name}=\"{value}\""))
.unwrap_or_default(),
Attribute::Bool(include) => {
Cow::Borrowed(if *include { attr_name } else { "" })
if *include {
attr_name.to_string()
} else {
String::new()
}
}
}
}
/// Converts the attribute to its HTML value at that moment, not including
/// the attribute name, so it can be rendered on the server.
pub fn as_nameless_value_string(&self) -> Option<Cow<'static, str>> {
pub fn as_nameless_value_string(&self) -> Option<String> {
match self {
Attribute::String(value) => Some(value.clone()),
Attribute::String(value) => Some(value.to_string()),
Attribute::Fn(_, f) => {
let mut value = f();
while let Attribute::Fn(_, f) = value {
@@ -60,10 +59,12 @@ impl Attribute {
}
value.as_nameless_value_string()
}
Attribute::Option(_, value) => value.as_ref().cloned(),
Attribute::Option(_, value) => {
value.as_ref().map(|value| value.to_string())
}
Attribute::Bool(include) => {
if *include {
Some("".into())
Some("".to_string())
} else {
None
}
@@ -108,19 +109,18 @@ pub trait IntoAttribute {
}
impl<T: IntoAttribute + 'static> From<T> for Box<dyn IntoAttribute> {
#[inline(always)]
fn from(value: T) -> Self {
Box::new(value)
}
}
impl IntoAttribute for Attribute {
#[inline(always)]
#[inline]
fn into_attribute(self, _: Scope) -> Attribute {
self
}
#[inline(always)]
#[inline]
fn into_attribute_boxed(self: Box<Self>, _: Scope) -> Attribute {
*self
}
@@ -128,7 +128,7 @@ impl IntoAttribute for Attribute {
macro_rules! impl_into_attr_boxed {
() => {
#[inline(always)]
#[inline]
fn into_attribute_boxed(self: Box<Self>, cx: Scope) -> Attribute {
self.into_attribute(cx)
}
@@ -136,7 +136,6 @@ macro_rules! impl_into_attr_boxed {
}
impl IntoAttribute for Option<Attribute> {
#[inline(always)]
fn into_attribute(self, cx: Scope) -> Attribute {
self.unwrap_or(Attribute::Option(cx, None))
}
@@ -145,25 +144,6 @@ impl IntoAttribute for Option<Attribute> {
}
impl IntoAttribute for String {
#[inline(always)]
fn into_attribute(self, _: Scope) -> Attribute {
Attribute::String(Cow::Owned(self))
}
impl_into_attr_boxed! {}
}
impl IntoAttribute for &'static str {
#[inline(always)]
fn into_attribute(self, _: Scope) -> Attribute {
Attribute::String(Cow::Borrowed(self))
}
impl_into_attr_boxed! {}
}
impl IntoAttribute for Cow<'static, str> {
#[inline(always)]
fn into_attribute(self, _: Scope) -> Attribute {
Attribute::String(self)
}
@@ -172,7 +152,6 @@ impl IntoAttribute for Cow<'static, str> {
}
impl IntoAttribute for bool {
#[inline(always)]
fn into_attribute(self, _: Scope) -> Attribute {
Attribute::Bool(self)
}
@@ -181,25 +160,6 @@ impl IntoAttribute for bool {
}
impl IntoAttribute for Option<String> {
#[inline(always)]
fn into_attribute(self, cx: Scope) -> Attribute {
Attribute::Option(cx, self.map(Cow::Owned))
}
impl_into_attr_boxed! {}
}
impl IntoAttribute for Option<&'static str> {
#[inline(always)]
fn into_attribute(self, cx: Scope) -> Attribute {
Attribute::Option(cx, self.map(Cow::Borrowed))
}
impl_into_attr_boxed! {}
}
impl IntoAttribute for Option<Cow<'static, str>> {
#[inline(always)]
fn into_attribute(self, cx: Scope) -> Attribute {
Attribute::Option(cx, self)
}
@@ -221,7 +181,6 @@ where
}
impl<T: IntoAttribute> IntoAttribute for (Scope, T) {
#[inline(always)]
fn into_attribute(self, _: Scope) -> Attribute {
self.1.into_attribute(self.0)
}
@@ -241,7 +200,6 @@ impl IntoAttribute for (Scope, Option<Box<dyn IntoAttribute>>) {
}
impl IntoAttribute for (Scope, Box<dyn IntoAttribute>) {
#[inline(always)]
fn into_attribute(self, _: Scope) -> Attribute {
self.1.into_attribute_boxed(self.0)
}
@@ -253,7 +211,7 @@ macro_rules! attr_type {
($attr_type:ty) => {
impl IntoAttribute for $attr_type {
fn into_attribute(self, _: Scope) -> Attribute {
Attribute::String(self.to_string().into())
Attribute::String(self.to_string())
}
#[inline]
@@ -264,7 +222,7 @@ macro_rules! attr_type {
impl IntoAttribute for Option<$attr_type> {
fn into_attribute(self, cx: Scope) -> Attribute {
Attribute::Option(cx, self.map(|n| n.to_string().into()))
Attribute::Option(cx, self.map(|n| n.to_string()))
}
#[inline]
@@ -276,6 +234,7 @@ macro_rules! attr_type {
}
attr_type!(&String);
attr_type!(&str);
attr_type!(usize);
attr_type!(u8);
attr_type!(u16);
@@ -292,9 +251,10 @@ attr_type!(f32);
attr_type!(f64);
attr_type!(char);
#[cfg(all(target_arch = "wasm32", feature = "web"))]
use std::borrow::Cow;
#[cfg(all(target_arch = "wasm32", feature = "web"))]
#[doc(hidden)]
#[inline(never)]
pub fn attribute_helper(
el: &web_sys::Element,
name: Cow<'static, str>,
@@ -317,7 +277,6 @@ pub fn attribute_helper(
}
#[cfg(all(target_arch = "wasm32", feature = "web"))]
#[inline(never)]
pub(crate) fn attribute_expression(
el: &web_sys::Element,
attr_name: &str,

View File

@@ -21,7 +21,6 @@ pub trait IntoClass {
}
impl IntoClass for bool {
#[inline(always)]
fn into_class(self, _cx: Scope) -> Class {
Class::Value(self)
}
@@ -31,7 +30,6 @@ impl<T> IntoClass for T
where
T: Fn() -> bool + 'static,
{
#[inline(always)]
fn into_class(self, cx: Scope) -> Class {
let modified_fn = Box::new(self);
Class::Fn(cx, modified_fn)
@@ -62,7 +60,6 @@ impl Class {
}
impl<T: IntoClass> IntoClass for (Scope, T) {
#[inline(always)]
fn into_class(self, _: Scope) -> Class {
self.1.into_class(self.0)
}
@@ -73,7 +70,6 @@ use std::borrow::Cow;
#[cfg(all(target_arch = "wasm32", feature = "web"))]
#[doc(hidden)]
#[inline(never)]
pub fn class_helper(
el: &web_sys::Element,
name: Cow<'static, str>,
@@ -99,7 +95,6 @@ pub fn class_helper(
}
#[cfg(all(target_arch = "wasm32", feature = "web"))]
#[inline(never)]
pub(crate) fn class_expression(
class_list: &web_sys::DomTokenList,
class_name: &str,

View File

@@ -36,7 +36,6 @@ where
}
impl<T: IntoProperty> IntoProperty for (Scope, T) {
#[inline(always)]
fn into_property(self, _: Scope) -> Property {
self.1.into_property(self.0)
}
@@ -45,14 +44,12 @@ impl<T: IntoProperty> IntoProperty for (Scope, T) {
macro_rules! prop_type {
($prop_type:ty) => {
impl IntoProperty for $prop_type {
#[inline(always)]
fn into_property(self, _cx: Scope) -> Property {
Property::Value(self.into())
}
}
impl IntoProperty for Option<$prop_type> {
#[inline(always)]
fn into_property(self, _cx: Scope) -> Property {
Property::Value(self.into())
}
@@ -84,7 +81,6 @@ prop_type!(bool);
use std::borrow::Cow;
#[cfg(all(target_arch = "wasm32", feature = "web"))]
#[inline(never)]
pub(crate) fn property_helper(
el: &web_sys::Element,
name: Cow<'static, str>,
@@ -110,7 +106,6 @@ pub(crate) fn property_helper(
}
#[cfg(all(target_arch = "wasm32", feature = "web"))]
#[inline(never)]
pub(crate) fn property_expression(
el: &web_sys::Element,
prop_name: &str,

View File

@@ -35,7 +35,6 @@ use std::cell::Cell;
/// }
/// }
/// ```
#[repr(transparent)]
pub struct NodeRef<T: ElementDescriptor + 'static>(
RwSignal<Option<HtmlElement<T>>>,
);
@@ -71,7 +70,6 @@ pub struct NodeRef<T: ElementDescriptor + 'static>(
/// }
/// }
/// ```
#[inline(always)]
pub fn create_node_ref<T: ElementDescriptor + 'static>(
cx: Scope,
) -> NodeRef<T> {
@@ -91,7 +89,6 @@ impl<T: ElementDescriptor + 'static> NodeRef<T> {
/// Initially, the value will be `None`, but once it is loaded the effect
/// will rerun and its value will be `Some(Element)`.
#[track_caller]
#[inline(always)]
pub fn get(&self) -> Option<HtmlElement<T>>
where
T: Clone,
@@ -99,18 +96,6 @@ impl<T: ElementDescriptor + 'static> NodeRef<T> {
self.0.get()
}
/// Gets the element that is currently stored in the reference.
///
/// This **does not** track reactively.
#[track_caller]
#[inline(always)]
pub fn get_untracked(&self) -> Option<HtmlElement<T>>
where
T: Clone,
{
self.0.get_untracked()
}
#[doc(hidden)]
/// Loads an element into the reference. This tracks reactively,
/// so that effects that use the node reference will rerun once it is loaded,
@@ -135,7 +120,6 @@ impl<T: ElementDescriptor + 'static> NodeRef<T> {
/// Runs the provided closure when the `NodeRef` has been connected
/// with it's [`HtmlElement`].
#[inline(always)]
pub fn on_load<F>(self, cx: Scope, f: F)
where
T: Clone,
@@ -164,21 +148,18 @@ cfg_if::cfg_if! {
impl<T: Clone + ElementDescriptor + 'static> FnOnce<()> for NodeRef<T> {
type Output = Option<HtmlElement<T>>;
#[inline(always)]
extern "rust-call" fn call_once(self, _args: ()) -> Self::Output {
self.get()
}
}
impl<T: Clone + ElementDescriptor + 'static> FnMut<()> for NodeRef<T> {
#[inline(always)]
extern "rust-call" fn call_mut(&mut self, _args: ()) -> Self::Output {
self.get()
}
}
impl<T: Clone + ElementDescriptor + Clone + 'static> Fn<()> for NodeRef<T> {
#[inline(always)]
extern "rust-call" fn call(&self, _args: ()) -> Self::Output {
self.get()
}

View File

@@ -244,28 +244,19 @@ fn fragments_to_chunks(
impl View {
/// Consumes the node and renders it into an HTML string.
pub fn render_to_string(self, _cx: Scope) -> Cow<'static, str> {
self.render_to_string_helper(false)
self.render_to_string_helper()
}
pub(crate) fn render_to_string_helper(
self,
dont_escape_text: bool,
) -> Cow<'static, str> {
pub(crate) fn render_to_string_helper(self) -> Cow<'static, str> {
match self {
View::Text(node) => {
if dont_escape_text {
node.content
} else {
html_escape::encode_safe(&node.content).to_string().into()
}
html_escape::encode_safe(&node.content).to_string().into()
}
View::Component(node) => {
let content = || {
node.children
.into_iter()
.map(|node| {
node.render_to_string_helper(dont_escape_text)
})
.map(|node| node.render_to_string_helper())
.join("")
};
cfg_if! {
@@ -292,8 +283,7 @@ impl View {
}
View::Suspense(id, node) => format!(
"<!--suspense-open-{id}-->{}<!--suspense-close-{id}-->",
View::CoreComponent(node)
.render_to_string_helper(dont_escape_text)
View::CoreComponent(node).render_to_string_helper()
)
.into(),
View::CoreComponent(node) => {
@@ -343,9 +333,7 @@ impl View {
t.content
}
} else {
child.render_to_string_helper(
dont_escape_text,
)
child.render_to_string_helper()
}
} else {
"".into()
@@ -368,9 +356,7 @@ impl View {
let id = node.id;
let content = || {
node.child.render_to_string_helper(
dont_escape_text,
)
node.child.render_to_string_helper()
};
#[cfg(debug_assertions)]
@@ -423,8 +409,6 @@ impl View {
}
}
View::Element(el) => {
let is_script_or_style =
el.name == "script" || el.name == "style";
let el_html = if let ElementChildren::Chunks(chunks) =
el.children
{
@@ -432,8 +416,9 @@ impl View {
.into_iter()
.map(|chunk| match chunk {
StringOrView::String(string) => string,
StringOrView::View(view) => view()
.render_to_string_helper(is_script_or_style),
StringOrView::View(view) => {
view().render_to_string_helper()
}
})
.join("")
.into()
@@ -475,11 +460,7 @@ impl View {
ElementChildren::Empty => "".into(),
ElementChildren::Children(c) => c
.into_iter()
.map(|v| {
v.render_to_string_helper(
is_script_or_style,
)
})
.map(View::render_to_string_helper)
.join("")
.into(),
ElementChildren::InnerHtml(h) => h,

View File

@@ -213,7 +213,7 @@ impl View {
/// Renders the view into a set of HTML chunks that can be streamed.
pub fn into_stream_chunks(self, cx: Scope) -> VecDeque<StreamChunk> {
let mut chunks = VecDeque::new();
self.into_stream_chunks_helper(cx, &mut chunks, false);
self.into_stream_chunks_helper(cx, &mut chunks);
chunks
}
@@ -221,7 +221,6 @@ impl View {
self,
cx: Scope,
chunks: &mut VecDeque<StreamChunk>,
dont_escape_text: bool,
) {
match self {
View::Suspense(id, _) => {
@@ -242,21 +241,18 @@ impl View {
let name = crate::ssr::to_kebab_case(&node.name);
chunks.push_back(StreamChunk::Sync(format!(r#"<!--hk={}|leptos-{name}-start-->"#, HydrationCtx::to_string(&node.id, false)).into()));
for child in node.children {
child.into_stream_chunks_helper(cx, chunks, dont_escape_text);
child.into_stream_chunks_helper(cx, chunks);
}
chunks.push_back(StreamChunk::Sync(format!(r#"<!--hk={}|leptos-{name}-end-->"#, HydrationCtx::to_string(&node.id, true)).into()));
} else {
for child in node.children {
child.into_stream_chunks_helper(cx, chunks, dont_escape_text);
child.into_stream_chunks_helper(cx, chunks);
}
chunks.push_back(StreamChunk::Sync(format!(r#"<!--hk={}-->"#, HydrationCtx::to_string(&node.id, true)).into()))
}
}
}
View::Element(el) => {
let is_script_or_style =
el.name == "script" || el.name == "style";
#[cfg(debug_assertions)]
if let Some(id) = &el.view_marker {
chunks.push_back(StreamChunk::Sync(
@@ -270,11 +266,7 @@ impl View {
chunks.push_back(StreamChunk::Sync(string))
}
StringOrView::View(view) => {
view().into_stream_chunks_helper(
cx,
chunks,
is_script_or_style,
);
view().into_stream_chunks_helper(cx, chunks);
}
}
}
@@ -326,11 +318,7 @@ impl View {
ElementChildren::Empty => {}
ElementChildren::Children(children) => {
for child in children {
child.into_stream_chunks_helper(
cx,
chunks,
is_script_or_style,
);
child.into_stream_chunks_helper(cx, chunks);
}
}
ElementChildren::InnerHtml(inner_html) => {
@@ -399,33 +387,22 @@ impl View {
// into one single node, so we need to artificially make the
// browser create the dynamic text as it's own text node
if let View::Text(t) = child {
let content = if dont_escape_text {
t.content
} else {
html_escape::encode_safe(
&t.content,
)
.to_string()
.into()
};
chunks.push_back(
if !cfg!(debug_assertions) {
StreamChunk::Sync(
format!(
"<!>{}",
content
html_escape::encode_safe(&t.content)
)
.into(),
)
} else {
StreamChunk::Sync(content)
StreamChunk::Sync(html_escape::encode_safe(&t.content).to_string().into())
},
);
} else {
child.into_stream_chunks_helper(
cx,
chunks,
dont_escape_text,
cx, chunks,
);
}
}
@@ -458,9 +435,7 @@ impl View {
);
node.child
.into_stream_chunks_helper(
cx,
chunks,
dont_escape_text,
cx, chunks,
);
chunks.push_back(
StreamChunk::Sync(
@@ -472,26 +447,6 @@ impl View {
),
);
}
#[cfg(not(debug_assertions))]
{
node.child
.into_stream_chunks_helper(
cx,
chunks,
dont_escape_text,
);
chunks.push_back(
StreamChunk::Sync(
format!(
"<!--hk={}-->",
HydrationCtx::to_string(
&id, true
)
)
.into(),
),
);
}
}
},
)

View File

@@ -4,12 +4,10 @@ use std::{any::Any, fmt, rc::Rc};
/// Wrapper for arbitrary data that can be passed through the view.
#[derive(Clone)]
#[repr(transparent)]
pub struct Transparent(Rc<dyn Any>);
impl Transparent {
/// Creates a new wrapper for this data.
#[inline(always)]
pub fn new<T>(value: T) -> Self
where
T: 'static,
@@ -18,7 +16,6 @@ impl Transparent {
}
/// Returns some reference to the inner value if it is of type `T`, or `None` if it isn't.
#[inline(always)]
pub fn downcast_ref<T>(&self) -> Option<&T>
where
T: 'static,
@@ -34,7 +31,6 @@ impl fmt::Debug for Transparent {
}
impl PartialEq for Transparent {
#[inline(always)]
fn eq(&self, other: &Self) -> bool {
std::ptr::eq(&self.0, &other.0)
}
@@ -43,7 +39,6 @@ impl PartialEq for Transparent {
impl Eq for Transparent {}
impl IntoView for Transparent {
#[inline(always)]
fn into_view(self, _: Scope) -> View {
View::Transparent(self)
}

View File

@@ -393,7 +393,6 @@ fn element_to_tokens_ssr(
.to_string()
.replace("svg::", "")
.replace("math::", "");
let is_script_or_style = tag_name == "script" || tag_name == "style";
template.push('<');
template.push_str(&tag_name);
@@ -407,7 +406,6 @@ fn element_to_tokens_ssr(
template,
holes,
exprs_for_compiler,
global_class,
);
}
}
@@ -463,16 +461,9 @@ fn element_to_tokens_ssr(
}
Node::Text(text) => {
if let Some(value) = value_to_string(&text.value) {
let value = if is_script_or_style {
value.into()
} else {
html_escape::encode_safe(&value)
};
template.push_str(
&value
.replace('{', "{{")
.replace('}', "}}"),
);
template.push_str(&html_escape::encode_safe(
&value,
));
} else {
template.push_str("{}");
let value = text.value.as_ref();
@@ -522,17 +513,14 @@ fn attribute_to_tokens_ssr<'a>(
template: &mut String,
holes: &mut Vec<TokenStream>,
exprs_for_compiler: &mut Vec<TokenStream>,
global_class: Option<&TokenTree>,
) -> Option<&'a NodeValueExpr> {
let name = node.key.to_string();
if name == "ref" || name == "_ref" || name == "ref_" || name == "node_ref" {
// ignore refs on SSR
} else if let Some(name) = name.strip_prefix("on:") {
let handler = attribute_value(node);
let (event_type, _, _) = parse_event_name(name);
} else if name.strip_prefix("on:").is_some() {
let (event_type, handler) = event_from_attribute_node(node, false);
exprs_for_compiler.push(quote! {
leptos::leptos_dom::helpers::ssr_event_listener(::leptos::ev::#event_type, #handler);
leptos::leptos_dom::helpers::ssr_event_listener(#event_type, #handler);
})
} else if name.strip_prefix("prop:").is_some()
|| name.strip_prefix("class:").is_some()
@@ -544,18 +532,6 @@ fn attribute_to_tokens_ssr<'a>(
} else {
let name = name.replacen("attr:", "", 1);
// special case of global_class and class attribute
if name == "class"
&& global_class.is_some()
&& node.value.as_ref().and_then(value_to_string).is_none()
{
let span = node.key.span();
proc_macro_error::emit_error!(span, "Combining a global class (view! { cx, class = ... }) \
and a dynamic `class=` attribute on an element causes runtime inconsistencies. You can \
toggle individual classes dynamically with the `class:name=value` syntax. \n\nSee this issue \
for more information and an example: https://github.com/leptos-rs/leptos/issues/773")
};
if name != "class" {
template.push(' ');
@@ -787,7 +763,7 @@ fn node_to_tokens(
let value = node.value.as_ref();
quote! { #value }
}
Node::Attribute(node) => attribute_to_tokens(cx, node, global_class),
Node::Attribute(node) => attribute_to_tokens(cx, node),
Node::Element(node) => {
element_to_tokens(cx, node, parent_type, global_class, view_marker)
}
@@ -845,7 +821,7 @@ fn element_to_tokens(
if node.key.to_string().trim().starts_with("class:") {
None
} else {
Some(attribute_to_tokens(cx, node, global_class))
Some(attribute_to_tokens(cx, node))
}
} else {
None
@@ -854,7 +830,7 @@ fn element_to_tokens(
let class_attrs = node.attributes.iter().filter_map(|node| {
if let Node::Attribute(node) = node {
if node.key.to_string().trim().starts_with("class:") {
Some(attribute_to_tokens(cx, node, global_class))
Some(attribute_to_tokens(cx, node))
} else {
None
}
@@ -874,67 +850,37 @@ fn element_to_tokens(
}
};
let children = node.children.iter().map(|node| {
let (child, is_static) = match node {
Node::Fragment(fragment) => (
fragment_to_tokens(
cx,
Span::call_site(),
&fragment.children,
true,
parent_type,
global_class,
None,
),
false,
let child = match node {
Node::Fragment(fragment) => fragment_to_tokens(
cx,
Span::call_site(),
&fragment.children,
true,
parent_type,
global_class,
None,
),
Node::Text(node) => {
if let Some(primitive) = value_to_string(&node.value) {
(quote! { #primitive }, true)
} else {
let value = node.value.as_ref();
(
quote! {
#[allow(unused_braces)] #value
},
false,
)
let value = node.value.as_ref();
quote! {
#[allow(unused_braces)] #value
}
}
Node::Block(node) => {
if let Some(primitive) = value_to_string(&node.value) {
(quote! { #primitive }, true)
} else {
let value = node.value.as_ref();
(
quote! {
#[allow(unused_braces)] #value
},
false,
)
let value = node.value.as_ref();
quote! {
#[allow(unused_braces)] #value
}
}
Node::Element(node) => (
element_to_tokens(
cx,
node,
parent_type,
global_class,
None,
),
false,
),
Node::Element(node) => {
element_to_tokens(cx, node, parent_type, global_class, None)
}
Node::Comment(_) | Node::Doctype(_) | Node::Attribute(_) => {
(quote! {}, false)
quote! {}
}
};
if is_static {
quote! {
.child(#child)
}
} else {
quote! {
.child((#cx, #child))
}
quote! {
.child((#cx, #child))
}
});
let view_marker = if let Some(marker) = view_marker {
@@ -953,11 +899,7 @@ fn element_to_tokens(
}
}
fn attribute_to_tokens(
cx: &Ident,
node: &NodeAttribute,
global_class: Option<&TokenTree>,
) -> TokenStream {
fn attribute_to_tokens(cx: &Ident, node: &NodeAttribute) -> TokenStream {
let span = node.key.span();
let name = node.key.to_string();
if name == "ref" || name == "_ref" || name == "ref_" || name == "node_ref" {
@@ -969,9 +911,24 @@ fn attribute_to_tokens(
}
} else if let Some(name) = name.strip_prefix("on:") {
let handler = attribute_value(node);
let (name, is_force_undelegated) = parse_event(name);
let (event_type, is_custom, is_force_undelegated) =
parse_event_name(name);
let event_type = TYPED_EVENTS
.iter()
.find(|e| **e == name)
.copied()
.unwrap_or("Custom");
let is_custom = event_type == "Custom";
let Ok(event_type) = event_type.parse::<TokenStream>() else {
abort!(event_type, "couldn't parse event name");
};
let event_type = if is_custom {
quote! { Custom::new(#name) }
} else {
event_type
};
let event_name_ident = match &node.key {
NodeName::Punctuated(parts) => {
@@ -1068,18 +1025,6 @@ fn attribute_to_tokens(
return fancy;
}
// special case of global_class and class attribute
if name == "class"
&& global_class.is_some()
&& node.value.as_ref().and_then(value_to_string).is_none()
{
let span = node.key.span();
proc_macro_error::emit_error!(span, "Combining a global class (view! { cx, class = ... }) \
and a dynamic `class=` attribute on an element causes runtime inconsistencies. You can \
toggle individual classes dynamically with the `class:name=value` syntax. \n\nSee this issue \
for more information and an example: https://github.com/leptos-rs/leptos/issues/773")
};
// all other attributes
let value = match node.value.as_ref() {
Some(value) => {
@@ -1089,7 +1034,6 @@ fn attribute_to_tokens(
}
None => quote_spanned! { span => "" },
};
let attr = match &node.key {
NodeName::Punctuated(parts) => Some(&parts[0]),
_ => None,
@@ -1110,28 +1054,6 @@ fn attribute_to_tokens(
}
}
pub(crate) fn parse_event_name(name: &str) -> (TokenStream, bool, bool) {
let (name, is_force_undelegated) = parse_event(name);
let event_type = TYPED_EVENTS
.iter()
.find(|e| **e == name)
.copied()
.unwrap_or("Custom");
let is_custom = event_type == "Custom";
let Ok(event_type) = event_type.parse::<TokenStream>() else {
abort!(event_type, "couldn't parse event name");
};
let event_type = if is_custom {
quote! { Custom::new(#name) }
} else {
event_type
};
(event_type, is_custom, is_force_undelegated)
}
pub(crate) fn component_to_tokens(
cx: &Ident,
node: &NodeElement,

View File

@@ -3,8 +3,8 @@
use crate::{runtime::with_runtime, Scope};
use std::any::{Any, TypeId};
/// Provides a context value of type `T` to the current reactive [`Scope`](crate::Scope)
/// and all of its descendants. This can be consumed using [`use_context`](crate::use_context).
/// Provides a context value of type `T` to the current reactive [Scope](crate::Scope)
/// and all of its descendants. This can be consumed using [use_context](crate::use_context).
///
/// This is useful for passing values down to components or functions lower in a
/// hierarchy without needs to “prop drill” by passing them through each layer as
@@ -27,7 +27,7 @@ use std::any::{Any, TypeId};
/// #[component]
/// pub fn Provider(cx: Scope) -> impl IntoView {
/// let (value, set_value) = create_signal(cx, 0);
///
///
/// // the newtype pattern isn't *necessary* here but is a good practice
/// // it avoids confusion with other possible future `WriteSignal<bool>` contexts
/// // and makes it easier to refer to it in ButtonD
@@ -61,9 +61,9 @@ where
}
/// Extracts a context value of type `T` from the reactive system by traversing
/// it upwards, beginning from the current [`Scope`](crate::Scope) and iterating
/// it upwards, beginning from the current [Scope](crate::Scope) and iterating
/// through its parents, if any. The context value should have been provided elsewhere
/// using [`provide_context`](crate::provide_context).
/// using [provide_context](crate::provide_context).
///
/// This is useful for passing values down to components or functions lower in a
/// hierarchy without needs to “prop drill” by passing them through each layer as
@@ -86,7 +86,7 @@ where
/// #[component]
/// pub fn Provider(cx: Scope) -> impl IntoView {
/// let (value, set_value) = create_signal(cx, 0);
///
///
/// // the newtype pattern isn't *necessary* here but is a good practice
/// // it avoids confusion with other possible future `WriteSignal<bool>` contexts
/// // and makes it easier to refer to it in ButtonD
@@ -140,61 +140,3 @@ where
.ok()
.flatten()
}
/// Extracts a context value of type `T` from the reactive system by traversing
/// it upwards, beginning from the current [Scope](crate::Scope) and iterating
/// through its parents, if any. The context value should have been provided elsewhere
/// using [provide_context](crate::provide_context).
///
/// This is useful for passing values down to components or functions lower in a
/// hierarchy without needs to “prop drill” by passing them through each layer as
/// arguments to a function or properties of a component.
///
/// Context works similarly to variable scope: a context that is provided higher in
/// the component tree can be used lower down, but a context that is provided lower
/// in the tree cannot be used higher up.
///
/// ```
/// use leptos::*;
///
/// // define a newtype we'll provide as context
/// // contexts are stored by their types, so it can be useful to create
/// // a new type to avoid confusion with other `WriteSignal<i32>`s we may have
/// // all types to be shared via context should implement `Clone`
/// #[derive(Copy, Clone)]
/// struct ValueSetter(WriteSignal<i32>);
///
/// #[component]
/// pub fn Provider(cx: Scope) -> impl IntoView {
/// let (value, set_value) = create_signal(cx, 0);
///
/// // the newtype pattern isn't *necessary* here but is a good practice
/// // it avoids confusion with other possible future `WriteSignal<bool>` contexts
/// // and makes it easier to refer to it in ButtonD
/// provide_context(cx, ValueSetter(set_value));
///
/// // because <Consumer/> is nested inside <Provider/>,
/// // it has access to the provided context
/// view! { cx, <div><Consumer/></div> }
/// }
///
/// #[component]
/// pub fn Consumer(cx: Scope) -> impl IntoView {
/// // consume the provided context of type `ValueSetter` using `use_context`
/// // this traverses up the tree of `Scope`s and gets the nearest provided `ValueSetter`
/// let set_value = expect_context::<ValueSetter>(cx).0;
///
/// todo!()
/// }
/// ```
pub fn expect_context<T>(cx: Scope) -> T
where
T: Clone + 'static,
{
use_context(cx).unwrap_or_else(|| {
panic!(
"context of type {:?} to be present",
std::any::type_name::<T>()
)
})
}

View File

@@ -1,3 +1,5 @@
use cfg_if::cfg_if;
// The point of these diagnostics is to give useful error messages when someone
// tries to access a reactive variable outside the reactive scope. They track when
// you create a signal/memo, and where you access it non-reactively.
@@ -21,7 +23,7 @@ pub(crate) struct AccessDiagnostics {}
#[doc(hidden)]
pub struct SpecialNonReactiveZone {}
cfg_if::cfg_if! {
cfg_if! {
if #[cfg(debug_assertions)] {
use std::cell::Cell;
@@ -33,7 +35,6 @@ cfg_if::cfg_if! {
impl SpecialNonReactiveZone {
#[allow(dead_code)] // allowed for SSR
#[inline(always)]
pub(crate) fn is_inside() -> bool {
#[cfg(debug_assertions)]
{
@@ -43,7 +44,6 @@ impl SpecialNonReactiveZone {
false
}
#[inline(always)]
pub fn enter() {
#[cfg(debug_assertions)]
{
@@ -51,7 +51,6 @@ impl SpecialNonReactiveZone {
}
}
#[inline(always)]
pub fn exit() {
#[cfg(debug_assertions)]
{
@@ -64,7 +63,7 @@ impl SpecialNonReactiveZone {
#[macro_export]
macro_rules! diagnostics {
($this:ident) => {{
cfg_if::cfg_if! {
cfg_if! {
if #[cfg(debug_assertions)] {
AccessDiagnostics {
defined_at: $this.defined_at,

View File

@@ -11,14 +11,14 @@ use std::{any::Any, cell::RefCell, marker::PhantomData, rc::Rc};
/// Effects are intended to run *side-effects* of the system, not to synchronize state
/// *within* the system. In other words: don't write to signals within effects.
/// (If you need to define a signal that depends on the value of other signals, use a
/// derived signal or [`create_memo`](crate::create_memo)).
/// derived signal or [create_memo](crate::create_memo)).
///
/// The effect function is called with an argument containing whatever value it returned
/// the last time it ran. On the initial run, this is `None`.
///
/// By default, effects **do not run on the server**. This means you can call browser-specific
/// APIs within the effect function without causing issues. If you need an effect to run on
/// the server, use [`create_isomorphic_effect`].
/// the server, use [create_isomorphic_effect].
/// ```
/// # use leptos_reactive::*;
/// # use log::*;
@@ -58,7 +58,6 @@ use std::{any::Any, cell::RefCell, marker::PhantomData, rc::Rc};
)
)]
#[track_caller]
#[inline(always)]
pub fn create_effect<T>(cx: Scope, f: impl Fn(Option<T>) -> T + 'static)
where
T: 'static,
@@ -67,7 +66,7 @@ where
if #[cfg(not(feature = "ssr"))] {
let e = cx.runtime.create_effect(f);
//eprintln!("created effect {e:?}");
cx.push_scope_property(ScopeProperty::Effect(e))
cx.with_scope_property(|prop| prop.push(ScopeProperty::Effect(e)))
} else {
// clear warnings
_ = cx;
@@ -76,7 +75,7 @@ where
}
}
/// Creates an effect; unlike effects created by [`create_effect`], isomorphic effects will run on
/// Creates an effect; unlike effects created by [create_effect], isomorphic effects will run on
/// the server as well as the client.
/// ```
/// # use leptos_reactive::*;
@@ -114,7 +113,6 @@ where
)
)]
#[track_caller]
#[inline(always)]
pub fn create_isomorphic_effect<T>(
cx: Scope,
f: impl Fn(Option<T>) -> T + 'static,
@@ -123,7 +121,7 @@ pub fn create_isomorphic_effect<T>(
{
let e = cx.runtime.create_effect(f);
//eprintln!("created effect {e:?}");
cx.push_scope_property(ScopeProperty::Effect(e))
cx.with_scope_property(|prop| prop.push(ScopeProperty::Effect(e)))
}
#[doc(hidden)]
@@ -138,7 +136,6 @@ pub fn create_isomorphic_effect<T>(
)
)
)]
#[inline(always)]
pub fn create_render_effect<T>(cx: Scope, f: impl Fn(Option<T>) -> T + 'static)
where
T: 'static,

View File

@@ -17,19 +17,18 @@
//! Here are the most commonly-used functions and types you'll need to build a reactive system:
//!
//! ### Signals
//! 1. *Signals:* [`create_signal`](crate::create_signal), which returns a ([`ReadSignal`](crate::ReadSignal),
//! [`WriteSignal`](crate::WriteSignal)) tuple, or [`create_rw_signal`](crate::create_rw_signal), which returns
//! a signal [`RwSignal`](crate::RwSignal) without this read-write segregation.
//! 1. *Signals:* [create_signal](crate::create_signal), which returns a ([ReadSignal](crate::ReadSignal),
//! [WriteSignal](crate::WriteSignal)) tuple, or [create_rw_signal](crate::create_rw_signal), which returns
//! a signal [RwSignal](crate::RwSignal) without this read-write segregation.
//! 2. *Derived Signals:* any function that relies on another signal.
//! 3. *Memos:* [`create_memo`], which returns a [`Memo`](crate::Memo).
//! 4. *Resources:* [`create_resource`], which converts an `async` [`Future`](std::future::Future) into a
//! synchronous [`Resource`](crate::Resource) signal.
//! 5. *Triggers:* [`create_trigger`], creates a purely reactive [`Trigger`] primitive without any associated state.
//! 3. *Memos:* [create_memo](crate::create_memo), which returns a [Memo](crate::Memo).
//! 4. *Resources:* [create_resource], which converts an `async` [std::future::Future] into a
//! synchronous [Resource](crate::Resource) signal.
//!
//! ### Effects
//! 1. Use [`create_effect`](crate::create_effect) when you need to synchronize the reactive system
//! 1. Use [create_effect](crate::create_effect) when you need to synchronize the reactive system
//! with something outside it (for example: logging to the console, writing to a file or local storage)
//! 2. The Leptos DOM renderer wraps any [`Fn`] in your template with [`create_effect`](crate::create_effect), so
//! 2. The Leptos DOM renderer wraps any [Fn] in your template with [create_effect](crate::create_effect), so
//! components you write do *not* need explicit effects to synchronize with the DOM.
//!
//! ### Example
@@ -91,7 +90,6 @@ mod spawn;
mod spawn_microtask;
mod stored_value;
pub mod suspense;
mod trigger;
pub use context::*;
pub use diagnostics::SpecialNonReactiveZone;
@@ -111,7 +109,6 @@ pub use spawn::*;
pub use spawn_microtask::*;
pub use stored_value::*;
pub use suspense::SuspenseContext;
pub use trigger::*;
mod macros {
macro_rules! debug_warn {

View File

@@ -1,10 +1,10 @@
#![forbid(unsafe_code)]
use crate::{
create_effect, diagnostics::AccessDiagnostics, node::NodeId, on_cleanup,
with_runtime, AnyComputation, RuntimeId, Scope, ScopeProperty,
SignalDispose, SignalGet, SignalGetUntracked, SignalStream, SignalWith,
SignalWithUntracked,
with_runtime, AnyComputation, RuntimeId, Scope, SignalDispose, SignalGet,
SignalGetUntracked, SignalStream, SignalWith, SignalWithUntracked,
};
use cfg_if::cfg_if;
use std::{any::Any, cell::RefCell, fmt::Debug, marker::PhantomData, rc::Rc};
/// Creates an efficient derived reactive value based on other reactive values.
@@ -20,7 +20,7 @@ use std::{any::Any, cell::RefCell, fmt::Debug, marker::PhantomData, rc::Rc};
/// create a derived signal. But if the derivation calculation is expensive, you should
/// create a memo.
///
/// As with [`create_effect`](crate::create_effect), the argument to the memo function is the previous value,
/// As with [create_effect](crate::create_effect), the argument to the memo function is the previous value,
/// i.e., the current value of the memo, which will be `None` for the initial calculation.
///
/// ```
@@ -72,7 +72,6 @@ use std::{any::Any, cell::RefCell, fmt::Debug, marker::PhantomData, rc::Rc};
)
)]
#[track_caller]
#[inline(always)]
pub fn create_memo<T>(
cx: Scope,
f: impl Fn(Option<&T>) -> T + 'static,
@@ -80,9 +79,7 @@ pub fn create_memo<T>(
where
T: PartialEq + 'static,
{
let memo = cx.runtime.create_memo(f);
cx.push_scope_property(ScopeProperty::Effect(memo.id));
memo
cx.runtime.create_memo(f)
}
/// An efficient derived reactive value based on other reactive values.
@@ -98,7 +95,7 @@ where
/// create a derived signal. But if the derivation calculation is expensive, you should
/// create a memo.
///
/// As with [`create_effect`](crate::create_effect), the argument to the memo function is the previous value,
/// As with [create_effect](crate::create_effect), the argument to the memo function is the previous value,
/// i.e., the current value of the memo, which will be `None` for the initial calculation.
///
/// ## Core Trait Implementations
@@ -221,9 +218,12 @@ impl<T: Clone> SignalGetUntracked<T> for Memo<T> {
)
)
)]
#[inline(always)]
fn try_get_untracked(&self) -> Option<T> {
self.try_with_untracked(T::clone)
with_runtime(self.runtime, move |runtime| {
self.id.try_with_no_subscription(runtime, T::clone).ok()
})
.ok()
.flatten()
}
}
@@ -269,7 +269,6 @@ impl<T> SignalWithUntracked<T> for Memo<T> {
)
)
)]
#[inline]
fn try_with_untracked<O>(&self, f: impl FnOnce(&T) -> O) -> Option<O> {
with_runtime(self.runtime, |runtime| {
self.id.try_with_no_subscription(runtime, |v: &T| f(v)).ok()
@@ -310,7 +309,6 @@ impl<T: Clone> SignalGet<T> for Memo<T> {
)
)]
#[track_caller]
#[inline(always)]
fn get(&self) -> T {
self.with(T::clone)
}
@@ -329,7 +327,6 @@ impl<T: Clone> SignalGet<T> for Memo<T> {
)
)]
#[track_caller]
#[inline(always)]
fn try_get(&self) -> Option<T> {
self.try_with(T::clone)
}
@@ -484,8 +481,6 @@ where
}
}
#[cold]
#[inline(never)]
#[track_caller]
fn format_memo_warning(
msg: &str,
@@ -508,8 +503,6 @@ fn format_memo_warning(
format!("{msg}\n{defined_at_msg}warning happened here: {location}",)
}
#[cold]
#[inline(never)]
#[track_caller]
pub(crate) fn panic_getting_dead_memo(
#[cfg(debug_assertions)] defined_at: &'static std::panic::Location<'static>,

View File

@@ -8,22 +8,13 @@ slotmap::new_key_type! {
#[derive(Clone)]
pub(crate) struct ReactiveNode {
pub value: Option<Rc<RefCell<dyn Any>>>,
pub value: Rc<RefCell<dyn Any>>,
pub state: ReactiveNodeState,
pub node_type: ReactiveNodeType,
}
impl ReactiveNode {
pub fn value(&self) -> Rc<RefCell<dyn Any>> {
self.value
.clone()
.expect("ReactiveNode.value to have a value")
}
}
#[derive(Clone)]
pub(crate) enum ReactiveNodeType {
Trigger,
Signal,
Memo { f: Rc<dyn AnyComputation> },
Effect { f: Rc<dyn AnyComputation> },

View File

@@ -5,8 +5,8 @@ use crate::{
runtime::{with_runtime, RuntimeId},
serialization::Serializable,
spawn::spawn_local,
use_context, Memo, ReadSignal, Scope, ScopeProperty, SignalGetUntracked,
SignalSet, SignalUpdate, SignalWith, SuspenseContext, WriteSignal,
use_context, Memo, ReadSignal, Scope, ScopeProperty, SignalUpdate,
SignalWith, SuspenseContext, WriteSignal,
};
use std::{
any::Any,
@@ -20,19 +20,19 @@ use std::{
rc::Rc,
};
/// Creates a [`Resource`](crate::Resource), which is a signal that reflects the
/// Creates [Resource](crate::Resource), which is a signal that reflects the
/// current state of an asynchronous task, allowing you to integrate `async`
/// [`Future`]s into the synchronous reactive system.
/// [Future]s into the synchronous reactive system.
///
/// Takes a `fetcher` function that generates a [`Future`] when called and a
/// Takes a `fetcher` function that generates a [Future] when called and a
/// `source` signal that provides the argument for the `fetcher`. Whenever the
/// value of the `source` changes, a new [`Future`] will be created and run.
/// value of the `source` changes, a new [Future] will be created and run.
///
/// When server-side rendering is used, the server will handle running the
/// [`Future`] and will stream the result to the client. This process requires the
/// output type of the Future to be [`Serializable`]. If your output cannot be
/// serialized, or you just want to make sure the [`Future`] runs locally, use
/// [`create_local_resource()`].
/// [Future] and will stream the result to the client. This process requires the
/// output type of the Future to be [Serializable]. If your output cannot be
/// serialized, or you just want to make sure the [Future] runs locally, use
/// [create_local_resource()].
///
/// ```
/// # use leptos_reactive::*;
@@ -79,14 +79,14 @@ where
create_resource_with_initial_value(cx, source, fetcher, initial_value)
}
/// Creates a [`Resource`](crate::Resource) with the given initial value, which
/// will only generate and run a [`Future`] using the `fetcher` when the `source` changes.
/// Creates a [Resource](crate::Resource) with the given initial value, which
/// will only generate and run a [Future] using the `fetcher` when the `source` changes.
///
/// When server-side rendering is used, the server will handle running the
/// [`Future`] and will stream the result to the client. This process requires the
/// output type of the Future to be [`Serializable`]. If your output cannot be
/// serialized, or you just want to make sure the [`Future`] runs locally, use
/// [`create_local_resource_with_initial_value()`].
/// [Future] and will stream the result to the client. This process requires the
/// output type of the Future to be [Serializable]. If your output cannot be
/// serialized, or you just want to make sure the [Future] runs locally, use
/// [create_local_resource_with_initial_value()].
#[cfg_attr(
debug_assertions,
instrument(
@@ -120,7 +120,7 @@ where
)
}
/// Creates a “blocking” [`Resource`](crate::Resource). When server-side rendering is used,
/// Creates a “blocking” [Resource](crate::Resource). When server-side rendering is used,
/// this resource will cause any `<Suspense/>` you read it under to block the initial
/// chunk of HTML from being sent to the client. This means that if you set things like
/// HTTP headers or `<head>` metadata in that `<Suspense/>`, that header material will
@@ -198,7 +198,6 @@ where
fetcher,
resolved: Rc::new(Cell::new(resolved)),
scheduled: Rc::new(Cell::new(false)),
preempted: Rc::new(Cell::new(false)),
suspense_contexts: Default::default(),
serializable,
});
@@ -217,7 +216,7 @@ where
}
});
cx.push_scope_property(ScopeProperty::Resource(id));
cx.with_scope_property(|prop| prop.push(ScopeProperty::Resource(id)));
Resource {
runtime: cx.runtime,
@@ -229,16 +228,16 @@ where
}
}
/// Creates a _local_ [`Resource`](crate::Resource), which is a signal that
/// Creates a _local_ [Resource](crate::Resource), which is a signal that
/// reflects the current state of an asynchronous task, allowing you to
/// integrate `async` [`Future`]s into the synchronous reactive system.
/// integrate `async` [Future]s into the synchronous reactive system.
///
/// Takes a `fetcher` function that generates a [`Future`] when called and a
/// Takes a `fetcher` function that generates a [Future] when called and a
/// `source` signal that provides the argument for the `fetcher`. Whenever the
/// value of the `source` changes, a new [`Future`] will be created and run.
/// value of the `source` changes, a new [Future] will be created and run.
///
/// Unlike [`create_resource()`], this [`Future`] is always run on the local system
/// and therefore it's result type does not need to be [`Serializable`].
/// Unlike [create_resource()], this [Future] is always run on the local system
/// and therefore it's result type does not need to be [Serializable].
///
/// ```
/// # use leptos_reactive::*;
@@ -274,13 +273,13 @@ where
create_local_resource_with_initial_value(cx, source, fetcher, initial_value)
}
/// Creates a _local_ [`Resource`](crate::Resource) with the given initial value,
/// which will only generate and run a [`Future`] using the `fetcher` when the
/// Creates a _local_ [Resource](crate::Resource) with the given initial value,
/// which will only generate and run a [Future] using the `fetcher` when the
/// `source` changes.
///
/// Unlike [`create_resource_with_initial_value()`], this [`Future`] will always run
/// Unlike [create_resource_with_initial_value()], this [Future] will always run
/// on the local system and therefore its output type does not need to be
/// [`Serializable`].
/// [Serializable].
#[cfg_attr(
debug_assertions,
instrument(
@@ -323,7 +322,6 @@ where
fetcher,
resolved: Rc::new(Cell::new(resolved)),
scheduled: Rc::new(Cell::new(false)),
preempted: Rc::new(Cell::new(false)),
suspense_contexts: Default::default(),
serializable: ResourceSerialization::Local,
});
@@ -341,7 +339,7 @@ where
move |_| r.load(false)
});
cx.push_scope_property(ScopeProperty::Resource(id));
cx.with_scope_property(|prop| prop.push(ScopeProperty::Resource(id)));
Resource {
runtime: cx.runtime,
@@ -445,7 +443,7 @@ where
/// resource is still pending). Also subscribes the running effect to this
/// resource.
///
/// If you want to get the value without cloning it, use [`Resource::with`].
/// If you want to get the value without cloning it, use [Resource::with].
/// (`value.read(cx)` is equivalent to `value.with(cx, T::clone)`.)
#[track_caller]
pub fn read(&self, cx: Scope) -> Option<T>
@@ -465,10 +463,10 @@ where
/// Applies a function to the current value of the resource, and subscribes
/// the running effect to this resource. If the resource hasn't yet
/// resolved, the function won't be called and this will return
/// [`Option::None`].
/// [Option::None].
///
/// If you want to get the value by cloning it, you can use
/// [`Resource::read`].
/// [Resource::read].
#[track_caller]
pub fn with<U>(&self, cx: Scope, f: impl FnOnce(&T) -> U) -> Option<U> {
let location = std::panic::Location::caller();
@@ -503,8 +501,8 @@ where
});
}
/// Returns a [`Future`] that will resolve when the resource has loaded,
/// yield its [`ResourceId`] and a JSON string.
/// Returns a [std::future::Future] that will resolve when the resource has loaded,
/// yield its [ResourceId] and a JSON string.
#[cfg(any(feature = "ssr", doc))]
pub async fn to_serialization_resolver(
&self,
@@ -526,114 +524,19 @@ where
}
}
impl<S, T> SignalUpdate<Option<T>> for Resource<S, T> {
#[cfg_attr(
debug_assertions,
instrument(
level = "trace",
name = "Resource::update()",
skip_all,
fields(
id = ?self.id,
defined_at = %self.defined_at,
ty = %std::any::type_name::<T>()
)
)
)]
#[inline(always)]
fn update(&self, f: impl FnOnce(&mut Option<T>)) {
self.try_update(f);
}
#[cfg_attr(
debug_assertions,
instrument(
level = "trace",
name = "Resource::try_update()",
skip_all,
fields(
id = ?self.id,
defined_at = %self.defined_at,
ty = %std::any::type_name::<T>()
)
)
)]
#[inline(always)]
fn try_update<O>(&self, f: impl FnOnce(&mut Option<T>) -> O) -> Option<O> {
with_runtime(self.runtime, |runtime| {
runtime.resource(self.id, |resource: &ResourceState<S, T>| {
if resource.loading.get_untracked() {
resource.preempted.set(true);
for suspense_context in
resource.suspense_contexts.borrow().iter()
{
suspense_context.decrement(
resource.serializable
!= ResourceSerialization::Local,
);
}
}
resource.set_loading.set(false);
resource.set_value.try_update(f)
})
})
.ok()
.flatten()
}
}
impl<S, T> SignalSet<T> for Resource<S, T> {
#[cfg_attr(
debug_assertions,
instrument(
level = "trace",
name = "Resource::set()",
skip_all,
fields(
id = ?self.id,
defined_at = %self.defined_at,
ty = %std::any::type_name::<T>()
)
)
)]
#[inline(always)]
fn set(&self, new_value: T) {
self.try_set(new_value);
}
#[cfg_attr(
debug_assertions,
instrument(
level = "trace",
name = "Resource::try_set()",
skip_all,
fields(
id = ?self.id,
defined_at = %self.defined_at,
ty = %std::any::type_name::<T>()
)
)
)]
#[inline(always)]
fn try_set(&self, new_value: T) -> Option<T> {
self.update(|n| *n = Some(new_value));
None
}
}
/// A signal that reflects the
/// current state of an asynchronous task, allowing you to integrate `async`
/// [`Future`]s into the synchronous reactive system.
/// [Future]s into the synchronous reactive system.
///
/// Takes a `fetcher` function that generates a [`Future`] when called and a
/// Takes a `fetcher` function that generates a [Future] when called and a
/// `source` signal that provides the argument for the `fetcher`. Whenever the
/// value of the `source` changes, a new [`Future`] will be created and run.
/// value of the `source` changes, a new [Future] will be created and run.
///
/// When server-side rendering is used, the server will handle running the
/// [`Future`] and will stream the result to the client. This process requires the
/// output type of the Future to be [`Serializable`]. If your output cannot be
/// serialized, or you just want to make sure the [`Future`] runs locally, use
/// [`create_local_resource()`].
/// [Future] and will stream the result to the client. This process requires the
/// output type of the Future to be [Serializable]. If your output cannot be
/// serialized, or you just want to make sure the [Future] runs locally, use
/// [create_local_resource()].
///
/// ```
/// # use leptos_reactive::*;
@@ -680,7 +583,7 @@ where
// Resources
slotmap::new_key_type! {
/// Unique ID assigned to a [`Resource`](crate::Resource).
/// Unique ID assigned to a [Resource](crate::Resource).
pub struct ResourceId;
}
@@ -723,7 +626,6 @@ where
fetcher: Rc<dyn Fn(S) -> Pin<Box<dyn Future<Output = T>>>>,
resolved: Rc<Cell<bool>>,
scheduled: Rc<Cell<bool>>,
preempted: Rc<Cell<bool>>,
suspense_contexts: Rc<RefCell<HashSet<SuspenseContext>>>,
serializable: ResourceSerialization,
}
@@ -836,7 +738,6 @@ where
return;
}
self.preempted.set(false);
self.scheduled.set(false);
_ = self.source.try_with(|source| {
@@ -871,27 +772,19 @@ where
let resolved = self.resolved.clone();
let set_value = self.set_value;
let set_loading = self.set_loading;
let preempted = self.preempted.clone();
async move {
let res = fut.await;
resolved.set(true);
if !preempted.get() {
set_value.update(|n| *n = Some(res));
}
set_value.update(|n| *n = Some(res));
set_loading.update(|n| *n = false);
if !preempted.get() {
for suspense_context in
suspense_contexts.borrow().iter()
{
suspense_context.decrement(
serializable != ResourceSerialization::Local,
);
}
for suspense_context in suspense_contexts.borrow().iter() {
suspense_context.decrement(
serializable != ResourceSerialization::Local,
);
}
preempted.set(false);
}
})
});

View File

@@ -4,8 +4,8 @@ use crate::{
node::{NodeId, ReactiveNode, ReactiveNodeState, ReactiveNodeType},
AnyComputation, AnyResource, Effect, Memo, MemoState, ReadSignal,
ResourceId, ResourceState, RwSignal, Scope, ScopeDisposer, ScopeId,
ScopeProperty, SerializableResource, StoredValueId, Trigger,
UnserializableResource, WriteSignal,
ScopeProperty, SerializableResource, StoredValueId, UnserializableResource,
WriteSignal,
};
use cfg_if::cfg_if;
use core::hash::BuildHasherDefault;
@@ -117,16 +117,15 @@ impl Runtime {
// memos and effects rerun
// signals simply have their value
let changed = match node.node_type {
ReactiveNodeType::Signal | ReactiveNodeType::Trigger => true,
ReactiveNodeType::Memo { ref f }
| ReactiveNodeType::Effect { ref f } => {
let value = node.value();
ReactiveNodeType::Signal => true,
ReactiveNodeType::Memo { f }
| ReactiveNodeType::Effect { f } => {
// set this node as the observer
self.with_observer(node_id, move || {
// clean up sources of this memo/effect
self.cleanup(node_id);
f.run(value)
f.run(Rc::clone(&node.value))
})
}
};
@@ -192,17 +191,12 @@ impl Runtime {
pub(crate) fn mark_dirty(&self, node: NodeId) {
//crate::macros::debug_warn!("marking {node:?} dirty");
let mut nodes = self.nodes.borrow_mut();
let mut pending_effects = self.pending_effects.borrow_mut();
let subscribers = self.node_subscribers.borrow();
let current_observer = self.observer.get();
// mark self dirty
if let Some(current_node) = nodes.get_mut(node) {
if current_node.state == ReactiveNodeState::DirtyMarked {
return;
}
let mut pending_effects = self.pending_effects.borrow_mut();
let subscribers = self.node_subscribers.borrow();
let current_observer = self.observer.get();
// mark self dirty
Runtime::mark(
node,
current_node,
@@ -252,11 +246,11 @@ impl Runtime {
while let Some(iter) = stack.last_mut() {
let res = iter.with_iter_mut(|iter| {
let Some(mut child) = iter.next().copied() else {
let Some(&child) = iter.next() else {
return IterResult::Empty;
};
while let Some(node) = nodes.get_mut(child) {
if let Some(node) = nodes.get_mut(child) {
if node.state == ReactiveNodeState::Check
|| node.state == ReactiveNodeState::DirtyMarked
{
@@ -272,23 +266,11 @@ impl Runtime {
);
if let Some(children) = subscribers.get(child) {
let children = children.borrow();
if !children.is_empty() {
// avoid going through an iterator in the simple psuedo-recursive case
if children.len() == 1 {
child = children[0];
continue;
}
return IterResult::NewIter(RefIter::new(
children,
|children| children.iter(),
));
}
return IterResult::NewIter(RefIter::new(
children.borrow(),
|children| children.iter(),
));
}
break;
}
IterResult::Continue
@@ -331,12 +313,16 @@ impl Runtime {
}
}
pub(crate) fn run_effects(&self) {
if !self.batching.get() {
let effects = self.pending_effects.take();
for effect_id in effects {
self.update_if_necessary(effect_id);
}
pub(crate) fn run_effects(runtime_id: RuntimeId) {
_ = with_runtime(runtime_id, |runtime| {
runtime.run_your_effects();
});
}
pub(crate) fn run_your_effects(&self) {
let effects = self.pending_effects.take();
for effect_id in effects {
self.update_if_necessary(effect_id);
}
}
@@ -360,7 +346,6 @@ impl Debug for Runtime {
}
/// Get the selected runtime from the thread-local set of runtimes. On the server,
/// this will return the correct runtime. In the browser, there should only be one runtime.
#[inline(always)] // it monomorphizes anyway
pub(crate) fn with_runtime<T>(
id: RuntimeId,
f: impl FnOnce(&Runtime) -> T,
@@ -384,7 +369,7 @@ pub(crate) fn with_runtime<T>(
#[doc(hidden)]
#[must_use = "Runtime will leak memory if Runtime::dispose() is never called."]
/// Creates a new reactive [`Runtime`]. This should almost always be handled by the framework.
/// Creates a new reactive [Runtime]. This should almost always be handled by the framework.
pub fn create_runtime() -> RuntimeId {
cfg_if! {
if #[cfg(any(feature = "csr", feature = "hydrate"))] {
@@ -397,17 +382,17 @@ pub fn create_runtime() -> RuntimeId {
#[cfg(not(any(feature = "csr", feature = "hydrate")))]
slotmap::new_key_type! {
/// Unique ID assigned to a Runtime.
/// Unique ID assigned to a [Runtime](crate::Runtime).
pub struct RuntimeId;
}
/// Unique ID assigned to a Runtime.
/// Unique ID assigned to a [Runtime](crate::Runtime).
#[cfg(any(feature = "csr", feature = "hydrate"))]
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct RuntimeId;
impl RuntimeId {
/// Removes the runtime, disposing all its child [`Scope`](crate::Scope)s.
/// Removes the runtime, disposing all its child [Scope](crate::Scope)s.
pub fn dispose(self) {
cfg_if! {
if #[cfg(not(any(feature = "csr", feature = "hydrate")))] {
@@ -421,7 +406,7 @@ impl RuntimeId {
with_runtime(self, |runtime| {
let id = { runtime.scopes.borrow_mut().insert(Default::default()) };
let scope = Scope { runtime: self, id };
let disposer = ScopeDisposer(scope);
let disposer = ScopeDisposer(Box::new(move || scope.dispose()));
(scope, disposer)
})
.expect(
@@ -430,34 +415,24 @@ impl RuntimeId {
)
}
pub(crate) fn raw_scope_and_disposer_with_parent(
pub(crate) fn run_scope_undisposed<T>(
self,
f: impl FnOnce(Scope) -> T,
parent: Option<Scope>,
) -> (Scope, ScopeDisposer) {
) -> (T, ScopeId, ScopeDisposer) {
with_runtime(self, |runtime| {
let id = { runtime.scopes.borrow_mut().insert(Default::default()) };
if let Some(parent) = parent {
runtime.scope_parents.borrow_mut().insert(id, parent.id);
}
let scope = Scope { runtime: self, id };
let disposer = ScopeDisposer(scope);
(scope, disposer)
let val = f(scope);
let disposer = ScopeDisposer(Box::new(move || scope.dispose()));
(val, id, disposer)
})
.expect("tried to crate scope in a runtime that has been disposed")
.expect("tried to run scope in a runtime that has been disposed")
}
#[inline(always)]
pub(crate) fn run_scope_undisposed<T>(
self,
f: impl FnOnce(Scope) -> T,
parent: Option<Scope>,
) -> (T, ScopeId, ScopeDisposer) {
let (scope, disposer) = self.raw_scope_and_disposer_with_parent(parent);
(f(scope), scope.id, disposer)
}
#[inline(always)]
pub(crate) fn run_scope<T>(
self,
f: impl FnOnce(Scope) -> T,
@@ -469,34 +444,13 @@ impl RuntimeId {
}
#[track_caller]
#[inline(always)] // only because it's placed here to fit in with the other create methods
pub(crate) fn create_trigger(self) -> Trigger {
let id = with_runtime(self, |runtime| {
runtime.nodes.borrow_mut().insert(ReactiveNode {
value: None,
state: ReactiveNodeState::Clean,
node_type: ReactiveNodeType::Trigger,
})
})
.expect(
"tried to create a trigger in a runtime that has been disposed",
);
Trigger {
id,
runtime: self,
#[cfg(debug_assertions)]
defined_at: std::panic::Location::caller(),
}
}
pub(crate) fn create_concrete_signal(
self,
value: Rc<RefCell<dyn Any>>,
) -> NodeId {
with_runtime(self, |runtime| {
runtime.nodes.borrow_mut().insert(ReactiveNode {
value: Some(value),
value,
state: ReactiveNodeState::Clean,
node_type: ReactiveNodeType::Signal,
})
@@ -505,7 +459,6 @@ impl RuntimeId {
}
#[track_caller]
#[inline(always)]
pub(crate) fn create_signal<T>(
self,
value: T,
@@ -561,7 +514,7 @@ impl RuntimeId {
values
.map(|value| {
signals.insert(ReactiveNode {
value: Some(Rc::new(RefCell::new(value))),
value: Rc::new(RefCell::new(value)),
state: ReactiveNodeState::Clean,
node_type: ReactiveNodeType::Signal,
})
@@ -592,7 +545,6 @@ impl RuntimeId {
}
#[track_caller]
#[inline(always)]
pub(crate) fn create_rw_signal<T>(self, value: T) -> RwSignal<T>
where
T: Any + 'static,
@@ -613,6 +565,7 @@ impl RuntimeId {
}
}
#[track_caller]
pub(crate) fn create_concrete_effect(
self,
value: Rc<RefCell<dyn Any>>,
@@ -620,7 +573,7 @@ impl RuntimeId {
) -> NodeId {
with_runtime(self, |runtime| {
let id = runtime.nodes.borrow_mut().insert(ReactiveNode {
value: Some(Rc::clone(&value)),
value: Rc::clone(&value),
state: ReactiveNodeState::Clean,
node_type: ReactiveNodeType::Effect {
f: Rc::clone(&effect),
@@ -640,25 +593,7 @@ impl RuntimeId {
.expect("tried to create an effect in a runtime that has been disposed")
}
pub(crate) fn create_concrete_memo(
self,
value: Rc<RefCell<dyn Any>>,
computation: Rc<dyn AnyComputation>,
) -> NodeId {
with_runtime(self, |runtime| {
runtime.nodes.borrow_mut().insert(ReactiveNode {
value: Some(value),
// memos are lazy, so are dirty when created
// will be run the first time we ask for it
state: ReactiveNodeState::Dirty,
node_type: ReactiveNodeType::Memo { f: computation },
})
})
.expect("tried to create a memo in a runtime that has been disposed")
}
#[track_caller]
#[inline(always)]
pub(crate) fn create_effect<T>(
self,
f: impl Fn(Option<T>) -> T + 'static,
@@ -666,19 +601,21 @@ impl RuntimeId {
where
T: Any + 'static,
{
self.create_concrete_effect(
Rc::new(RefCell::new(None::<T>)),
Rc::new(Effect {
f,
ty: PhantomData,
#[cfg(debug_assertions)]
defined_at: std::panic::Location::caller(),
}),
)
#[cfg(debug_assertions)]
let defined_at = std::panic::Location::caller();
let effect = Effect {
f,
ty: PhantomData,
#[cfg(debug_assertions)]
defined_at,
};
let value = Rc::new(RefCell::new(None::<T>));
self.create_concrete_effect(value, Rc::new(effect))
}
#[track_caller]
#[inline(always)]
pub(crate) fn create_memo<T>(
self,
f: impl Fn(Option<&T>) -> T + 'static,
@@ -686,20 +623,33 @@ impl RuntimeId {
where
T: PartialEq + Any + 'static,
{
#[cfg(debug_assertions)]
let defined_at = std::panic::Location::caller();
let id = with_runtime(self, |runtime| {
runtime.nodes.borrow_mut().insert(ReactiveNode {
value: Rc::new(RefCell::new(None::<T>)),
// memos are lazy, so are dirty when created
// will be run the first time we ask for it
state: ReactiveNodeState::Dirty,
node_type: ReactiveNodeType::Memo {
f: Rc::new(MemoState {
f,
t: PhantomData,
#[cfg(debug_assertions)]
defined_at,
}),
},
})
})
.expect("tried to create a memo in a runtime that has been disposed");
Memo {
runtime: self,
id: self.create_concrete_memo(
Rc::new(RefCell::new(None::<T>)),
Rc::new(MemoState {
f,
t: PhantomData,
#[cfg(debug_assertions)]
defined_at: std::panic::Location::caller(),
}),
),
id,
ty: PhantomData,
#[cfg(debug_assertions)]
defined_at: std::panic::Location::caller(),
defined_at,
}
}
}
@@ -796,15 +746,6 @@ impl Runtime {
}
f
}
/// Do not call on triggers
pub(crate) fn get_value(
&self,
node_id: NodeId,
) -> Option<Rc<RefCell<dyn Any>>> {
let signals = self.nodes.borrow();
signals.get(node_id).map(|node| node.value())
}
}
impl PartialEq for Runtime {

View File

@@ -82,7 +82,7 @@ pub fn run_scope_undisposed<T>(
/// when it is removed from the list.
///
/// Every other function in this crate takes a `Scope` as its first argument. Since `Scope`
/// is [`Copy`] and `'static` this does not add much overhead or lifetime complexity.
/// is [Copy] and `'static` this does not add much overhead or lifetime complexity.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct Scope {
#[doc(hidden)]
@@ -116,7 +116,6 @@ impl Scope {
/// This is useful for applications like a list or a router, which may want to create child scopes and
/// dispose of them when they are no longer needed (e.g., a list item has been destroyed or the user
/// has navigated away from the route.)
#[inline(always)]
pub fn child_scope(self, f: impl FnOnce(Scope)) -> ScopeDisposer {
let (_, disposer) = self.run_child_scope(f);
disposer
@@ -131,20 +130,12 @@ impl Scope {
/// This is useful for applications like a list or a router, which may want to create child scopes and
/// dispose of them when they are no longer needed (e.g., a list item has been destroyed or the user
/// has navigated away from the route.)
#[inline(always)]
pub fn run_child_scope<T>(
self,
f: impl FnOnce(Scope) -> T,
) -> (T, ScopeDisposer) {
let (res, child_id, disposer) =
self.runtime.run_scope_undisposed(f, Some(self));
self.push_child(child_id);
(res, disposer)
}
fn push_child(&self, child_id: ScopeId) {
_ = with_runtime(self.runtime, |runtime| {
let mut children = runtime.scope_children.borrow_mut();
children
@@ -156,6 +147,7 @@ impl Scope {
.or_default()
.push(child_id);
});
(res, disposer)
}
/// Suspends reactive tracking while running the given function.
@@ -183,23 +175,13 @@ impl Scope {
///
/// # });
/// ```
#[inline(always)]
pub fn untrack<T>(&self, f: impl FnOnce() -> T) -> T {
with_runtime(self.runtime, |runtime| {
let untracked_result;
SpecialNonReactiveZone::enter();
let prev_observer =
SetObserverOnDrop(self.runtime, runtime.observer.take());
untracked_result = f();
runtime.observer.set(prev_observer.1);
std::mem::forget(prev_observer); // avoid Drop
let prev_observer = runtime.observer.take();
let untracked_result = f();
runtime.observer.set(prev_observer);
SpecialNonReactiveZone::exit();
untracked_result
})
.expect(
@@ -209,16 +191,6 @@ impl Scope {
}
}
struct SetObserverOnDrop(RuntimeId, Option<NodeId>);
impl Drop for SetObserverOnDrop {
fn drop(&mut self) {
_ = with_runtime(self.0, |rt| {
rt.observer.set(self.1);
});
}
}
// Internals
impl Scope {
@@ -226,7 +198,7 @@ impl Scope {
///
/// This will
/// 1. dispose of all child `Scope`s
/// 2. run all cleanup functions defined for this scope by [`on_cleanup`](crate::on_cleanup).
/// 2. run all cleanup functions defined for this scope by [on_cleanup](crate::on_cleanup).
/// 3. dispose of all signals, effects, and resources owned by this `Scope`.
pub fn dispose(self) {
_ = with_runtime(self.runtime, |runtime| {
@@ -254,8 +226,6 @@ impl Scope {
}
}
runtime.scope_parents.borrow_mut().remove(self.id);
// remove everything we own and run cleanups
let owned = {
let owned = runtime.scopes.borrow_mut().remove(self.id);
@@ -264,8 +234,7 @@ impl Scope {
if let Some(owned) = owned {
for property in owned {
match property {
ScopeProperty::Signal(id)
| ScopeProperty::Trigger(id) => {
ScopeProperty::Signal(id) => {
// remove the signal
runtime.nodes.borrow_mut().remove(id);
let subs = runtime
@@ -302,11 +271,14 @@ impl Scope {
})
}
pub(crate) fn push_scope_property(&self, prop: ScopeProperty) {
pub(crate) fn with_scope_property(
&self,
f: impl FnOnce(&mut Vec<ScopeProperty>),
) {
_ = with_runtime(self.runtime, |runtime| {
let scopes = runtime.scopes.borrow();
if let Some(scope) = scopes.get(self.id) {
scope.borrow_mut().push(prop);
f(&mut scope.borrow_mut());
} else {
console_warn(
"tried to add property to a scope that has been disposed",
@@ -317,90 +289,82 @@ impl Scope {
/// Returns the the parent Scope, if any.
pub fn parent(&self) -> Option<Scope> {
match with_runtime(self.runtime, |runtime| {
with_runtime(self.runtime, |runtime| {
runtime.scope_parents.borrow().get(self.id).copied()
}) {
Ok(Some(id)) => Some(Scope {
runtime: self.runtime,
id,
}),
_ => None,
}
})
.ok()
.flatten()
.map(|id| Scope {
runtime: self.runtime,
id,
})
}
}
fn push_cleanup(cx: Scope, cleanup_fn: Box<dyn FnOnce()>) {
/// Creates a cleanup function, which will be run when a [Scope] is disposed.
///
/// It runs after child scopes have been disposed, but before signals, effects, and resources
/// are invalidated.
pub fn on_cleanup(cx: Scope, cleanup_fn: impl FnOnce() + 'static) {
_ = with_runtime(cx.runtime, |runtime| {
let mut cleanups = runtime.scope_cleanups.borrow_mut();
let cleanups = cleanups
.entry(cx.id)
.expect("trying to clean up a Scope that has already been disposed")
.or_insert_with(Default::default);
cleanups.push(cleanup_fn);
});
}
/// Creates a cleanup function, which will be run when a [`Scope`] is disposed.
///
/// It runs after child scopes have been disposed, but before signals, effects, and resources
/// are invalidated.
#[inline(always)]
pub fn on_cleanup(cx: Scope, cleanup_fn: impl FnOnce() + 'static) {
push_cleanup(cx, Box::new(cleanup_fn))
cleanups.push(Box::new(cleanup_fn));
})
}
slotmap::new_key_type! {
/// Unique ID assigned to a [`Scope`](crate::Scope).
/// Unique ID assigned to a [Scope](crate::Scope).
pub struct ScopeId;
}
#[derive(Debug)]
pub(crate) enum ScopeProperty {
Trigger(NodeId),
Signal(NodeId),
Effect(NodeId),
Resource(ResourceId),
StoredValue(StoredValueId),
}
/// Creating a [`Scope`](crate::Scope) gives you a disposer, which can be called
/// Creating a [Scope](crate::Scope) gives you a disposer, which can be called
/// to dispose of that reactive scope.
///
/// This will
/// 1. dispose of all child `Scope`s
/// 2. run all cleanup functions defined for this scope by [`on_cleanup`](crate::on_cleanup).
/// 2. run all cleanup functions defined for this scope by [on_cleanup](crate::on_cleanup).
/// 3. dispose of all signals, effects, and resources owned by this `Scope`.
#[repr(transparent)]
pub struct ScopeDisposer(pub(crate) Scope);
pub struct ScopeDisposer(pub(crate) Box<dyn FnOnce()>);
impl ScopeDisposer {
/// Disposes of a reactive [`Scope`](crate::Scope).
/// Disposes of a reactive [Scope](crate::Scope).
///
/// This will
/// 1. dispose of all child `Scope`s
/// 2. run all cleanup functions defined for this scope by [`on_cleanup`](crate::on_cleanup).
/// 2. run all cleanup functions defined for this scope by [on_cleanup](crate::on_cleanup).
/// 3. dispose of all signals, effects, and resources owned by this `Scope`.
#[inline(always)]
pub fn dispose(self) {
self.0.dispose()
(self.0)()
}
}
impl Scope {
/// Returns IDs for all [`Resource`](crate::Resource)s found on any scope.
/// Returns IDs for all [Resource](crate::Resource)s found on any scope.
pub fn all_resources(&self) -> Vec<ResourceId> {
with_runtime(self.runtime, |runtime| runtime.all_resources())
.unwrap_or_default()
}
/// Returns IDs for all [`Resource`](crate::Resource)s found on any scope that are
/// Returns IDs for all [Resource](crate::Resource)s found on any scope that are
/// pending from the server.
pub fn pending_resources(&self) -> Vec<ResourceId> {
with_runtime(self.runtime, |runtime| runtime.pending_resources())
.unwrap_or_default()
}
/// Returns IDs for all [`Resource`](crate::Resource)s found on any scope.
/// Returns IDs for all [Resource](crate::Resource)s found on any scope.
pub fn serialization_resolvers(
&self,
) -> FuturesUnordered<PinnedFuture<(ResourceId, String)>> {
@@ -410,7 +374,7 @@ impl Scope {
.unwrap_or_default()
}
/// Registers the given [`SuspenseContext`](crate::SuspenseContext) with the current scope,
/// Registers the given [SuspenseContext](crate::SuspenseContext) with the current scope,
/// calling the `resolver` when its resources are all resolved.
pub fn register_suspense(
&self,
@@ -512,19 +476,12 @@ impl Scope {
///
/// # Panics
/// Panics if the runtime this scope belongs to has already been disposed.
#[inline(always)]
pub fn batch<T>(&self, f: impl FnOnce() -> T) -> T {
with_runtime(self.runtime, move |runtime| {
let batching =
SetBatchingOnDrop(self.runtime, runtime.batching.get());
runtime.batching.set(true);
let val = f();
runtime.batching.set(batching.1);
std::mem::forget(batching);
runtime.run_effects();
runtime.batching.set(false);
runtime.run_your_effects();
val
})
.expect(
@@ -533,16 +490,6 @@ impl Scope {
}
}
struct SetBatchingOnDrop(RuntimeId, bool);
impl Drop for SetBatchingOnDrop {
fn drop(&mut self) {
_ = with_runtime(self.0, |rt| {
rt.batching.set(self.1);
});
}
}
impl fmt::Debug for ScopeDisposer {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("ScopeDisposer").finish()

View File

@@ -9,7 +9,7 @@ use std::{
/// Creates a conditional signal that only notifies subscribers when a change
/// in the source signals value changes whether it is equal to the key value
/// (as determined by [`PartialEq`].)
/// (as determined by [PartialEq].)
///
/// **You probably dont need this,** but it can be a very useful optimization
/// in certain situations (e.g., “set the class `selected` if `selected() == this_row_index`)
@@ -46,7 +46,6 @@ use std::{
/// # })
/// # .dispose()
/// ```
#[inline(always)]
pub fn create_selector<T>(
cx: Scope,
source: impl Fn() -> T + Clone + 'static,
@@ -54,7 +53,7 @@ pub fn create_selector<T>(
where
T: PartialEq + Eq + Debug + Clone + Hash + 'static,
{
create_selector_with_fn(cx, source, PartialEq::eq)
create_selector_with_fn(cx, source, |a, b| a == b)
}
/// Creates a conditional signal that only notifies subscribers when a change

View File

@@ -4,7 +4,7 @@ use std::rc::Rc;
use thiserror::Error;
/// Describes errors that can occur while serializing and deserializing data,
/// typically during the process of streaming [`Resource`](crate::Resource)s from
/// typically during the process of streaming [Resource](crate::Resource)s from
/// the server to the client.
#[derive(Debug, Clone, Error)]
pub enum SerializationError {
@@ -19,7 +19,7 @@ pub enum SerializationError {
/// Describes an object that can be serialized to or from a supported format
/// Currently those are JSON and Cbor
///
/// This is primarily used for serializing and deserializing [`Resource`](crate::Resource)s
/// This is primarily used for serializing and deserializing [Resource](crate::Resource)s
/// so they can begin on the server and be resolved on the client, but can be used
/// for any data that needs to be serialized/deserialized.
///

View File

@@ -8,10 +8,9 @@ use crate::{
runtime::{with_runtime, RuntimeId},
Runtime, Scope, ScopeProperty,
};
use cfg_if::cfg_if;
use futures::Stream;
use std::{
any::Any, cell::RefCell, fmt::Debug, marker::PhantomData, pin::Pin, rc::Rc,
};
use std::{fmt::Debug, marker::PhantomData, pin::Pin, rc::Rc};
use thiserror::Error;
macro_rules! impl_get_fn_traits {
@@ -21,7 +20,6 @@ macro_rules! impl_get_fn_traits {
impl<T: Clone> FnOnce<()> for $ty<T> {
type Output = T;
#[inline(always)]
extern "rust-call" fn call_once(self, _args: ()) -> Self::Output {
impl_get_fn_traits!(@method_name self $($method_name)?)
}
@@ -29,7 +27,6 @@ macro_rules! impl_get_fn_traits {
#[cfg(not(feature = "stable"))]
impl<T: Clone> FnMut<()> for $ty<T> {
#[inline(always)]
extern "rust-call" fn call_mut(&mut self, _args: ()) -> Self::Output {
impl_get_fn_traits!(@method_name self $($method_name)?)
}
@@ -37,7 +34,6 @@ macro_rules! impl_get_fn_traits {
#[cfg(not(feature = "stable"))]
impl<T: Clone> Fn<()> for $ty<T> {
#[inline(always)]
extern "rust-call" fn call(&self, _args: ()) -> Self::Output {
impl_get_fn_traits!(@method_name self $($method_name)?)
}
@@ -59,7 +55,6 @@ macro_rules! impl_set_fn_traits {
impl<T> FnOnce<(T,)> for $ty<T> {
type Output = ();
#[inline(always)]
extern "rust-call" fn call_once(self, args: (T,)) -> Self::Output {
impl_set_fn_traits!(@method_name self $($method_name)? args)
}
@@ -67,7 +62,6 @@ macro_rules! impl_set_fn_traits {
#[cfg(not(feature = "stable"))]
impl<T> FnMut<(T,)> for $ty<T> {
#[inline(always)]
extern "rust-call" fn call_mut(&mut self, args: (T,)) -> Self::Output {
impl_set_fn_traits!(@method_name self $($method_name)? args)
}
@@ -75,7 +69,6 @@ macro_rules! impl_set_fn_traits {
#[cfg(not(feature = "stable"))]
impl<T> Fn<(T,)> for $ty<T> {
#[inline(always)]
extern "rust-call" fn call(&self, args: (T,)) -> Self::Output {
impl_set_fn_traits!(@method_name self $($method_name)? args)
}
@@ -109,7 +102,7 @@ pub trait SignalGet<T> {
/// the running effect to this signal.
///
/// # Panics
/// Panics if you try to access a signal that was created in a [`Scope`] that has been disposed.
/// Panics if you try to access a signal that was created in a [Scope] that has been disposed.
#[track_caller]
fn get(&self) -> T;
@@ -125,7 +118,7 @@ pub trait SignalWith<T> {
/// the running effect to this signal.
///
/// # Panics
/// Panics if you try to access a signal that was created in a [`Scope`] that has been disposed.
/// Panics if you try to access a signal that was created in a [Scope] that has been disposed.
#[track_caller]
fn with<O>(&self, f: impl FnOnce(&T) -> O) -> O;
@@ -153,7 +146,7 @@ pub trait SignalSet<T> {
/// if the signal is still valid, [`Some(T)`] otherwise.
///
/// **Note:** `set()` does not auto-memoize, i.e., it will notify subscribers
/// even if the value has not actually changed.
/// even if the value has not actually changed.
fn try_set(&self, new_value: T) -> Option<T>;
}
@@ -197,7 +190,7 @@ pub trait SignalGetUntracked<T> {
/// current scope.
///
/// # Panics
/// Panics if you try to access a signal that was created in a [`Scope`] that has been disposed.
/// Panics if you try to access a signal that was created in a [Scope] that has been disposed.
#[track_caller]
fn get_untracked(&self) -> T;
@@ -214,7 +207,7 @@ pub trait SignalWithUntracked<T> {
/// value without creating a dependency on the current scope.
///
/// # Panics
/// Panics if you try to access a signal that was created in a [`Scope`] that has been disposed.
/// Panics if you try to access a signal that was created in a [Scope] that has been disposed.
#[track_caller]
fn with_untracked<O>(&self, f: impl FnOnce(&T) -> O) -> O;
@@ -254,7 +247,6 @@ pub trait SignalUpdateUntracked<T> {
/// the value the closure returned.
#[deprecated = "Please use `try_update_untracked` instead. This method \
will be removed in a future version of `leptos`"]
#[inline(always)]
fn update_returning_untracked<U>(
&self,
f: impl FnOnce(&mut T) -> U,
@@ -275,7 +267,7 @@ pub trait SignalStream<T> {
/// whenever it changes.
///
/// # Panics
/// Panics if you try to access a signal that was created in a [`Scope`] that has been disposed.
/// Panics if you try to access a signal that was created in a [Scope] that has been disposed.
// We're returning an opaque type until impl trait in trait
// positions are stabilized, and also so any underlying
// changes are non-breaking
@@ -283,7 +275,7 @@ pub trait SignalStream<T> {
fn to_stream(&self, cx: Scope) -> Pin<Box<dyn Stream<Item = T>>>;
}
/// This trait allows disposing a signal before its [`Scope`] has been disposed.
/// This trait allows disposing a signal before its [Scope] has been disposed.
pub trait SignalDispose {
/// Disposes of the signal. This:
/// 1. Detaches the signal from the reactive graph, preventing it from triggering
@@ -299,8 +291,8 @@ pub trait SignalDispose {
/// and notifies other code when it has changed. This is the
/// core primitive of Leptoss reactive system.
///
/// Takes a reactive [`Scope`] and the initial value as arguments,
/// and returns a tuple containing a [`ReadSignal`] and a [`WriteSignal`],
/// Takes a reactive [Scope] and the initial value as arguments,
/// and returns a tuple containing a [ReadSignal] and a [WriteSignal],
/// each of which can be called as a function.
///
/// ```
@@ -348,11 +340,11 @@ pub fn create_signal<T>(
value: T,
) -> (ReadSignal<T>, WriteSignal<T>) {
let s = cx.runtime.create_signal(value);
cx.push_scope_property(ScopeProperty::Signal(s.0.id));
cx.with_scope_property(|prop| prop.push(ScopeProperty::Signal(s.0.id)));
s
}
/// Works exactly as [`create_signal`], but creates multiple signals at once.
/// Works exactly as [create_signal], but creates multiple signals at once.
#[cfg_attr(
debug_assertions,
instrument(
@@ -372,7 +364,7 @@ pub fn create_many_signals<T>(
cx.runtime.create_many_signals_with_map(cx, values, |x| x)
}
/// Works exactly as [`create_many_signals`], but applies the map function to each signal pair.
/// Works exactly as [create_many_signals], but applies the map function to each signal pair.
#[cfg_attr(
debug_assertions,
instrument(
@@ -397,7 +389,7 @@ where
}
/// Creates a signal that always contains the most recent value emitted by a
/// [`Stream`](futures::stream::Stream).
/// [Stream](futures::stream::Stream).
/// If the stream has not yet emitted a value since the signal was created, the signal's
/// value will be `None`.
///
@@ -418,7 +410,7 @@ pub fn create_signal_from_stream<T>(
#[allow(unused_mut)] // allowed because needed for SSR
mut stream: impl Stream<Item = T> + Unpin + 'static,
) -> ReadSignal<Option<T>> {
cfg_if::cfg_if! {
cfg_if! {
if #[cfg(feature = "ssr")] {
_ = stream;
let (read, _) = create_signal(cx, None);
@@ -444,7 +436,7 @@ pub fn create_signal_from_stream<T>(
/// and notifies other code when it has changed. This is the
/// core primitive of Leptoss reactive system.
///
/// `ReadSignal` is also [`Copy`] and `'static`, so it can very easily moved into closures
/// `ReadSignal` is also [Copy] and `'static`, so it can very easily moved into closures
/// or copied structs.
///
/// ## Core Trait Implementations
@@ -565,7 +557,6 @@ impl<T> SignalWithUntracked<T> for ReadSignal<T> {
)
)
)]
#[inline(always)]
fn with_untracked<O>(&self, f: impl FnOnce(&T) -> O) -> O {
self.with_no_subscription(f)
}
@@ -584,16 +575,16 @@ impl<T> SignalWithUntracked<T> for ReadSignal<T> {
)
)]
#[track_caller]
#[inline(always)]
fn try_with_untracked<O>(&self, f: impl FnOnce(&T) -> O) -> Option<O> {
let diagnostics = diagnostics!(self);
match with_runtime(self.runtime, |runtime| {
with_runtime(self.runtime, |runtime| {
self.id.try_with(runtime, f, diagnostics)
}) {
Ok(Ok(o)) => Some(o),
_ => None,
}
})
.ok()
.transpose()
.ok()
.flatten()
}
}
@@ -630,14 +621,13 @@ impl<T> SignalWith<T> for ReadSignal<T> {
)
)]
#[track_caller]
#[inline(always)]
fn with<O>(&self, f: impl FnOnce(&T) -> O) -> O {
let diagnostics = diagnostics!(self);
match with_runtime(self.runtime, |runtime| {
self.id.try_with(runtime, f, diagnostics)
})
.expect("runtime to be alive")
.expect("runtime to be alive ")
{
Ok(o) => o,
Err(_) => panic_getting_dead_signal(
@@ -661,7 +651,6 @@ impl<T> SignalWith<T> for ReadSignal<T> {
)
)]
#[track_caller]
#[inline(always)]
fn try_with<O>(&self, f: impl FnOnce(&T) -> O) -> Option<O> {
let diagnostics = diagnostics!(self);
@@ -776,7 +765,6 @@ impl<T> ReadSignal<T>
where
T: 'static,
{
#[inline(always)]
pub(crate) fn with_no_subscription<U>(&self, f: impl FnOnce(&T) -> U) -> U {
self.id.with_no_subscription(self.runtime, f)
}
@@ -784,7 +772,6 @@ where
/// Applies the function to the current Signal, if it exists, and subscribes
/// the running effect.
#[track_caller]
#[inline(always)]
pub(crate) fn try_with<U>(
&self,
f: impl FnOnce(&T) -> U,
@@ -803,7 +790,13 @@ where
impl<T> Clone for ReadSignal<T> {
fn clone(&self) -> Self {
*self
Self {
runtime: self.runtime,
id: self.id,
ty: PhantomData,
#[cfg(debug_assertions)]
defined_at: self.defined_at,
}
}
}
@@ -815,13 +808,13 @@ impl<T> Copy for ReadSignal<T> {}
/// and notifies other code when it has changed. This is the
/// core primitive of Leptoss reactive system.
///
/// Calling [`WriteSignal::update`] will mutate the signals value in place,
/// Calling [WriteSignal::update] will mutate the signals value in place,
/// and notify all subscribers that the signals value has changed.
///
/// `WriteSignal` implements [`Fn`], such that `set_value(new_value)` is equivalent to
/// `WriteSignal` implements [Fn], such that `set_value(new_value)` is equivalent to
/// `set_value.update(|value| *value = new_value)`.
///
/// `WriteSignal` is [`Copy`] and `'static`, so it can very easily moved into closures
/// `WriteSignal` is [Copy] and `'static`, so it can very easily moved into closures
/// or copied structs.
///
/// ## Core Trait Implementations
@@ -925,7 +918,6 @@ impl<T> SignalUpdateUntracked<T> for WriteSignal<T> {
)
)
)]
#[inline(always)]
fn update_untracked(&self, f: impl FnOnce(&mut T)) {
self.id.update_with_no_effect(self.runtime, f);
}
@@ -943,7 +935,6 @@ impl<T> SignalUpdateUntracked<T> for WriteSignal<T> {
)
)
)]
#[inline(always)]
fn update_returning_untracked<U>(
&self,
f: impl FnOnce(&mut T) -> U,
@@ -951,7 +942,6 @@ impl<T> SignalUpdateUntracked<T> for WriteSignal<T> {
self.id.update_with_no_effect(self.runtime, f)
}
#[inline(always)]
fn try_update_untracked<O>(
&self,
f: impl FnOnce(&mut T) -> O,
@@ -990,7 +980,6 @@ impl<T> SignalUpdate<T> for WriteSignal<T> {
)
)
)]
#[inline(always)]
fn update(&self, f: impl FnOnce(&mut T)) {
if self.id.update(self.runtime, f).is_none() {
warn_updating_dead_signal(
@@ -1013,7 +1002,6 @@ impl<T> SignalUpdate<T> for WriteSignal<T> {
)
)
)]
#[inline(always)]
fn try_update<O>(&self, f: impl FnOnce(&mut T) -> O) -> Option<O> {
self.id.update(self.runtime, f)
}
@@ -1085,7 +1073,13 @@ impl<T> SignalDispose for WriteSignal<T> {
impl<T> Clone for WriteSignal<T> {
fn clone(&self) -> Self {
*self
Self {
runtime: self.runtime,
id: self.id,
ty: PhantomData,
#[cfg(debug_assertions)]
defined_at: self.defined_at,
}
}
}
@@ -1125,12 +1119,12 @@ impl<T> Copy for WriteSignal<T> {}
#[track_caller]
pub fn create_rw_signal<T>(cx: Scope, value: T) -> RwSignal<T> {
let s = cx.runtime.create_rw_signal(value);
cx.push_scope_property(ScopeProperty::Signal(s.id));
cx.with_scope_property(|prop| prop.push(ScopeProperty::Signal(s.id)));
s
}
/// A signal that combines the getter and setter into one value, rather than
/// separating them into a [`ReadSignal`] and a [`WriteSignal`]. You may prefer this
/// separating them into a [ReadSignal] and a [WriteSignal]. You may prefer this
/// its style, or it may be easier to pass around in a context or as a function argument.
///
/// ## Core Trait Implementations
@@ -1186,7 +1180,13 @@ where
impl<T> Clone for RwSignal<T> {
fn clone(&self) -> Self {
*self
Self {
runtime: self.runtime,
id: self.id,
ty: self.ty,
#[cfg(debug_assertions)]
defined_at: self.defined_at,
}
}
}
@@ -1252,7 +1252,6 @@ impl<T> SignalWithUntracked<T> for RwSignal<T> {
)
)
)]
#[inline(always)]
fn with_untracked<O>(&self, f: impl FnOnce(&T) -> O) -> O {
self.id.with_no_subscription(self.runtime, f)
}
@@ -1271,16 +1270,16 @@ impl<T> SignalWithUntracked<T> for RwSignal<T> {
)
)]
#[track_caller]
#[inline(always)]
fn try_with_untracked<O>(&self, f: impl FnOnce(&T) -> O) -> Option<O> {
let diagnostics = diagnostics!(self);
match with_runtime(self.runtime, |runtime| {
with_runtime(self.runtime, |runtime| {
self.id.try_with(runtime, f, diagnostics)
}) {
Ok(Ok(o)) => Some(o),
_ => None,
}
})
.ok()
.transpose()
.ok()
.flatten()
}
}
@@ -1340,7 +1339,6 @@ impl<T> SignalUpdateUntracked<T> for RwSignal<T> {
)
)
)]
#[inline(always)]
fn update_untracked(&self, f: impl FnOnce(&mut T)) {
self.id.update_with_no_effect(self.runtime, f);
}
@@ -1358,7 +1356,6 @@ impl<T> SignalUpdateUntracked<T> for RwSignal<T> {
)
)
)]
#[inline(always)]
fn update_returning_untracked<U>(
&self,
f: impl FnOnce(&mut T) -> U,
@@ -1379,7 +1376,6 @@ impl<T> SignalUpdateUntracked<T> for RwSignal<T> {
)
)
)]
#[inline(always)]
fn try_update_untracked<O>(
&self,
f: impl FnOnce(&mut T) -> O,
@@ -1422,7 +1418,6 @@ impl<T> SignalWith<T> for RwSignal<T> {
)
)]
#[track_caller]
#[inline(always)]
fn with<O>(&self, f: impl FnOnce(&T) -> O) -> O {
let diagnostics = diagnostics!(self);
@@ -1453,7 +1448,6 @@ impl<T> SignalWith<T> for RwSignal<T> {
)
)]
#[track_caller]
#[inline(always)]
fn try_with<O>(&self, f: impl FnOnce(&T) -> O) -> Option<O> {
let diagnostics = diagnostics!(self);
@@ -1573,7 +1567,6 @@ impl<T> SignalUpdate<T> for RwSignal<T> {
)
)
)]
#[inline(always)]
fn update(&self, f: impl FnOnce(&mut T)) {
if self.id.update(self.runtime, f).is_none() {
warn_updating_dead_signal(
@@ -1596,7 +1589,6 @@ impl<T> SignalUpdate<T> for RwSignal<T> {
)
)
)]
#[inline(always)]
fn try_update<O>(&self, f: impl FnOnce(&mut T) -> O) -> Option<O> {
self.id.update(self.runtime, f)
}
@@ -1723,7 +1715,7 @@ impl<T> RwSignal<T> {
/// Returns a write-only handle to the signal.
///
/// Useful if you're trying to give write access to another component, or split an
/// [`RwSignal`] into a [`ReadSignal`] and a [`WriteSignal`].
/// `RwSignal` into a [ReadSignal] and a [WriteSignal].
/// ```
/// # use leptos_reactive::*;
/// # create_scope(create_runtime(), |cx| {
@@ -1865,18 +1857,7 @@ impl NodeId {
}
}
fn try_with_no_subscription_inner(
&self,
runtime: &Runtime,
) -> Result<Rc<RefCell<dyn Any>>, SignalError> {
runtime.update_if_necessary(*self);
let nodes = runtime.nodes.borrow();
let node = nodes.get(*self).ok_or(SignalError::Disposed)?;
Ok(node.value())
}
#[track_caller]
#[inline(always)]
pub(crate) fn try_with_no_subscription<T, U>(
&self,
runtime: &Runtime,
@@ -1885,7 +1866,13 @@ impl NodeId {
where
T: 'static,
{
let value = self.try_with_no_subscription_inner(runtime)?;
runtime.update_if_necessary(*self);
let value = {
let nodes = runtime.nodes.borrow();
let node = nodes.get(*self).ok_or(SignalError::Disposed)?;
Rc::clone(&node.value)
};
let value = value.borrow();
let value = value
.downcast_ref::<T>()
@@ -1895,7 +1882,6 @@ impl NodeId {
}
#[track_caller]
#[inline(always)]
pub(crate) fn try_with<T, U>(
&self,
runtime: &Runtime,
@@ -1910,7 +1896,6 @@ impl NodeId {
self.try_with_no_subscription(runtime, f)
}
#[inline(always)]
pub(crate) fn with_no_subscription<T, U>(
&self,
runtime: RuntimeId,
@@ -1925,7 +1910,6 @@ impl NodeId {
.expect("runtime to be alive")
}
#[inline(always)]
fn update_value<T, U>(
&self,
runtime: RuntimeId,
@@ -1935,7 +1919,11 @@ impl NodeId {
T: 'static,
{
with_runtime(runtime, |runtime| {
if let Some(value) = runtime.get_value(*self) {
let value = {
let signals = runtime.nodes.borrow();
signals.get(*self).map(|node| Rc::clone(&node.value))
};
if let Some(value) = value {
let mut value = value.borrow_mut();
if let Some(value) = value.downcast_mut::<T>() {
Some(f(value))
@@ -1962,7 +1950,6 @@ impl NodeId {
.unwrap_or_default()
}
#[inline(always)]
pub(crate) fn update<T, U>(
&self,
runtime_id: RuntimeId,
@@ -1972,7 +1959,11 @@ impl NodeId {
T: 'static,
{
with_runtime(runtime_id, |runtime| {
let updated = if let Some(value) = runtime.get_value(*self) {
let value = {
let signals = runtime.nodes.borrow();
signals.get(*self).map(|node| Rc::clone(&node.value))
};
let updated = if let Some(value) = value {
let mut value = value.borrow_mut();
if let Some(value) = value.downcast_mut::<T>() {
Some(f(value))
@@ -1996,20 +1987,18 @@ impl NodeId {
None
};
// mark descendants dirty
runtime.mark_dirty(*self);
// notify subscribers
if updated.is_some() {
// mark descendants dirty
runtime.mark_dirty(*self);
runtime.run_effects();
}
if updated.is_some() && !runtime.batching.get() {
Runtime::run_effects(runtime_id);
};
updated
})
.unwrap_or_default()
}
#[inline(always)]
pub(crate) fn update_with_no_effect<T, U>(
&self,
runtime: RuntimeId,
@@ -2023,8 +2012,6 @@ impl NodeId {
}
}
#[cold]
#[inline(never)]
#[track_caller]
fn format_signal_warning(
msg: &str,
@@ -2047,8 +2034,6 @@ fn format_signal_warning(
format!("{msg}\n{defined_at_msg}warning happened here: {location}",)
}
#[cold]
#[inline(never)]
#[track_caller]
pub(crate) fn panic_getting_dead_signal(
#[cfg(debug_assertions)] defined_at: &'static std::panic::Location<'static>,
@@ -2063,8 +2048,6 @@ pub(crate) fn panic_getting_dead_signal(
)
}
#[cold]
#[inline(never)]
#[track_caller]
pub(crate) fn warn_updating_dead_signal(
#[cfg(debug_assertions)] defined_at: &'static std::panic::Location<'static>,

View File

@@ -21,8 +21,8 @@ where
}
}
/// A wrapper for any kind of readable reactive signal: a [`ReadSignal`](crate::ReadSignal),
/// [`Memo`](crate::Memo), [`RwSignal`](crate::RwSignal), or derived signal closure.
/// A wrapper for any kind of readable reactive signal: a [ReadSignal](crate::ReadSignal),
/// [Memo](crate::Memo), [RwSignal](crate::RwSignal), or derived signal closure.
///
/// This allows you to create APIs that take any kind of `Signal<T>` as an argument,
/// rather than adding a generic `F: Fn() -> T`. Values can be access with the same

View File

@@ -18,8 +18,8 @@ where
}
}
/// A wrapper for any kind of settable reactive signal: a [`WriteSignal`](crate::WriteSignal),
/// [`RwSignal`](crate::RwSignal), or closure that receives a value and sets a signal depending
/// A wrapper for any kind of settable reactive signal: a [WriteSignal](crate::WriteSignal),
/// [RwSignal](crate::RwSignal), or closure that receives a value and sets a signal depending
/// on it.
///
/// This allows you to create APIs that take any kind of `SignalSetter<T>` as an argument,

View File

@@ -3,9 +3,9 @@ use crate::{
SignalUpdate, SignalWith,
};
/// Derives a reactive slice of an [`RwSignal`](crate::RwSignal).
/// Derives a reactive slice of an [RwSignal](crate::RwSignal).
///
/// Slices have the same guarantees as [`Memo`s](crate::Memo):
/// Slices have the same guarantees as [Memos](crate::Memo):
/// they only emit their value when it has actually been changed.
///
/// Slices need a getter and a setter, and you must make sure that

View File

@@ -2,7 +2,7 @@
use cfg_if::cfg_if;
use std::future::Future;
/// Spawns and runs a thread-local [`Future`] in a platform-independent way.
/// Spawns and runs a thread-local [std::future::Future] in a platform-independent way.
///
/// This can be used to interface with any `async` code.
pub fn spawn_local<F>(fut: F)

View File

@@ -7,7 +7,7 @@ use cfg_if::cfg_if;
cfg_if! {
if #[cfg(all(target_arch = "wasm32", any(feature = "csr", feature = "hydrate")))] {
/// Exposes the [`queueMicrotask`](https://developer.mozilla.org/en-US/docs/Web/API/queueMicrotask) method
/// Exposes the [queueMicrotask](https://developer.mozilla.org/en-US/docs/Web/API/queueMicrotask) method
/// in the browser, and simply runs the given function when on the server.
pub fn queue_microtask(task: impl FnOnce() + 'static) {
microtask(wasm_bindgen::closure::Closure::once_into_js(task));
@@ -21,7 +21,7 @@ cfg_if! {
fn microtask(task: wasm_bindgen::JsValue);
}
} else {
/// Exposes the [`queueMicrotask`](https://developer.mozilla.org/en-US/docs/Web/API/queueMicrotask) method
/// Exposes the [queueMicrotask](https://developer.mozilla.org/en-US/docs/Web/API/queueMicrotask) method
/// in the browser, and simply runs the given function when on the server.
pub fn queue_microtask(task: impl FnOnce() + 'static) {
task();

View File

@@ -3,17 +3,17 @@ use crate::{with_runtime, RuntimeId, Scope, ScopeProperty};
use std::{cell::RefCell, marker::PhantomData, rc::Rc};
slotmap::new_key_type! {
/// Unique ID assigned to a [`StoredValue`].
/// Unique ID assigned to a [StoredValue].
pub(crate) struct StoredValueId;
}
/// A **non-reactive** wrapper for any value, which can be created with [`store_value`].
/// A **non-reactive** wrapper for any value, which can be created with [store_value].
///
/// If you want a reactive wrapper, use [`create_signal`](crate::create_signal).
/// If you want a reactive wrapper, use [create_signal](crate::create_signal).
///
/// This allows you to create a stable reference for any value by storing it within
/// the reactive system. Like the signal types (e.g., [`ReadSignal`](crate::ReadSignal)
/// and [`RwSignal`](crate::RwSignal)), it is `Copy` and `'static`. Unlike the signal
/// the reactive system. Like the signal types (e.g., [ReadSignal](crate::ReadSignal)
/// and [RwSignal](crate::RwSignal)), it is `Copy` and `'static`. Unlike the signal
/// types, it is not reactive; accessing it does not cause effects to subscribe, and
/// updating it does not notify anything else.
#[derive(Debug, PartialEq, Eq, Hash)]
@@ -43,7 +43,7 @@ impl<T> StoredValue<T> {
/// to this signal.
///
/// # Panics
/// Panics if you try to access a value stored in a [`Scope`] that has been disposed.
/// Panics if you try to access a value stored in a [Scope] that has been disposed.
///
/// # Examples
/// ```
@@ -77,7 +77,7 @@ impl<T> StoredValue<T> {
/// to this signal.
///
/// # Panics
/// Panics if you try to access a value stored in a [`Scope`] that has been disposed.
/// Panics if you try to access a value stored in a [Scope] that has been disposed.
///
/// # Examples
/// ```
@@ -128,7 +128,7 @@ impl<T> StoredValue<T> {
/// Applies a function to the current stored value.
///
/// # Panics
/// Panics if you try to access a value stored in a [`Scope`] that has been disposed.
/// Panics if you try to access a value stored in a [Scope] that has been disposed.
///
/// # Examples
/// ```
@@ -155,7 +155,7 @@ impl<T> StoredValue<T> {
/// Applies a function to the current stored value.
///
/// # Panics
/// Panics if you try to access a value stored in a [`Scope`] that has been disposed.
/// Panics if you try to access a value stored in a [Scope] that has been disposed.
///
/// # Examples
/// ```
@@ -375,8 +375,8 @@ impl<T> StoredValue<T> {
/// Creates a **non-reactive** wrapper for any value by storing it within
/// the reactive system.
///
/// Like the signal types (e.g., [`ReadSignal`](crate::ReadSignal)
/// and [`RwSignal`](crate::RwSignal)), it is `Copy` and `'static`. Unlike the signal
/// Like the signal types (e.g., [ReadSignal](crate::ReadSignal)
/// and [RwSignal](crate::RwSignal)), it is `Copy` and `'static`. Unlike the signal
/// types, it is not reactive; accessing it does not cause effects to subscribe, and
/// updating it does not notify anything else.
/// ```compile_fail
@@ -418,7 +418,7 @@ where
.insert(Rc::new(RefCell::new(value)))
})
.unwrap_or_default();
cx.push_scope_property(ScopeProperty::StoredValue(id));
cx.with_scope_property(|prop| prop.push(ScopeProperty::StoredValue(id)));
StoredValue {
runtime: cx.runtime,
id,

View File

@@ -8,7 +8,7 @@ use crate::{
use futures::Future;
use std::{borrow::Cow, collections::VecDeque, pin::Pin};
/// Tracks [`Resource`](crate::Resource)s that are read under a suspense context,
/// Tracks [Resource](crate::Resource)s that are read under a suspense context,
/// i.e., within a [`Suspense`](https://docs.rs/leptos_core/latest/leptos_core/fn.Suspense.html) component.
#[derive(Copy, Clone, Debug)]
pub struct SuspenseContext {

View File

@@ -1,252 +0,0 @@
#![forbid(unsafe_code)]
use crate::{
diagnostics,
diagnostics::*,
node::NodeId,
runtime::{with_runtime, RuntimeId},
Scope, ScopeProperty, SignalGet, SignalSet, SignalUpdate,
};
/// Reactive Trigger, notifies reactive code to rerun.
///
/// See [`create_trigger`] for more.
#[derive(Clone, Copy)]
pub struct Trigger {
pub(crate) runtime: RuntimeId,
pub(crate) id: NodeId,
#[cfg(debug_assertions)]
pub(crate) defined_at: &'static std::panic::Location<'static>,
}
impl Trigger {
/// Notifies any reactive code where this trigger is tracked to rerun.
pub fn notify(&self) {
assert!(self.try_notify(), "Trigger::notify(): runtime not alive")
}
/// Attempts to notify any reactive code where this trigger is tracked to rerun.
///
/// Returns `None` if the runtime has been disposed.
pub fn try_notify(&self) -> bool {
with_runtime(self.runtime, |runtime| {
runtime.mark_dirty(self.id);
runtime.run_effects();
})
.is_ok()
}
/// Subscribes the running effect to this trigger.
pub fn track(&self) {
assert!(self.try_track(), "Trigger::track(): runtime not alive")
}
/// Attempts to subscribe the running effect to this trigger, returning
/// `None` if the runtime has been disposed.
pub fn try_track(&self) -> bool {
let diagnostics = diagnostics!(self);
with_runtime(self.runtime, |runtime| {
self.id.subscribe(runtime, diagnostics);
})
.is_ok()
}
}
/// Creates a [`Trigger`], a kind of reactive primitive.
///
/// A trigger is a data-less signal with the sole purpose
/// of notifying other reactive code of a change. This can be useful
/// for when using external data not stored in signals, for example.
///
/// Take a reactive [`Scope`] and returns the [`Trigger`] handle, which
/// can be called as a function to track the trigger in the current
/// reactive context.
///
/// ```
/// # use leptos_reactive::*;
/// # create_scope(create_runtime(), |cx| {
/// use std::{cell::RefCell, fmt::Write, rc::Rc};
///
/// let external_data = Rc::new(RefCell::new(1));
/// let output = Rc::new(RefCell::new(String::new()));
///
/// let rerun_on_data = create_trigger(cx);
///
/// let o = output.clone();
/// let e = external_data.clone();
/// create_effect(cx, move |_| {
/// rerun_on_data(); // or rerun_on_data.track();
/// write!(o.borrow_mut(), "{}", *e.borrow());
/// *e.borrow_mut() += 1;
/// });
/// # if !cfg!(feature = "ssr") {
/// assert_eq!(*output.borrow(), "1");
///
/// rerun_on_data.notify(); // reruns the above effect
///
/// assert_eq!(*output.borrow(), "12");
/// # }
/// # }).dispose();
/// ```
#[cfg_attr(
debug_assertions,
instrument(
level = "trace",
skip_all,
fields(scope = ?cx.id)
)
)]
#[track_caller]
pub fn create_trigger(cx: Scope) -> Trigger {
let t = cx.runtime.create_trigger();
cx.push_scope_property(ScopeProperty::Trigger(t.id));
t
}
impl SignalGet<()> for Trigger {
#[cfg_attr(
debug_assertions,
instrument(
level = "trace",
name = "Trigger::get()",
skip_all,
fields(
id = ?self.id,
defined_at = %self.defined_at
)
)
)]
#[track_caller]
#[inline(always)]
fn get(&self) {
self.track()
}
#[cfg_attr(
debug_assertions,
instrument(
level = "trace",
name = "Trigger::try_get()",
skip_all,
fields(
id = ?self.id,
defined_at = %self.defined_at
)
)
)]
#[inline(always)]
fn try_get(&self) -> Option<()> {
self.try_track().then_some(())
}
}
impl SignalUpdate<()> for Trigger {
#[cfg_attr(
debug_assertions,
instrument(
name = "Trigger::update()",
level = "trace",
skip_all,
fields(
id = ?self.id,
defined_at = %self.defined_at
)
)
)]
#[inline(always)]
fn update(&self, f: impl FnOnce(&mut ())) {
self.try_update(f).expect("runtime to be alive")
}
#[cfg_attr(
debug_assertions,
instrument(
name = "Trigger::try_update()",
level = "trace",
skip_all,
fields(
id = ?self.id,
defined_at = %self.defined_at
)
)
)]
#[inline(always)]
fn try_update<O>(&self, f: impl FnOnce(&mut ()) -> O) -> Option<O> {
// run callback with runtime before dirtying the trigger,
// consistent with signals.
with_runtime(self.runtime, |runtime| {
let res = f(&mut ());
runtime.mark_dirty(self.id);
runtime.run_effects();
Some(res)
})
.ok()
.flatten()
}
}
impl SignalSet<()> for Trigger {
#[cfg_attr(
debug_assertions,
instrument(
level = "trace",
name = "Trigger::set()",
skip_all,
fields(
id = ?self.id,
defined_at = %self.defined_at
)
)
)]
#[inline(always)]
fn set(&self, _: ()) {
self.notify();
}
#[cfg_attr(
debug_assertions,
instrument(
level = "trace",
name = "Trigger::try_set()",
skip_all,
fields(
id = ?self.id,
defined_at = %self.defined_at
)
)
)]
#[inline(always)]
fn try_set(&self, _: ()) -> Option<()> {
self.try_notify().then_some(())
}
}
#[cfg(not(feature = "stable"))]
impl FnOnce<()> for Trigger {
type Output = ();
#[inline(always)]
extern "rust-call" fn call_once(self, _args: ()) -> Self::Output {
self.track()
}
}
#[cfg(not(feature = "stable"))]
impl FnMut<()> for Trigger {
#[inline(always)]
extern "rust-call" fn call_mut(&mut self, _args: ()) -> Self::Output {
self.track()
}
}
#[cfg(not(feature = "stable"))]
impl Fn<()> for Trigger {
#[inline(always)]
extern "rust-call" fn call(&self, _args: ()) -> Self::Output {
self.track()
}
}

View File

@@ -10,7 +10,7 @@ readme = "../README.md"
[dependencies]
leptos_reactive = { workspace = true }
server_fn = { workspace = true, default-features = false }
server_fn = { workspace = true }
lazy_static = "1"
serde = { version = "1", features = ["derive"] }
thiserror = "1"
@@ -19,11 +19,8 @@ thiserror = "1"
leptos = { path = "../leptos" }
[features]
default = ["default-tls"]
csr = ["leptos_reactive/csr"]
default-tls = ["server_fn/default-tls"]
hydrate = ["leptos_reactive/hydrate"]
rustls = ["server_fn/rustls"]
ssr = ["leptos_reactive/ssr", "server_fn/ssr"]
stable = ["leptos_reactive/stable", "server_fn/stable"]

View File

@@ -3,7 +3,6 @@ use crate::TextProp;
/// A collection of additional HTML attributes to be applied to an element,
/// each of which may or may not be reactive.
#[derive(Default, Clone)]
#[repr(transparent)]
pub struct AdditionalAttributes(pub(crate) Vec<(String, TextProp)>);
impl<I, T, U> From<I> for AdditionalAttributes
@@ -23,7 +22,6 @@ where
}
/// Iterator over additional HTML attributes.
#[repr(transparent)]
pub struct AdditionalAttributesIter<'a>(
std::slice::Iter<'a, (String, TextProp)>,
);
@@ -31,7 +29,6 @@ pub struct AdditionalAttributesIter<'a>(
impl<'a> Iterator for AdditionalAttributesIter<'a> {
type Item = &'a (String, TextProp);
#[inline(always)]
fn next(&mut self) -> Option<Self::Item> {
self.0.next()
}
@@ -42,6 +39,6 @@ impl<'a> IntoIterator for &'a AdditionalAttributes {
type IntoIter = AdditionalAttributesIter<'a>;
fn into_iter(self) -> Self::IntoIter {
AdditionalAttributesIter(self.0.iter())
todo!()
}
}

View File

@@ -1,3 +1,4 @@
use crate::{additional_attributes::AdditionalAttributes, TextProp};
use cfg_if::cfg_if;
use leptos::*;
use std::{cell::RefCell, rc::Rc};
@@ -19,7 +20,8 @@ impl BodyContext {
.map(|val| format!("class=\"{}\"", val.get()));
let attributes = self.attributes.borrow().as_ref().map(|val| {
val.with(|val| {
val.into_iter()
val.0
.iter()
.map(|(n, v)| format!("{}=\"{}\"", n, v.get()))
.collect::<Vec<_>>()
.join(" ")
@@ -100,10 +102,8 @@ pub fn Body(
if let Some(attributes) = attributes {
let attributes = attributes.get();
for (attr_name, attr_value) in attributes.into_iter() {
for (attr_name, attr_value) in attributes.0.into_iter() {
let el = el.clone();
let attr_name = attr_name.to_owned();
let attr_value = attr_value.to_owned();
create_render_effect(cx, move |_|{
let value = attr_value.get();
_ = el.set_attribute(&attr_name, &value);

View File

@@ -1,3 +1,4 @@
use crate::{additional_attributes::AdditionalAttributes, TextProp};
use cfg_if::cfg_if;
use leptos::*;
use std::{cell::RefCell, rc::Rc};
@@ -31,7 +32,8 @@ impl HtmlContext {
.map(|val| format!("class=\"{}\"", val.get()));
let attributes = self.attributes.borrow().as_ref().map(|val| {
val.with(|val| {
val.into_iter()
val.0
.iter()
.map(|(n, v)| format!("{}=\"{}\"", n, v.get()))
.collect::<Vec<_>>()
.join(" ")
@@ -129,10 +131,8 @@ pub fn Html(
if let Some(attributes) = attributes {
let attributes = attributes.get();
for (attr_name, attr_value) in attributes.into_iter() {
for (attr_name, attr_value) in attributes.0.into_iter() {
let el = el.clone();
let attr_name = attr_name.to_owned();
let attr_value = attr_value.to_owned();
create_render_effect(cx, move |_|{
let value = attr_value.get();
_ = el.set_attribute(&attr_name, &value);

View File

@@ -50,7 +50,6 @@ use leptos::{
*,
};
use std::{
borrow::Cow,
cell::{Cell, RefCell},
collections::HashMap,
fmt::Debug,
@@ -59,6 +58,7 @@ use std::{
#[cfg(any(feature = "csr", feature = "hydrate"))]
use wasm_bindgen::{JsCast, UnwrapThrowExt};
mod additional_attributes;
mod body;
mod html;
mod link;
@@ -67,6 +67,7 @@ mod script;
mod style;
mod stylesheet;
mod title;
pub use additional_attributes::*;
pub use body::*;
pub use html::*;
pub use link::*;
@@ -100,7 +101,7 @@ pub struct MetaTagsContext {
els: Rc<
RefCell<
HashMap<
Cow<'static, str>,
String,
(HtmlElement<AnyElement>, Scope, Option<web_sys::Element>),
>,
>,
@@ -130,7 +131,7 @@ impl MetaTagsContext {
pub fn register(
&self,
cx: Scope,
id: Cow<'static, str>,
id: String,
builder_el: HtmlElement<AnyElement>,
) {
cfg_if! {
@@ -307,6 +308,45 @@ pub fn generate_head_metadata_separated(cx: Scope) -> (String, String) {
(head, format!("<body{body_meta}>"))
}
/// Describes a value that is either a static or a reactive string, i.e.,
/// a [String], a [&str], or a reactive `Fn() -> String`.
#[derive(Clone)]
pub struct TextProp(Rc<dyn Fn() -> String>);
impl TextProp {
fn get(&self) -> String {
(self.0)()
}
}
impl Debug for TextProp {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("TextProp").finish()
}
}
impl From<String> for TextProp {
fn from(s: String) -> Self {
TextProp(Rc::new(move || s.clone()))
}
}
impl From<&str> for TextProp {
fn from(s: &str) -> Self {
let s = s.to_string();
TextProp(Rc::new(move || s.clone()))
}
}
impl<F> From<F> for TextProp
where
F: Fn() -> String + 'static,
{
fn from(s: F) -> Self {
TextProp(Rc::new(s))
}
}
#[cfg(debug_assertions)]
pub(crate) fn feature_warning() {
if !cfg!(any(feature = "csr", feature = "hydrate", feature = "ssr")) {

View File

@@ -1,6 +1,5 @@
use crate::use_head;
use leptos::*;
use std::borrow::Cow;
/// Injects an [HTMLLinkElement](https://developer.mozilla.org/en-US/docs/Web/API/HTMLLinkElement) into the document
/// head, accepting any of the valid attributes for that tag.
@@ -29,69 +28,68 @@ pub fn Link(
cx: Scope,
/// The [`id`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link#attr-id) attribute.
#[prop(optional, into)]
id: Option<Cow<'static, str>>,
id: Option<String>,
/// The [`as`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link#attr-as) attribute.
#[prop(optional, into)]
as_: Option<Cow<'static, str>>,
as_: Option<String>,
/// The [`crossorigin`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link#attr-crossorigin) attribute.
#[prop(optional, into)]
crossorigin: Option<Cow<'static, str>>,
crossorigin: Option<String>,
/// The [`disabled`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link#attr-disabled) attribute.
#[prop(optional, into)]
disabled: Option<bool>,
/// The [`fetchpriority`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link#attr-fetchpriority) attribute.
#[prop(optional, into)]
fetchpriority: Option<Cow<'static, str>>,
fetchpriority: Option<String>,
/// The [`href`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link#attr-href) attribute.
#[prop(optional, into)]
href: Option<Cow<'static, str>>,
href: Option<String>,
/// The [`hreflang`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link#attr-hreflang) attribute.
#[prop(optional, into)]
hreflang: Option<Cow<'static, str>>,
hreflang: Option<String>,
/// The [`imagesizes`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link#attr-imagesizes) attribute.
#[prop(optional, into)]
imagesizes: Option<Cow<'static, str>>,
imagesizes: Option<String>,
/// The [`imagesrcset`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link#attr-imagesrcset) attribute.
#[prop(optional, into)]
imagesrcset: Option<Cow<'static, str>>,
imagesrcset: Option<String>,
/// The [`integrity`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link#attr-integrity) attribute.
#[prop(optional, into)]
integrity: Option<Cow<'static, str>>,
integrity: Option<String>,
/// The [`media`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link#attr-media) attribute.
#[prop(optional, into)]
media: Option<Cow<'static, str>>,
media: Option<String>,
/// The [`prefetch`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link#attr-prefetch) attribute.
#[prop(optional, into)]
prefetch: Option<Cow<'static, str>>,
prefetch: Option<String>,
/// The [`referrerpolicy`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link#attr-referrerpolicy) attribute.
#[prop(optional, into)]
referrerpolicy: Option<Cow<'static, str>>,
referrerpolicy: Option<String>,
/// The [`rel`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link#attr-rel) attribute.
#[prop(optional, into)]
rel: Option<Cow<'static, str>>,
rel: Option<String>,
/// The [`sizes`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link#attr-sizes) attribute.
#[prop(optional, into)]
sizes: Option<Cow<'static, str>>,
sizes: Option<String>,
/// The [`title`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link#attr-title) attribute.
#[prop(optional, into)]
title: Option<Cow<'static, str>>,
title: Option<String>,
/// The [`type`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link#attr-type) attribute.
#[prop(optional, into)]
type_: Option<Cow<'static, str>>,
type_: Option<String>,
/// The [`blocking`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link#attr-blocking) attribute.
#[prop(optional, into)]
blocking: Option<Cow<'static, str>>,
blocking: Option<String>,
) -> impl IntoView {
let meta = use_head(cx);
let next_id = meta.tags.get_next_id();
let id: Cow<'static, str> =
id.unwrap_or_else(|| format!("leptos-link-{}", next_id.0).into());
let id = id.unwrap_or_else(|| format!("leptos-link-{}", next_id.0));
let builder_el = leptos::leptos_dom::html::as_meta_tag({
let id = id.clone();
move || {
leptos::leptos_dom::html::link(cx)
.attr("id", id)
.attr("id", &id)
.attr("as", as_)
.attr("crossorigin", crossorigin)
.attr("disabled", disabled.unwrap_or(false))

View File

@@ -53,5 +53,5 @@ pub fn Meta(
.attr("content", move || content.as_ref().map(|v| v.get()))
});
meta.tags.register(cx, id.into(), builder_el.into_any());
meta.tags.register(cx, id, builder_el.into_any());
}

View File

@@ -1,6 +1,5 @@
use crate::use_head;
use leptos::*;
use std::borrow::Cow;
/// Injects an [HTMLScriptElement](https://developer.mozilla.org/en-US/docs/Web/API/HTMLScriptElement) into the document
/// head, accepting any of the valid attributes for that tag.
@@ -26,54 +25,53 @@ pub fn Script(
cx: Scope,
/// An ID for the `<script>` tag.
#[prop(optional, into)]
id: Option<Cow<'static, str>>,
id: Option<String>,
/// The [`async`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attr-async) attribute.
#[prop(optional, into)]
async_: Option<Cow<'static, str>>,
async_: Option<String>,
/// The [`crossorigin`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attr-crossorigin) attribute.
#[prop(optional, into)]
crossorigin: Option<Cow<'static, str>>,
crossorigin: Option<String>,
/// The [`defer`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attr-defer) attribute.
#[prop(optional, into)]
defer: Option<Cow<'static, str>>,
defer: Option<String>,
/// The [`fetchpriority `](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attr-fetchpriority ) attribute.
#[prop(optional, into)]
fetchpriority: Option<Cow<'static, str>>,
fetchpriority: Option<String>,
/// The [`integrity`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attr-integrity) attribute.
#[prop(optional, into)]
integrity: Option<Cow<'static, str>>,
integrity: Option<String>,
/// The [`nomodule`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attr-nomodule) attribute.
#[prop(optional, into)]
nomodule: Option<Cow<'static, str>>,
nomodule: Option<String>,
/// The [`nonce`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attr-nonce) attribute.
#[prop(optional, into)]
nonce: Option<Cow<'static, str>>,
nonce: Option<String>,
/// The [`referrerpolicy`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attr-referrerpolicy) attribute.
#[prop(optional, into)]
referrerpolicy: Option<Cow<'static, str>>,
referrerpolicy: Option<String>,
/// The [`src`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attr-src) attribute.
#[prop(optional, into)]
src: Option<Cow<'static, str>>,
src: Option<String>,
/// The [`type`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attr-type) attribute.
#[prop(optional, into)]
type_: Option<Cow<'static, str>>,
type_: Option<String>,
/// The [`blocking`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attr-blocking) attribute.
#[prop(optional, into)]
blocking: Option<Cow<'static, str>>,
blocking: Option<String>,
/// The content of the `<script>` tag.
#[prop(optional)]
children: Option<Box<dyn FnOnce(Scope) -> Fragment>>,
) -> impl IntoView {
let meta = use_head(cx);
let next_id = meta.tags.get_next_id();
let id: Cow<'static, str> =
id.unwrap_or_else(|| format!("leptos-link-{}", next_id.0).into());
let id = id.unwrap_or_else(|| format!("leptos-link-{}", next_id.0));
let builder_el = leptos::leptos_dom::html::as_meta_tag({
let id = id.clone();
move || {
leptos::leptos_dom::html::script(cx)
.attr("id", id)
.attr("id", &id)
.attr("async", async_)
.attr("crossorigin", crossorigin)
.attr("defer", defer)

View File

@@ -1,6 +1,5 @@
use crate::use_head;
use leptos::*;
use std::borrow::Cow;
/// Injects an [HTMLStyleElement](https://developer.mozilla.org/en-US/docs/Web/API/HTMLStyleElement) into the document
/// head, accepting any of the valid attributes for that tag.
@@ -26,33 +25,32 @@ pub fn Style(
cx: Scope,
/// An ID for the `<script>` tag.
#[prop(optional, into)]
id: Option<Cow<'static, str>>,
id: Option<String>,
/// The [`media`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/style#attr-media) attribute.
#[prop(optional, into)]
media: Option<Cow<'static, str>>,
media: Option<String>,
/// The [`nonce`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/style#attr-nonce) attribute.
#[prop(optional, into)]
nonce: Option<Cow<'static, str>>,
nonce: Option<String>,
/// The [`title`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/style#attr-title) attribute.
#[prop(optional, into)]
title: Option<Cow<'static, str>>,
title: Option<String>,
/// The [`blocking`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/style#attr-blocking) attribute.
#[prop(optional, into)]
blocking: Option<Cow<'static, str>>,
blocking: Option<String>,
/// The content of the `<style>` tag.
#[prop(optional)]
children: Option<Box<dyn FnOnce(Scope) -> Fragment>>,
) -> impl IntoView {
let meta = use_head(cx);
let next_id = meta.tags.get_next_id();
let id: Cow<'static, str> =
id.unwrap_or_else(|| format!("leptos-link-{}", next_id.0).into());
let id = id.unwrap_or_else(|| format!("leptos-link-{}", next_id.0));
let builder_el = leptos::leptos_dom::html::as_meta_tag({
let id = id.clone();
move || {
leptos::leptos_dom::html::style(cx)
.attr("id", id)
.attr("id", &id)
.attr("media", media)
.attr("nonce", nonce)
.attr("title", title)

View File

@@ -17,7 +17,7 @@ pub struct TitleContext {
impl TitleContext {
/// Converts the title into a string that can be used as the text content of a `<title>` tag.
pub fn as_string(&self) -> Option<String> {
let title = self.text.borrow().as_ref().map(|f| f.get());
let title = self.text.borrow().as_ref().map(|f| (f.0)());
title.map(|title| {
if let Some(formatter) = &*self.formatter.borrow() {
(formatter.0)(title)
@@ -35,14 +35,12 @@ impl std::fmt::Debug for TitleContext {
}
/// A function that is applied to the text value before setting `document.title`.
#[repr(transparent)]
pub struct Formatter(Box<dyn Fn(String) -> String>);
impl<F> From<F> for Formatter
where
F: Fn(String) -> String + 'static,
{
#[inline(always)]
fn from(f: F) -> Formatter {
Formatter(Box::new(f))
}

View File

@@ -10,12 +10,11 @@ description = "Router for the Leptos web framework."
[dependencies]
leptos = { workspace = true }
cached = { optional = true }
cfg-if = "1"
common_macros = "0.1"
gloo-net = { version = "0.2", features = ["http"] }
lazy_static = "1"
linear-map = { version = "1", features = ["serde_impl"] }
linear-map = "1"
log = "0.4"
regex = { version = "1", optional = true }
url = { version = "2", optional = true }
@@ -27,7 +26,6 @@ tracing = "0.1"
js-sys = { version = "0.3" }
wasm-bindgen = { version = "0.2" }
wasm-bindgen-futures = { version = "0.4" }
lru = { version = "0.10", optional = true }
[dependencies.web-sys]
version = "0.3"
@@ -58,7 +56,7 @@ features = [
default = []
csr = ["leptos/csr"]
hydrate = ["leptos/hydrate"]
ssr = ["leptos/ssr", "dep:cached", "dep:lru", "dep:url", "dep:regex"]
ssr = ["leptos/ssr", "dep:url", "dep:regex"]
stable = ["leptos/stable"]
[package.metadata.cargo-all-features]

View File

@@ -1,96 +0,0 @@
/// Configures what animation should be shown when transitioning
/// between two root routes. Defaults to `None`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Animation {
/// Class set when a route is first painted.
pub start: Option<&'static str>,
/// Class set when a route is fading out.
pub outro: Option<&'static str>,
/// Class set when a route is fading in.
pub intro: Option<&'static str>,
/// Class set when a route is fading out, if its a “back” navigation.
pub outro_back: Option<&'static str>,
/// Class set when a route is fading in, if its a “back” navigation.
pub intro_back: Option<&'static str>,
/// Class set when all animations have finished.
pub finally: Option<&'static str>,
}
impl Animation {
pub(crate) fn next_state(
&self,
current: &AnimationState,
is_back: bool,
) -> (AnimationState, bool) {
let Animation {
start,
outro,
intro,
intro_back,
..
} = self;
match current {
AnimationState::Outro => {
let next = if start.is_some() {
AnimationState::Start
} else if intro.is_some() {
AnimationState::Intro
} else {
AnimationState::Finally
};
(next, true)
}
AnimationState::OutroBack => {
let next = if start.is_some() {
AnimationState::Start
} else if intro_back.is_some() {
AnimationState::IntroBack
} else if intro.is_some() {
AnimationState::Intro
} else {
AnimationState::Finally
};
(next, true)
}
AnimationState::Start => {
let next = if intro.is_some() {
AnimationState::Intro
} else {
AnimationState::Finally
};
(next, false)
}
AnimationState::Intro => (AnimationState::Finally, false),
AnimationState::IntroBack => (AnimationState::Finally, false),
AnimationState::Finally => {
if outro.is_some() {
if is_back {
(AnimationState::OutroBack, false)
} else {
(AnimationState::Outro, false)
}
} else if start.is_some() {
(AnimationState::Start, true)
} else if intro.is_some() {
if is_back {
(AnimationState::IntroBack, false)
} else {
(AnimationState::Intro, false)
}
} else {
(AnimationState::Finally, true)
}
}
}
}
}
#[derive(Copy, Clone, PartialEq, Eq, Debug, PartialOrd, Ord)]
pub(crate) enum AnimationState {
Outro,
OutroBack,
Start,
Intro,
IntroBack,
Finally,
}

View File

@@ -1,5 +1,5 @@
use crate::{use_navigate, use_resolved_path, ToHref, Url};
use leptos::{html::form, *};
use leptos::*;
use std::{error::Error, rc::Rc};
use wasm_bindgen::{JsCast, UnwrapThrowExt};
use wasm_bindgen_futures::JsFuture;
@@ -42,12 +42,6 @@ pub fn Form<A>(
/// to a form submission.
#[prop(optional)]
on_response: Option<OnResponse>,
/// A [`NodeRef`] in which the `<form>` element should be stored.
#[prop(optional)]
node_ref: Option<NodeRef<html::Form>>,
/// Arbitrary attributes to add to the `<form>`
#[prop(optional, into)]
attributes: Option<MaybeSignal<AdditionalAttributes>>,
/// Component children; should include the HTML of the form elements.
children: Children,
) -> impl IntoView
@@ -65,8 +59,6 @@ where
on_response: Option<OnResponse>,
class: Option<Attribute>,
children: Children,
node_ref: Option<NodeRef<html::Form>>,
attributes: Option<MaybeSignal<AdditionalAttributes>>,
) -> HtmlElement<html::Form> {
let action_version = version;
let on_submit = move |ev: web_sys::SubmitEvent| {
@@ -160,25 +152,17 @@ where
let method = method.unwrap_or("get");
let mut form = form(cx)
.attr("method", method)
.attr("action", move || action.get())
.attr("enctype", enctype)
.on(ev::submit, on_submit)
.attr("class", class)
.child(children(cx));
if let Some(node_ref) = node_ref {
form = form.node_ref(node_ref)
};
if let Some(attributes) = attributes {
let attributes = attributes.get();
for (attr_name, attr_value) in attributes.into_iter() {
let attr_name = attr_name.to_owned();
let attr_value = attr_value.to_owned();
form = form.attr(attr_name, move || attr_value.get());
}
view! { cx,
<form
method=method
action=move || action.get()
enctype=enctype
on:submit=on_submit
class=class
>
{children(cx)}
</form>
}
form
}
let action = use_resolved_path(cx, move || action.to_href()());
@@ -194,8 +178,6 @@ where
on_response,
class,
children,
node_ref,
attributes,
)
}
@@ -215,12 +197,6 @@ pub fn ActionForm<I, O>(
/// A signal that will be set if the form submission ends in an error.
#[prop(optional)]
error: Option<RwSignal<Option<Box<dyn Error>>>>,
/// A [`NodeRef`] in which the `<form>` element should be stored.
#[prop(optional)]
node_ref: Option<NodeRef<html::Form>>,
/// Arbitrary attributes to add to the `<form>`
#[prop(optional, into)]
attributes: Option<MaybeSignal<AdditionalAttributes>>,
/// Component children; should include the HTML of the form elements.
children: Children,
) -> impl IntoView
@@ -310,18 +286,19 @@ where
});
});
let class = class.map(|bx| bx.into_attribute_boxed(cx));
let mut props = FormProps::builder()
let props = FormProps::builder()
.action(action_url)
.version(version)
.on_form_data(on_form_data)
.on_response(on_response)
.method("post")
.class(class)
.children(children)
.build();
props.error = error;
props.node_ref = node_ref;
props.attributes = attributes;
.children(children);
let props = if let Some(error) = error {
props.error(error).build()
} else {
props.build()
};
Form(cx, props)
}
@@ -341,12 +318,6 @@ pub fn MultiActionForm<I, O>(
/// A signal that will be set if the form submission ends in an error.
#[prop(optional)]
error: Option<RwSignal<Option<Box<dyn Error>>>>,
/// A [`NodeRef`] in which the `<form>` element should be stored.
#[prop(optional)]
node_ref: Option<NodeRef<html::Form>>,
/// Arbitrary attributes to add to the `<form>`
#[prop(optional, into)]
attributes: Option<MaybeSignal<AdditionalAttributes>>,
/// Component children; should include the HTML of the form elements.
children: Children,
) -> impl IntoView
@@ -389,24 +360,16 @@ where
};
let class = class.map(|bx| bx.into_attribute_boxed(cx));
let mut form = form(cx)
.attr("method", "POST")
.attr("action", action)
.on(ev::submit, on_submit)
.attr("class", class)
.child(children(cx));
if let Some(node_ref) = node_ref {
form = form.node_ref(node_ref)
};
if let Some(attributes) = attributes {
let attributes = attributes.get();
for (attr_name, attr_value) in attributes.into_iter() {
let attr_name = attr_name.to_owned();
let attr_value = attr_value.to_owned();
form = form.attr(attr_name, move || attr_value.get());
}
view! { cx,
<form
method="POST"
action=action
class=class
on:submit=on_submit
>
{children(cx)}
</form>
}
form
}
fn extract_form_attributes(

View File

@@ -1,10 +1,6 @@
use crate::{
animation::{Animation, AnimationState},
use_is_back_navigation, use_route,
};
use crate::use_route;
use leptos::{leptos_dom::HydrationCtx, *};
use std::{cell::Cell, rc::Rc};
use web_sys::AnimationEvent;
/// Displays the child route nested in a parent route, allowing you to control exactly where
/// that child route is displayed. Renders nothing if there is no nested child.
@@ -43,142 +39,3 @@ pub fn Outlet(cx: Scope) -> impl IntoView {
leptos::leptos_dom::DynChild::new_with_id(id, move || outlet.get())
}
/// Displays the child route nested in a parent route, allowing you to control exactly where
/// that child route is displayed. Renders nothing if there is no nested child.
///
/// ## Animations
/// The router uses CSS classes for animations, and transitions to the next specified class in order when
/// the `animationend` event fires. Each property takes a `&'static str` that can contain a class or classes
/// to be added at certain points. These CSS classes must have associated animations.
/// - `outro`: added when route is being unmounted
/// - `start`: added when route is first created
/// - `intro`: added after `start` has completed (if defined), and the route is being mounted
/// - `finally`: added after the `intro` animation is complete
///
/// Each of these properties is optional, and the router will transition to the next correct state
/// whenever an `animationend` event fires.
#[component]
pub fn AnimatedOutlet(
cx: Scope,
/// Base classes to be applied to the `<div>` wrapping the outlet during any animation state.
#[prop(optional, into)]
class: Option<TextProp>,
/// CSS class added when route is being unmounted
#[prop(optional)]
outro: Option<&'static str>,
/// CSS class added when route is being unmounted, in a “back” navigation
#[prop(optional)]
outro_back: Option<&'static str>,
/// CSS class added when route is first created
#[prop(optional)]
start: Option<&'static str>,
/// CSS class added while the route is being mounted
#[prop(optional)]
intro: Option<&'static str>,
/// CSS class added while the route is being mounted, in a “back” navigation
#[prop(optional)]
intro_back: Option<&'static str>,
/// CSS class added after other animations have completed.
#[prop(optional)]
finally: Option<&'static str>,
) -> impl IntoView {
let route = use_route(cx);
let is_showing = Rc::new(Cell::new(None::<(usize, Scope)>));
let (outlet, set_outlet) = create_signal(cx, None::<View>);
let animation = Animation {
outro,
start,
intro,
finally,
outro_back,
intro_back,
};
let (animation_state, set_animation_state) =
create_signal(cx, AnimationState::Finally);
let trigger_animation = create_rw_signal(cx, ());
let is_back = use_is_back_navigation(cx);
let animation_and_outlet = create_memo(cx, {
move |prev: Option<&(AnimationState, View)>| {
let animation_state = animation_state.get();
let next_outlet = outlet.get().unwrap_or_default();
trigger_animation.track();
match prev {
None => (animation_state, next_outlet),
Some((prev_state, prev_outlet)) => {
let (next_state, can_advance) = animation
.next_state(prev_state, is_back.get_untracked());
if can_advance {
(next_state, next_outlet)
} else {
(next_state, prev_outlet.to_owned())
}
}
}
}
});
let current_animation =
create_memo(cx, move |_| animation_and_outlet.get().0);
let current_outlet = create_memo(cx, move |_| animation_and_outlet.get().1);
create_isomorphic_effect(cx, move |_| {
match (route.child(cx), &is_showing.get()) {
(None, prev) => {
if let Some(prev_scope) = prev.map(|(_, scope)| scope) {
prev_scope.dispose();
}
set_outlet.set(None);
}
(Some(child), Some((is_showing_val, _)))
if child.id() == *is_showing_val =>
{
// do nothing: we don't need to rerender the component, because it's the same
trigger_animation.set(());
}
(Some(child), prev) => {
if let Some(prev_scope) = prev.map(|(_, scope)| scope) {
prev_scope.dispose();
}
_ = cx.child_scope(|child_cx| {
provide_context(child_cx, child.clone());
set_outlet
.set(Some(child.outlet(child_cx).into_view(child_cx)));
is_showing.set(Some((child.id(), child_cx)));
});
}
}
});
let class = move || {
let animation_class = match current_animation.get() {
AnimationState::Outro => outro.unwrap_or_default(),
AnimationState::Start => start.unwrap_or_default(),
AnimationState::Intro => intro.unwrap_or_default(),
AnimationState::Finally => finally.unwrap_or_default(),
AnimationState::OutroBack => outro_back.unwrap_or_default(),
AnimationState::IntroBack => intro_back.unwrap_or_default(),
};
if let Some(class) = &class {
format!("{} {animation_class}", class.get())
} else {
animation_class.to_string()
}
};
let animationend = move |ev: AnimationEvent| {
ev.stop_propagation();
let current = current_animation.get();
set_animation_state.update(|current_state| {
let (next, _) =
animation.next_state(&current, is_back.get_untracked());
*current_state = next;
});
};
view! { cx,
<div class=class on:animationend=animationend>
{move || current_outlet.get()}
</div>
}
}

View File

@@ -9,28 +9,6 @@ thread_local! {
static ROUTE_ID: Cell<usize> = Cell::new(0);
}
/// 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,
}
/// Describes a portion of the nested layout of the app, specifying the route it should match,
/// the element it should display, and data that should be loaded alongside the route.
#[component(transparent)]
@@ -47,9 +25,6 @@ pub fn Route<E, F, P>(
/// The mode that this route prefers during server-side rendering. Defaults to out-of-order streaming.
#[prop(optional)]
ssr: SsrMode,
/// The HTTP methods that this route can handle (defaults to only `GET`).
#[prop(default = &[Method::Get])]
methods: &'static [Method],
/// `children` may be empty or include nested routes.
#[prop(optional)]
children: Option<Children>,
@@ -65,7 +40,6 @@ where
path.to_string(),
Rc::new(move |cx| view(cx).into_view(cx)),
ssr,
methods,
)
}
@@ -88,9 +62,6 @@ pub fn ProtectedRoute<P, E, F, C>(
/// The mode that this route prefers during server-side rendering. Defaults to out-of-order streaming.
#[prop(optional)]
ssr: SsrMode,
/// The HTTP methods that this route can handle (defaults to only `GET`).
#[prop(default = &[Method::Get])]
methods: &'static [Method],
/// `children` may be empty or include nested routes.
#[prop(optional)]
children: Option<Children>,
@@ -117,7 +88,6 @@ where
}
}),
ssr,
methods,
)
}
@@ -127,7 +97,6 @@ pub(crate) fn define_route(
path: String,
view: Rc<dyn Fn(Scope) -> View>,
ssr_mode: SsrMode,
methods: &'static [Method],
) -> RouteDefinition {
let children = children
.map(|children| {
@@ -156,7 +125,6 @@ pub(crate) fn define_route(
children,
view,
ssr_mode,
methods,
}
}

View File

@@ -54,7 +54,6 @@ pub(crate) struct RouterContextInner {
referrers: Rc<RefCell<Vec<LocationChange>>>,
state: ReadSignal<State>,
set_state: WriteSignal<State>,
pub(crate) is_back: RwSignal<bool>,
}
impl std::fmt::Debug for RouterContextInner {
@@ -111,7 +110,6 @@ impl RouterContext {
replace: true,
scroll: false,
state: State(None),
back: false,
});
}
}
@@ -164,7 +162,6 @@ impl RouterContext {
state,
set_state,
possible_routes: Default::default(),
is_back: create_rw_signal(cx, false),
});
// handle all click events on anchor tags
@@ -203,7 +200,6 @@ impl RouterContextInner {
self: Rc<Self>,
to: &str,
options: &NavigateOptions,
back: bool,
) -> Result<(), NavigationError> {
let cx = self.cx;
let this = Rc::clone(&self);
@@ -231,7 +227,6 @@ impl RouterContextInner {
replace: options.replace,
scroll: options.scroll,
state: self.state.get(),
back,
});
}
let len = self.referrers.borrow().len();
@@ -255,7 +250,6 @@ impl RouterContextInner {
replace: false,
scroll: true,
state,
back,
})
}
}
@@ -365,9 +359,8 @@ impl RouterContextInner {
scroll: !a.has_attribute("noscroll"),
state: State(state),
},
false,
) {
leptos::error!("{e:#?}");
log::error!("{e:#?}");
}
}
}

Some files were not shown because too many files have changed in this diff Show More