mirror of
https://github.com/leptos-rs/leptos.git
synced 2025-12-27 16:54:41 -05:00
Compare commits
18 Commits
async-docs
...
perf
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9ae3f6f7f0 | ||
|
|
73f67d9a55 | ||
|
|
8643126d09 | ||
|
|
99d28ed045 | ||
|
|
3d50ca32cd | ||
|
|
e576d93f83 | ||
|
|
e71779b8a6 | ||
|
|
0301c7f1cf | ||
|
|
46e6e7629c | ||
|
|
a985ae5660 | ||
|
|
efe29fd057 | ||
|
|
05b5b25c0e | ||
|
|
46f6deddbf | ||
|
|
e9c4b490e5 | ||
|
|
f7d0eea04d | ||
|
|
bf246a62e7 | ||
|
|
b8acfd758d | ||
|
|
dc8fd37461 |
21
Cargo.toml
21
Cargo.toml
@@ -11,6 +11,7 @@ members = [
|
||||
# integrations
|
||||
"integrations/actix",
|
||||
"integrations/axum",
|
||||
"integrations/viz",
|
||||
"integrations/utils",
|
||||
|
||||
# libraries
|
||||
@@ -20,18 +21,18 @@ members = [
|
||||
exclude = ["benchmarks", "examples"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.2.0-beta"
|
||||
version = "0.2.0"
|
||||
|
||||
[workspace.dependencies]
|
||||
leptos = { path = "./leptos", default-features = false, version = "0.2.0-beta" }
|
||||
leptos_dom = { path = "./leptos_dom", default-features = false, version = "0.2.0-beta" }
|
||||
leptos_macro = { path = "./leptos_macro", default-features = false, version = "0.2.0-beta" }
|
||||
leptos_reactive = { path = "./leptos_reactive", default-features = false, version = "0.2.0-beta" }
|
||||
leptos_server = { path = "./leptos_server", default-features = false, version = "0.2.0-beta" }
|
||||
leptos_config = { path = "./leptos_config", default-features = false, version = "0.2.0-beta" }
|
||||
leptos_router = { path = "./router", version = "0.2.0-beta" }
|
||||
leptos_meta = { path = "./meta", default-feature = false, version = "0.2.0-beta" }
|
||||
leptos_integration_utils = { path = "./integrations/utils", version = "0.2.0-beta" }
|
||||
leptos = { path = "./leptos", default-features = false, version = "0.2.0" }
|
||||
leptos_dom = { path = "./leptos_dom", default-features = false, version = "0.2.0" }
|
||||
leptos_macro = { path = "./leptos_macro", default-features = false, version = "0.2.0" }
|
||||
leptos_reactive = { path = "./leptos_reactive", default-features = false, version = "0.2.0" }
|
||||
leptos_server = { path = "./leptos_server", default-features = false, version = "0.2.0" }
|
||||
leptos_config = { path = "./leptos_config", default-features = false, version = "0.2.0" }
|
||||
leptos_router = { path = "./router", version = "0.2.0" }
|
||||
leptos_meta = { path = "./meta", default-feature = false, version = "0.2.0" }
|
||||
leptos_integration_utils = { path = "./integrations/utils", version = "0.2.0" }
|
||||
|
||||
[profile.release]
|
||||
codegen-units = 1
|
||||
|
||||
@@ -40,6 +40,7 @@ dependencies = [
|
||||
{ name = "check", path = "examples/tailwind" },
|
||||
{ name = "check", path = "examples/todo_app_sqlite" },
|
||||
{ name = "check", path = "examples/todo_app_sqlite_axum" },
|
||||
{ name = "check", path = "examples/todo_app_sqlite_viz" },
|
||||
{ name = "check", path = "examples/todomvc" },
|
||||
]
|
||||
|
||||
|
||||
@@ -14,11 +14,11 @@
|
||||
- [Passing Children to Components](./view/09_component_children.md)
|
||||
- [Interlude: Reactivity and Functions](./interlude_functions.md)
|
||||
- [Testing](./testing.md)
|
||||
- [Interlude: Styling — CSS, Tailwind, Style.rs, and more]()
|
||||
- [Async]()
|
||||
- [Resource]()
|
||||
- [Suspense]()
|
||||
- [Async](./async/README.md)
|
||||
- [Loading Data with Resources](./async/10_resources.md)
|
||||
- [Suspense](./async/11_suspense.md)
|
||||
- [Transition]()
|
||||
- [Interlude: Styling — CSS, Tailwind, Style.rs, and more]()
|
||||
- [State Management]()
|
||||
- [Interlude: Advanced Reactivity]()
|
||||
- [Router]()
|
||||
|
||||
53
docs/book/src/async/10_resources.md
Normal file
53
docs/book/src/async/10_resources.md
Normal file
@@ -0,0 +1,53 @@
|
||||
# Loading Data with Resources
|
||||
|
||||
A [Resource](https://docs.rs/leptos/latest/leptos/struct.Resource.html) is a reactive data structure that reflects the current state of an asynchronous task, allowing you to integrate asynchronous `Future`s into the synchronous reactive system. Rather than waiting for its data to load with `.await`, you transform the `Future` into a signal that returns `Some(T)` if it has resolved, and `None` if it’s still pending.
|
||||
|
||||
You do this by using the [`create_resource`](https://docs.rs/leptos/latest/leptos/fn.create_resource.html) function. This takes two arguments (other than the ubiquitous `cx`):
|
||||
|
||||
1. a source signal, which will generate a new `Future` whenever it changes
|
||||
2. a fetcher function, which takes the data from that signal and returns a `Future`
|
||||
|
||||
Here’s an example
|
||||
|
||||
```rust
|
||||
// our source signal: some synchronous, local state
|
||||
let (count, set_count) = create_signal(cx, 0);
|
||||
|
||||
// our resource
|
||||
let async_data = create_resource(cx,
|
||||
count,
|
||||
// every time `count` changes, this will run
|
||||
|value| async move {
|
||||
log!("loading data from API");
|
||||
load_data(value).await
|
||||
},
|
||||
);
|
||||
```
|
||||
|
||||
To create a resource that simply runs once, you can pass a non-reactive, empty source signal:
|
||||
|
||||
```rust
|
||||
let once = create_resource(cx, || (), |_| async move { load_data().await });
|
||||
```
|
||||
|
||||
To access the value you can use `.read(cx)` or `.with(cx, |data| /* */)`. These work just like `.get()` and `.with()` on a signal—`read` clones the value and returns it, `with` applies a closure to it—but with two differences
|
||||
|
||||
1. For any `Resource<_, T>`, they always return `Option<T>`, not `T`: because it’s always possible that your resource is still loading.
|
||||
2. They take a `Scope` argument. You’ll see why in the next chapter, on `<Suspense/>`.
|
||||
|
||||
So, you can show the current state of a resource in your view:
|
||||
|
||||
```rust
|
||||
let once = create_resource(cx, || (), |_| async move { load_data().await });
|
||||
view! { cx,
|
||||
<h1>"My Data"</h1>
|
||||
{move || match once.read(cx) {
|
||||
None => view! { cx, <p>"Loading..."</p> }.into_view(cx),
|
||||
Some(data) => view! { cx, <ShowData data/> }.into_view(cx)
|
||||
}}
|
||||
}
|
||||
```
|
||||
|
||||
Resources also provide a `refetch()` method that allow you to manually reload the data (for example, in response to a button click) and a `loading()` method that returns a `ReadSignal<bool>` indicating whether the resource is currently loading or not.
|
||||
|
||||
<iframe src="https://codesandbox.io/p/sandbox/10-async-resources-4z0qt3?file=%2Fsrc%2Fmain.rs&selection=%5B%7B%22endColumn%22%3A1%2C%22endLineNumber%22%3A3%2C%22startColumn%22%3A1%2C%22startLineNumber%22%3A3%7D%5D" width="100%" height="1000px"></iframe>
|
||||
72
docs/book/src/async/11_suspense.md
Normal file
72
docs/book/src/async/11_suspense.md
Normal file
@@ -0,0 +1,72 @@
|
||||
# `<Suspense/>`
|
||||
|
||||
In the previous chapter, we showed how you can create a simple loading screen to show some fallback while a resource is loading.
|
||||
|
||||
```rust
|
||||
let (count, set_count) = create_signal(cx, 0);
|
||||
let a = create_resource(cx, count, |count| async move { load_a(count).await });
|
||||
|
||||
view! { cx,
|
||||
<h1>"My Data"</h1>
|
||||
{move || match once.read(cx) {
|
||||
None => view! { cx, <p>"Loading..."</p> }.into_view(cx),
|
||||
Some(data) => view! { cx, <ShowData data/> }.into_view(cx)
|
||||
}}
|
||||
}
|
||||
```
|
||||
|
||||
But what if we have two resources, and want to wait for both of them?
|
||||
|
||||
```rust
|
||||
let (count, set_count) = create_signal(cx, 0);
|
||||
let (count2, set_count2) = create_signal(cx, 0);
|
||||
let a = create_resource(cx, count, |count| async move { load_a(count).await });
|
||||
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)
|
||||
}}
|
||||
}
|
||||
```
|
||||
|
||||
That’s not _so_ bad, but it’s kind of annoying. What if we could invert the flow of control?
|
||||
|
||||
The [`<Suspense/>`](https://docs.rs/leptos/latest/leptos/fn.Suspense.html) component lets us do exactly that. You give it a `fallback` prop and children, one or more of which usually involves reading from a resource. Reading from a resource “under” a `<Suspense/>` (i.e., in one of its children) registers that resource with the `<Suspense/>`. If it’s still waiting for resources to load, it shows the `fallback`. When they’ve all loaded, it shows the children.
|
||||
|
||||
```rust
|
||||
let (count, set_count) = create_signal(cx, 0);
|
||||
let (count2, set_count2) = create_signal(cx, 0);
|
||||
let a = create_resource(cx, count, |count| async move { load_a(count).await });
|
||||
let b = create_resource(cx, count2, |count| async move { load_b(count).await });
|
||||
|
||||
view! { cx,
|
||||
<h1>"My Data"</h1>
|
||||
<Suspense
|
||||
fallback=move || view! { cx, <p>"Loading..."</p> }
|
||||
>
|
||||
<h2>"My Data"</h2>
|
||||
<h3>"A"</h3>
|
||||
{move || {
|
||||
a.read(cx)
|
||||
.map(|a| view! { cx, <ShowA a/> })
|
||||
}}
|
||||
<h3>"B"</h3>
|
||||
{move || {
|
||||
b.read(cx)
|
||||
.map(|b| view! { cx, <ShowB b/> })
|
||||
}}
|
||||
</Suspense>
|
||||
}
|
||||
```
|
||||
|
||||
Every time one of the resources is reloading, the `"Loading..."` fallback will show again.
|
||||
|
||||
This inversion of the flow of control makes it easier to add or remove individual resources, as you don’t need to handle the matching yourself. It also unlocks some massive performance improvements during server-side rendering, which we’ll talk about during a later chapter.
|
||||
|
||||
<iframe src="https://codesandbox.io/p/sandbox/10-async-resources-4z0qt3?file=%2Fsrc%2Fmain.rs&selection=%5B%7B%22endColumn%22%3A1%2C%22endLineNumber%22%3A3%2C%22startColumn%22%3A1%2C%22startLineNumber%22%3A3%7D%5D" width="100%" height="1000px"></iframe>
|
||||
9
docs/book/src/async/12_transition.md
Normal file
9
docs/book/src/async/12_transition.md
Normal file
@@ -0,0 +1,9 @@
|
||||
# `<Transition/>`
|
||||
|
||||
You’ll notice in the `<Suspense/>` example that if you keep reloading the data, it keeps flickering back to `"Loading..."`. Sometimes this is fine. For other times, there’s [`<Transition/>`](https://docs.rs/leptos/latest/leptos/fn.Suspense.html).
|
||||
|
||||
`<Transition/>` behaves exactly the same as `<Suspense/>`, but instead of falling back every time, it only shows the fallback the first time. On all subsequent loads, it continues showing the old data until the new data are ready. This can be really handy to prevent the flickering effect, and to allow users to continue interacting with your application.
|
||||
|
||||
This example shows how you can create a simple tabbed contact list with `<Transition/>`. When you select a new tab, it continues showing the current contact until the new data laods. This can be a much better user experience than constantly falling back to a loading message.
|
||||
|
||||
<iframe src="https://codesandbox.io/p/sandbox/12-transition-sn38sd?selection=%5B%7B%22endColumn%22%3A15%2C%22endLineNumber%22%3A2%2C%22startColumn%22%3A15%2C%22startLineNumber%22%3A2%7D%5D&file=%2Fsrc%2Fmain.rs" width="100%" height="1000px"></iframe>
|
||||
9
docs/book/src/async/README.md
Normal file
9
docs/book/src/async/README.md
Normal file
@@ -0,0 +1,9 @@
|
||||
# Working with `async`
|
||||
|
||||
So far we’ve only been working with synchronous users interfaces: You provide some input,
|
||||
the app immediately process it and updates the interface. This is great, but is a tiny
|
||||
subset of what web applications do. In particular, most web apps have to deal with some kind
|
||||
of asynchronous data loading, usually loading something from an API.
|
||||
|
||||
Asynchronous data is notoriously hard to integrate with the synchronous parts of your code.
|
||||
In this chapter, we’ll see how Leptos helps smooth out that process for you.
|
||||
@@ -122,3 +122,5 @@ view! { cx,
|
||||
</WrappedChildren>
|
||||
}
|
||||
```
|
||||
|
||||
<iframe src="https://codesandbox.io/p/sandbox/9-component-children-2wrdfd?file=%2Fsrc%2Fmain.rs&selection=%5B%7B%22endColumn%22%3A12%2C%22endLineNumber%22%3A19%2C%22startColumn%22%3A12%2C%22startLineNumber%22%3A19%7D%5D" width="100%" height="1000px"></iframe>
|
||||
|
||||
7
examples/login_with_token_csr_only/Cargo.toml
Normal file
7
examples/login_with_token_csr_only/Cargo.toml
Normal file
@@ -0,0 +1,7 @@
|
||||
[workspace]
|
||||
members = ["client", "api-boundary", "server"]
|
||||
|
||||
[patch.crates-io]
|
||||
leptos = { path = "../../leptos" }
|
||||
leptos_router = { path = "../../router" }
|
||||
api-boundary = { path = "api-boundary" }
|
||||
23
examples/login_with_token_csr_only/README.md
Normal file
23
examples/login_with_token_csr_only/README.md
Normal file
@@ -0,0 +1,23 @@
|
||||
# Leptos Login Example
|
||||
|
||||
This example demonstrates a scenario of a client-side rendered application
|
||||
that uses uses an existing API that you cannot or do not want to change.
|
||||
The authentications of this example are done using an API token.
|
||||
|
||||
## Run
|
||||
|
||||
First start the example server:
|
||||
|
||||
```
|
||||
cd server/ && cargo run
|
||||
```
|
||||
|
||||
then use [`trunk`](https://trunkrs.dev) to serve the SPA:
|
||||
|
||||
```
|
||||
cd client/ && trunk serve
|
||||
```
|
||||
|
||||
finally you can visit the web application at `http://localhost:8080`
|
||||
|
||||
The `api-boundary` crate contains data structures that are used by the server and the client.
|
||||
@@ -0,0 +1,8 @@
|
||||
[package]
|
||||
name = "api-boundary"
|
||||
version = "0.0.0"
|
||||
edition = "2021"
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
22
examples/login_with_token_csr_only/api-boundary/src/lib.rs
Normal file
22
examples/login_with_token_csr_only/api-boundary/src/lib.rs
Normal file
@@ -0,0 +1,22 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub struct Credentials {
|
||||
pub email: String,
|
||||
pub password: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Serialize, Deserialize)]
|
||||
pub struct UserInfo {
|
||||
pub email: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Serialize, Deserialize)]
|
||||
pub struct ApiToken {
|
||||
pub token: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct Error {
|
||||
pub message: String,
|
||||
}
|
||||
19
examples/login_with_token_csr_only/client/Cargo.toml
Normal file
19
examples/login_with_token_csr_only/client/Cargo.toml
Normal file
@@ -0,0 +1,19 @@
|
||||
[package]
|
||||
name = "client"
|
||||
version = "0.0.0"
|
||||
edition = "2021"
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
api-boundary = "*"
|
||||
|
||||
leptos = { version = "0.2.0-alpha2", features = ["stable"] }
|
||||
leptos_router = { version = "0.2.0-alpha2", features = ["stable", "csr"] }
|
||||
|
||||
log = "0.4"
|
||||
console_error_panic_hook = "0.1"
|
||||
console_log = "0.2"
|
||||
gloo-net = "0.2"
|
||||
gloo-storage = "0.2"
|
||||
serde = "1.0"
|
||||
thiserror = "1.0"
|
||||
3
examples/login_with_token_csr_only/client/Trunk.toml
Normal file
3
examples/login_with_token_csr_only/client/Trunk.toml
Normal file
@@ -0,0 +1,3 @@
|
||||
[[proxy]]
|
||||
rewrite = "/api/"
|
||||
backend = "http://0.0.0.0:3000/"
|
||||
7
examples/login_with_token_csr_only/client/index.html
Normal file
7
examples/login_with_token_csr_only/client/index.html
Normal file
@@ -0,0 +1,7 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<link data-trunk rel="rust" data-wasm-opt="z" data-weak-refs/>
|
||||
</head>
|
||||
<body></body>
|
||||
</html>
|
||||
94
examples/login_with_token_csr_only/client/src/api.rs
Normal file
94
examples/login_with_token_csr_only/client/src/api.rs
Normal file
@@ -0,0 +1,94 @@
|
||||
use gloo_net::http::{Request, Response};
|
||||
use serde::de::DeserializeOwned;
|
||||
use thiserror::Error;
|
||||
|
||||
use api_boundary::*;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct UnauthorizedApi {
|
||||
url: &'static str,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct AuthorizedApi {
|
||||
url: &'static str,
|
||||
token: ApiToken,
|
||||
}
|
||||
|
||||
impl UnauthorizedApi {
|
||||
pub const fn new(url: &'static str) -> Self {
|
||||
Self { url }
|
||||
}
|
||||
pub async fn register(&self, credentials: &Credentials) -> Result<()> {
|
||||
let url = format!("{}/users", self.url);
|
||||
let response = Request::post(&url).json(credentials)?.send().await?;
|
||||
into_json(response).await
|
||||
}
|
||||
pub async fn login(
|
||||
&self,
|
||||
credentials: &Credentials,
|
||||
) -> Result<AuthorizedApi> {
|
||||
let url = format!("{}/login", self.url);
|
||||
let response = Request::post(&url).json(credentials)?.send().await?;
|
||||
let token = into_json(response).await?;
|
||||
Ok(AuthorizedApi::new(self.url, token))
|
||||
}
|
||||
}
|
||||
|
||||
impl AuthorizedApi {
|
||||
pub const fn new(url: &'static str, token: ApiToken) -> Self {
|
||||
Self { url, token }
|
||||
}
|
||||
fn auth_header_value(&self) -> String {
|
||||
format!("Bearer {}", self.token.token)
|
||||
}
|
||||
async fn send<T>(&self, req: Request) -> Result<T>
|
||||
where
|
||||
T: DeserializeOwned,
|
||||
{
|
||||
let response = req
|
||||
.header("Authorization", &self.auth_header_value())
|
||||
.send()
|
||||
.await?;
|
||||
into_json(response).await
|
||||
}
|
||||
pub async fn logout(&self) -> Result<()> {
|
||||
let url = format!("{}/logout", self.url);
|
||||
self.send(Request::post(&url)).await
|
||||
}
|
||||
pub async fn user_info(&self) -> Result<UserInfo> {
|
||||
let url = format!("{}/users", self.url);
|
||||
self.send(Request::get(&url)).await
|
||||
}
|
||||
pub fn token(&self) -> &ApiToken {
|
||||
&self.token
|
||||
}
|
||||
}
|
||||
|
||||
type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum Error {
|
||||
#[error(transparent)]
|
||||
Fetch(#[from] gloo_net::Error),
|
||||
#[error("{0:?}")]
|
||||
Api(api_boundary::Error),
|
||||
}
|
||||
|
||||
impl From<api_boundary::Error> for Error {
|
||||
fn from(e: api_boundary::Error) -> Self {
|
||||
Self::Api(e)
|
||||
}
|
||||
}
|
||||
|
||||
async fn into_json<T>(response: Response) -> Result<T>
|
||||
where
|
||||
T: DeserializeOwned,
|
||||
{
|
||||
// ensure we've got 2xx status
|
||||
if response.ok() {
|
||||
Ok(response.json().await?)
|
||||
} else {
|
||||
Err(response.json::<api_boundary::Error>().await?.into())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
use leptos::{ev, *};
|
||||
|
||||
#[component]
|
||||
pub fn CredentialsForm(
|
||||
cx: Scope,
|
||||
title: &'static str,
|
||||
action_label: &'static str,
|
||||
action: Action<(String, String), ()>,
|
||||
error: Signal<Option<String>>,
|
||||
disabled: Signal<bool>,
|
||||
) -> impl IntoView {
|
||||
let (password, set_password) = create_signal(cx, String::new());
|
||||
let (email, set_email) = create_signal(cx, String::new());
|
||||
|
||||
let dispatch_action =
|
||||
move || action.dispatch((email.get(), password.get()));
|
||||
|
||||
let button_is_disabled = Signal::derive(cx, move || {
|
||||
disabled.get() || password.get().is_empty() || email.get().is_empty()
|
||||
});
|
||||
|
||||
view! { cx,
|
||||
<form on:submit=|ev|ev.prevent_default()>
|
||||
<p>{ title }</p>
|
||||
{move || error.get().map(|err| view!{ cx,
|
||||
<p style ="color:red;" >{ err }</p>
|
||||
})}
|
||||
<input
|
||||
type = "email"
|
||||
required
|
||||
placeholder = "Email address"
|
||||
prop:disabled = move || disabled.get()
|
||||
on:keyup = move |ev: ev::KeyboardEvent| {
|
||||
let val = event_target_value(&ev);
|
||||
set_email.update(|v|*v = val);
|
||||
}
|
||||
// The `change` event fires when the browser fills the form automatically,
|
||||
on:change = move |ev| {
|
||||
let val = event_target_value(&ev);
|
||||
set_email.update(|v|*v = val);
|
||||
}
|
||||
/>
|
||||
<input
|
||||
type = "password"
|
||||
required
|
||||
placeholder = "Password"
|
||||
prop:disabled = move || disabled.get()
|
||||
on:keyup = move |ev: ev::KeyboardEvent| {
|
||||
match &*ev.key() {
|
||||
"Enter" => {
|
||||
dispatch_action();
|
||||
}
|
||||
_=> {
|
||||
let val = event_target_value(&ev);
|
||||
set_password.update(|p|*p = val);
|
||||
}
|
||||
}
|
||||
}
|
||||
// The `change` event fires when the browser fills the form automatically,
|
||||
on:change = move |ev| {
|
||||
let val = event_target_value(&ev);
|
||||
set_password.update(|p|*p = val);
|
||||
}
|
||||
/>
|
||||
<button
|
||||
prop:disabled = move || button_is_disabled.get()
|
||||
on:click = move |_| dispatch_action()
|
||||
>
|
||||
{ action_label }
|
||||
</button>
|
||||
</form>
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
pub mod credentials;
|
||||
pub mod navbar;
|
||||
|
||||
pub use self::{credentials::*, navbar::*};
|
||||
@@ -0,0 +1,32 @@
|
||||
use leptos::*;
|
||||
use leptos_router::*;
|
||||
|
||||
use crate::Page;
|
||||
|
||||
#[component]
|
||||
pub fn NavBar<F>(
|
||||
cx: Scope,
|
||||
logged_in: Signal<bool>,
|
||||
on_logout: F,
|
||||
) -> impl IntoView
|
||||
where
|
||||
F: Fn() + 'static + Clone,
|
||||
{
|
||||
view! { cx,
|
||||
<nav>
|
||||
<Show
|
||||
when = move || logged_in.get()
|
||||
fallback = |cx| view! { cx,
|
||||
<A href=Page::Login.path() >"Login"</A>
|
||||
" | "
|
||||
<A href=Page::Register.path() >"Register"</A>
|
||||
}
|
||||
>
|
||||
<a href="#" on:click={
|
||||
let on_logout = on_logout.clone();
|
||||
move |_| on_logout()
|
||||
}>"Logout"</a>
|
||||
</Show>
|
||||
</nav>
|
||||
}
|
||||
}
|
||||
130
examples/login_with_token_csr_only/client/src/lib.rs
Normal file
130
examples/login_with_token_csr_only/client/src/lib.rs
Normal file
@@ -0,0 +1,130 @@
|
||||
use gloo_storage::{LocalStorage, Storage};
|
||||
use leptos::*;
|
||||
use leptos_router::*;
|
||||
|
||||
use api_boundary::*;
|
||||
|
||||
mod api;
|
||||
mod components;
|
||||
mod pages;
|
||||
|
||||
use self::{components::*, pages::*};
|
||||
|
||||
const DEFAULT_API_URL: &str = "/api";
|
||||
const API_TOKEN_STORAGE_KEY: &str = "api-token";
|
||||
|
||||
#[component]
|
||||
pub fn App(cx: Scope) -> impl IntoView {
|
||||
// -- signals -- //
|
||||
|
||||
let authorized_api = create_rw_signal(cx, None::<api::AuthorizedApi>);
|
||||
let user_info = create_rw_signal(cx, None::<UserInfo>);
|
||||
let logged_in = Signal::derive(cx, move || authorized_api.get().is_some());
|
||||
|
||||
// -- actions -- //
|
||||
|
||||
let fetch_user_info = create_action(cx, move |_| async move {
|
||||
match authorized_api.get() {
|
||||
Some(api) => match api.user_info().await {
|
||||
Ok(info) => {
|
||||
user_info.update(|i| *i = Some(info));
|
||||
}
|
||||
Err(err) => {
|
||||
log::error!("Unable to fetch user info: {err}")
|
||||
}
|
||||
},
|
||||
None => {
|
||||
log::error!("Unable to fetch user info: not logged in")
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let logout = create_action(cx, move |_| async move {
|
||||
match authorized_api.get() {
|
||||
Some(api) => match api.logout().await {
|
||||
Ok(_) => {
|
||||
authorized_api.update(|a| *a = None);
|
||||
user_info.update(|i| *i = None);
|
||||
}
|
||||
Err(err) => {
|
||||
log::error!("Unable to logout: {err}")
|
||||
}
|
||||
},
|
||||
None => {
|
||||
log::error!("Unable to logout user: not logged in")
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// -- callbacks -- //
|
||||
|
||||
let on_logout = move || {
|
||||
logout.dispatch(());
|
||||
};
|
||||
|
||||
// -- init API -- //
|
||||
|
||||
let unauthorized_api = api::UnauthorizedApi::new(DEFAULT_API_URL);
|
||||
if let Ok(token) = LocalStorage::get(API_TOKEN_STORAGE_KEY) {
|
||||
let api = api::AuthorizedApi::new(DEFAULT_API_URL, token);
|
||||
authorized_api.update(|a| *a = Some(api));
|
||||
fetch_user_info.dispatch(());
|
||||
}
|
||||
|
||||
log::debug!("User is logged in: {}", logged_in.get());
|
||||
|
||||
// -- effects -- //
|
||||
|
||||
create_effect(cx, move |_| {
|
||||
log::debug!("API authorization state changed");
|
||||
match authorized_api.get() {
|
||||
Some(api) => {
|
||||
log::debug!(
|
||||
"API is now authorized: save token in LocalStorage"
|
||||
);
|
||||
LocalStorage::set(API_TOKEN_STORAGE_KEY, api.token())
|
||||
.expect("LocalStorage::set");
|
||||
}
|
||||
None => {
|
||||
log::debug!("API is no longer authorized: delete token from LocalStorage");
|
||||
LocalStorage::delete(API_TOKEN_STORAGE_KEY);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
view! { cx,
|
||||
<Router>
|
||||
<NavBar logged_in on_logout />
|
||||
<main>
|
||||
<Routes>
|
||||
<Route
|
||||
path=Page::Home.path()
|
||||
view=move |cx| view! { cx,
|
||||
<Home user_info = user_info.into() />
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path=Page::Login.path()
|
||||
view=move |cx| view! { cx,
|
||||
<Login
|
||||
api = unauthorized_api
|
||||
on_success = move |api| {
|
||||
log::info!("Successfully logged in");
|
||||
authorized_api.update(|v| *v = Some(api));
|
||||
let navigate = use_navigate(cx);
|
||||
navigate(Page::Home.path(), Default::default()).expect("Home route");
|
||||
fetch_user_info.dispatch(());
|
||||
} />
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path=Page::Register.path()
|
||||
view=move |cx| view! { cx,
|
||||
<Register api = unauthorized_api />
|
||||
}
|
||||
/>
|
||||
</Routes>
|
||||
</main>
|
||||
</Router>
|
||||
}
|
||||
}
|
||||
9
examples/login_with_token_csr_only/client/src/main.rs
Normal file
9
examples/login_with_token_csr_only/client/src/main.rs
Normal file
@@ -0,0 +1,9 @@
|
||||
use leptos::*;
|
||||
|
||||
use client::*;
|
||||
|
||||
pub fn main() {
|
||||
_ = console_log::init_with_level(log::Level::Debug);
|
||||
console_error_panic_hook::set_once();
|
||||
mount_to_body(|cx| view! { cx, <App /> })
|
||||
}
|
||||
20
examples/login_with_token_csr_only/client/src/pages/home.rs
Normal file
20
examples/login_with_token_csr_only/client/src/pages/home.rs
Normal file
@@ -0,0 +1,20 @@
|
||||
use crate::Page;
|
||||
use api_boundary::UserInfo;
|
||||
use leptos::*;
|
||||
use leptos_router::*;
|
||||
|
||||
#[component]
|
||||
pub fn Home(cx: Scope, user_info: Signal<Option<UserInfo>>) -> impl IntoView {
|
||||
view! { cx,
|
||||
<h2>"Leptos Login example"</h2>
|
||||
{move || match user_info.get() {
|
||||
Some(info) => view!{ cx,
|
||||
<p>"You are logged in with "{ info.email }"."</p>
|
||||
}.into_view(cx),
|
||||
None => view!{ cx,
|
||||
<p>"You are not logged in."</p>
|
||||
<A href=Page::Login.path() >"Login now."</A>
|
||||
}.into_view(cx)
|
||||
}}
|
||||
}
|
||||
}
|
||||
66
examples/login_with_token_csr_only/client/src/pages/login.rs
Normal file
66
examples/login_with_token_csr_only/client/src/pages/login.rs
Normal file
@@ -0,0 +1,66 @@
|
||||
use leptos::*;
|
||||
use leptos_router::*;
|
||||
|
||||
use api_boundary::*;
|
||||
|
||||
use crate::{
|
||||
api::{self, AuthorizedApi, UnauthorizedApi},
|
||||
components::credentials::*,
|
||||
Page,
|
||||
};
|
||||
|
||||
#[component]
|
||||
pub fn Login<F>(cx: Scope, api: UnauthorizedApi, on_success: F) -> impl IntoView
|
||||
where
|
||||
F: Fn(AuthorizedApi) + 'static + Clone,
|
||||
{
|
||||
let (login_error, set_login_error) = create_signal(cx, None::<String>);
|
||||
let (wait_for_response, set_wait_for_response) = create_signal(cx, false);
|
||||
|
||||
let login_action =
|
||||
create_action(cx, move |(email, password): &(String, String)| {
|
||||
log::debug!("Try to login with {email}");
|
||||
let email = email.to_string();
|
||||
let password = password.to_string();
|
||||
let credentials = Credentials { email, password };
|
||||
let on_success = on_success.clone();
|
||||
async move {
|
||||
set_wait_for_response.update(|w| *w = true);
|
||||
let result = api.login(&credentials).await;
|
||||
set_wait_for_response.update(|w| *w = false);
|
||||
match result {
|
||||
Ok(res) => {
|
||||
set_login_error.update(|e| *e = None);
|
||||
on_success(res);
|
||||
}
|
||||
Err(err) => {
|
||||
let msg = match err {
|
||||
api::Error::Fetch(js_err) => {
|
||||
format!("{js_err:?}")
|
||||
}
|
||||
api::Error::Api(err) => err.message,
|
||||
};
|
||||
error!(
|
||||
"Unable to login with {}: {msg}",
|
||||
credentials.email
|
||||
);
|
||||
set_login_error.update(|e| *e = Some(msg));
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let disabled = Signal::derive(cx, move || wait_for_response.get());
|
||||
|
||||
view! { cx,
|
||||
<CredentialsForm
|
||||
title = "Please login to your account"
|
||||
action_label = "Login"
|
||||
action = login_action
|
||||
error = login_error.into()
|
||||
disabled
|
||||
/>
|
||||
<p>"Don't have an account?"</p>
|
||||
<A href=Page::Register.path()>"Register"</A>
|
||||
}
|
||||
}
|
||||
23
examples/login_with_token_csr_only/client/src/pages/mod.rs
Normal file
23
examples/login_with_token_csr_only/client/src/pages/mod.rs
Normal file
@@ -0,0 +1,23 @@
|
||||
pub mod home;
|
||||
pub mod login;
|
||||
pub mod register;
|
||||
|
||||
pub use self::{home::*, login::*, register::*};
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default)]
|
||||
pub enum Page {
|
||||
#[default]
|
||||
Home,
|
||||
Login,
|
||||
Register,
|
||||
}
|
||||
|
||||
impl Page {
|
||||
pub fn path(&self) -> &'static str {
|
||||
match self {
|
||||
Self::Home => "/",
|
||||
Self::Login => "/login",
|
||||
Self::Register => "/register",
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
use leptos::*;
|
||||
use leptos_router::*;
|
||||
|
||||
use api_boundary::*;
|
||||
|
||||
use crate::{
|
||||
api::{self, UnauthorizedApi},
|
||||
components::credentials::*,
|
||||
Page,
|
||||
};
|
||||
|
||||
#[component]
|
||||
pub fn Register(cx: Scope, api: UnauthorizedApi) -> impl IntoView {
|
||||
let (register_response, set_register_response) =
|
||||
create_signal(cx, None::<()>);
|
||||
let (register_error, set_register_error) =
|
||||
create_signal(cx, None::<String>);
|
||||
let (wait_for_response, set_wait_for_response) = create_signal(cx, false);
|
||||
|
||||
let register_action =
|
||||
create_action(cx, move |(email, password): &(String, String)| {
|
||||
let email = email.to_string();
|
||||
let password = password.to_string();
|
||||
let credentials = Credentials { email, password };
|
||||
log!("Try to register new account for {}", credentials.email);
|
||||
async move {
|
||||
set_wait_for_response.update(|w| *w = true);
|
||||
let result = api.register(&credentials).await;
|
||||
set_wait_for_response.update(|w| *w = false);
|
||||
match result {
|
||||
Ok(res) => {
|
||||
set_register_response.update(|v| *v = Some(res));
|
||||
set_register_error.update(|e| *e = None);
|
||||
}
|
||||
Err(err) => {
|
||||
let msg = match err {
|
||||
api::Error::Fetch(js_err) => {
|
||||
format!("{js_err:?}")
|
||||
}
|
||||
api::Error::Api(err) => err.message,
|
||||
};
|
||||
log::warn!(
|
||||
"Unable to register new account for {}: {msg}",
|
||||
credentials.email
|
||||
);
|
||||
set_register_error.update(|e| *e = Some(msg));
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let disabled = Signal::derive(cx, move || wait_for_response.get());
|
||||
|
||||
view! { cx,
|
||||
<Show
|
||||
when = move || register_response.get().is_some()
|
||||
fallback = move |_| view!{ cx,
|
||||
<CredentialsForm
|
||||
title = "Please enter the desired credentials"
|
||||
action_label = "Register"
|
||||
action = register_action
|
||||
error = register_error.into()
|
||||
disabled
|
||||
/>
|
||||
<p>"Your already have an account?"</p>
|
||||
<A href=Page::Login.path()>"Login"</A>
|
||||
}
|
||||
>
|
||||
<p>"You have successfully registered."</p>
|
||||
<p>
|
||||
"You can now "
|
||||
<A href=Page::Login.path()>"login"</A>
|
||||
" with your new account."
|
||||
</p>
|
||||
</Show>
|
||||
}
|
||||
}
|
||||
18
examples/login_with_token_csr_only/server/Cargo.toml
Normal file
18
examples/login_with_token_csr_only/server/Cargo.toml
Normal file
@@ -0,0 +1,18 @@
|
||||
[package]
|
||||
name = "server"
|
||||
version = "0.0.0"
|
||||
edition = "2021"
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1.0"
|
||||
api-boundary = "*"
|
||||
axum = { version = "0.6", features = ["headers"] }
|
||||
env_logger = "0.10"
|
||||
log = "0.4"
|
||||
mailparse = "0.14"
|
||||
pwhash = "1.0"
|
||||
thiserror = "1.0"
|
||||
tokio = { version = "1.25", features = ["macros", "rt-multi-thread"] }
|
||||
tower-http = { version = "0.3", features = ["cors"] }
|
||||
uuid = { version = "1.3", features = ["v4"] }
|
||||
114
examples/login_with_token_csr_only/server/src/adapters.rs
Normal file
114
examples/login_with_token_csr_only/server/src/adapters.rs
Normal file
@@ -0,0 +1,114 @@
|
||||
use crate::{application::*, Error};
|
||||
use api_boundary as json;
|
||||
use axum::{
|
||||
http::StatusCode,
|
||||
response::Json,
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
use thiserror::Error;
|
||||
|
||||
impl From<InvalidEmailAddress> for json::Error {
|
||||
fn from(_: InvalidEmailAddress) -> Self {
|
||||
Self {
|
||||
message: "Invalid email address".to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<InvalidPassword> for json::Error {
|
||||
fn from(err: InvalidPassword) -> Self {
|
||||
let InvalidPassword::TooShort(min_len) = err;
|
||||
Self {
|
||||
message: format!("Invalid password (min. length = {min_len})"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<CreateUserError> for json::Error {
|
||||
fn from(err: CreateUserError) -> Self {
|
||||
let message = match err {
|
||||
CreateUserError::UserExists => "User already exits".to_string(),
|
||||
};
|
||||
Self { message }
|
||||
}
|
||||
}
|
||||
|
||||
impl From<LoginError> for json::Error {
|
||||
fn from(err: LoginError) -> Self {
|
||||
let message = match err {
|
||||
LoginError::InvalidEmailOrPassword => {
|
||||
"Invalid email or password".to_string()
|
||||
}
|
||||
};
|
||||
Self { message }
|
||||
}
|
||||
}
|
||||
|
||||
impl From<LogoutError> for json::Error {
|
||||
fn from(err: LogoutError) -> Self {
|
||||
let message = match err {
|
||||
LogoutError::NotLoggedIn => "No user is logged in".to_string(),
|
||||
};
|
||||
Self { message }
|
||||
}
|
||||
}
|
||||
|
||||
impl From<AuthError> for json::Error {
|
||||
fn from(err: AuthError) -> Self {
|
||||
let message = match err {
|
||||
AuthError::NotAuthorized => "Not authorized".to_string(),
|
||||
};
|
||||
Self { message }
|
||||
}
|
||||
}
|
||||
|
||||
impl From<CredentialParsingError> for json::Error {
|
||||
fn from(err: CredentialParsingError) -> Self {
|
||||
match err {
|
||||
CredentialParsingError::EmailAddress(err) => err.into(),
|
||||
CredentialParsingError::Password(err) => err.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum CredentialParsingError {
|
||||
#[error(transparent)]
|
||||
EmailAddress(#[from] InvalidEmailAddress),
|
||||
#[error(transparent)]
|
||||
Password(#[from] InvalidPassword),
|
||||
}
|
||||
|
||||
impl TryFrom<json::Credentials> for Credentials {
|
||||
type Error = CredentialParsingError;
|
||||
fn try_from(
|
||||
json::Credentials { email, password }: json::Credentials,
|
||||
) -> Result<Self, Self::Error> {
|
||||
let email: EmailAddress = email.parse()?;
|
||||
let password = Password::try_from(password)?;
|
||||
Ok(Self { email, password })
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoResponse for Error {
|
||||
fn into_response(self) -> Response {
|
||||
let (code, value) = match self {
|
||||
Self::Logout(err) => {
|
||||
(StatusCode::BAD_REQUEST, json::Error::from(err))
|
||||
}
|
||||
Self::Login(err) => {
|
||||
(StatusCode::BAD_REQUEST, json::Error::from(err))
|
||||
}
|
||||
Self::Credentials(err) => {
|
||||
(StatusCode::BAD_REQUEST, json::Error::from(err))
|
||||
}
|
||||
Self::CreateUser(err) => {
|
||||
(StatusCode::BAD_REQUEST, json::Error::from(err))
|
||||
}
|
||||
Self::Auth(err) => {
|
||||
(StatusCode::UNAUTHORIZED, json::Error::from(err))
|
||||
}
|
||||
};
|
||||
(code, Json(value)).into_response()
|
||||
}
|
||||
}
|
||||
159
examples/login_with_token_csr_only/server/src/application.rs
Normal file
159
examples/login_with_token_csr_only/server/src/application.rs
Normal file
@@ -0,0 +1,159 @@
|
||||
use mailparse::addrparse;
|
||||
use pwhash::bcrypt;
|
||||
use std::{collections::HashMap, str::FromStr, sync::RwLock};
|
||||
use thiserror::Error;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct AppState {
|
||||
users: RwLock<HashMap<EmailAddress, Password>>,
|
||||
tokens: RwLock<HashMap<Uuid, EmailAddress>>,
|
||||
}
|
||||
|
||||
impl AppState {
|
||||
pub fn create_user(
|
||||
&self,
|
||||
credentials: Credentials,
|
||||
) -> Result<(), CreateUserError> {
|
||||
let Credentials { email, password } = credentials;
|
||||
let user_exists = self.users.read().unwrap().get(&email).is_some();
|
||||
if user_exists {
|
||||
return Err(CreateUserError::UserExists);
|
||||
}
|
||||
self.users.write().unwrap().insert(email, password);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn login(
|
||||
&self,
|
||||
email: EmailAddress,
|
||||
password: &str,
|
||||
) -> Result<Uuid, LoginError> {
|
||||
let valid_credentials = self
|
||||
.users
|
||||
.read()
|
||||
.unwrap()
|
||||
.get(&email)
|
||||
.map(|hashed_password| hashed_password.verify(password))
|
||||
.unwrap_or(false);
|
||||
if !valid_credentials {
|
||||
Err(LoginError::InvalidEmailOrPassword)
|
||||
} else {
|
||||
let token = Uuid::new_v4();
|
||||
self.tokens.write().unwrap().insert(token, email);
|
||||
Ok(token)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn logout(&self, token: &str) -> Result<(), LogoutError> {
|
||||
let token = token
|
||||
.parse::<Uuid>()
|
||||
.map_err(|_| LogoutError::NotLoggedIn)?;
|
||||
self.tokens.write().unwrap().remove(&token);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn authorize_user(
|
||||
&self,
|
||||
token: &str,
|
||||
) -> Result<CurrentUser, AuthError> {
|
||||
token
|
||||
.parse::<Uuid>()
|
||||
.map_err(|_| AuthError::NotAuthorized)
|
||||
.and_then(|token| {
|
||||
self.tokens
|
||||
.read()
|
||||
.unwrap()
|
||||
.get(&token)
|
||||
.cloned()
|
||||
.map(|email| CurrentUser { email, token })
|
||||
.ok_or(AuthError::NotAuthorized)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum CreateUserError {
|
||||
#[error("The user already exists")]
|
||||
UserExists,
|
||||
}
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum LoginError {
|
||||
#[error("Invalid email or password")]
|
||||
InvalidEmailOrPassword,
|
||||
}
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum LogoutError {
|
||||
#[error("You are not logged in")]
|
||||
NotLoggedIn,
|
||||
}
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum AuthError {
|
||||
#[error("You are not authorized")]
|
||||
NotAuthorized,
|
||||
}
|
||||
|
||||
pub struct Credentials {
|
||||
pub email: EmailAddress,
|
||||
pub password: Password,
|
||||
}
|
||||
|
||||
#[derive(Clone, Eq, PartialEq, Hash)]
|
||||
pub struct EmailAddress(String);
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
#[error("The given email address is invalid")]
|
||||
pub struct InvalidEmailAddress;
|
||||
|
||||
impl FromStr for EmailAddress {
|
||||
type Err = InvalidEmailAddress;
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
addrparse(s)
|
||||
.ok()
|
||||
.and_then(|parsed| parsed.extract_single_info())
|
||||
.map(|single_info| Self(single_info.addr))
|
||||
.ok_or(InvalidEmailAddress)
|
||||
}
|
||||
}
|
||||
|
||||
impl EmailAddress {
|
||||
pub fn into_string(self) -> String {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct CurrentUser {
|
||||
pub email: EmailAddress,
|
||||
pub token: Uuid,
|
||||
}
|
||||
|
||||
const MIN_PASSWORD_LEN: usize = 3;
|
||||
|
||||
pub struct Password(String);
|
||||
|
||||
impl Password {
|
||||
pub fn verify(&self, password: &str) -> bool {
|
||||
bcrypt::verify(password, &self.0)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum InvalidPassword {
|
||||
#[error("Password is too short (min. length is {0})")]
|
||||
TooShort(usize),
|
||||
}
|
||||
|
||||
impl TryFrom<String> for Password {
|
||||
type Error = InvalidPassword;
|
||||
fn try_from(p: String) -> Result<Self, Self::Error> {
|
||||
if p.len() < MIN_PASSWORD_LEN {
|
||||
return Err(InvalidPassword::TooShort(MIN_PASSWORD_LEN));
|
||||
}
|
||||
let hashed = bcrypt::hash(&p).unwrap();
|
||||
Ok(Self(hashed))
|
||||
}
|
||||
}
|
||||
113
examples/login_with_token_csr_only/server/src/main.rs
Normal file
113
examples/login_with_token_csr_only/server/src/main.rs
Normal file
@@ -0,0 +1,113 @@
|
||||
use std::{env, sync::Arc};
|
||||
|
||||
use axum::{
|
||||
extract::{State, TypedHeader},
|
||||
headers::{authorization::Bearer, Authorization},
|
||||
http::Method,
|
||||
response::Json,
|
||||
routing::{get, post},
|
||||
Router,
|
||||
};
|
||||
use tower_http::cors::{Any, CorsLayer};
|
||||
|
||||
use api_boundary as json;
|
||||
|
||||
mod adapters;
|
||||
mod application;
|
||||
|
||||
use self::application::*;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
if let Err(err) = env::var("RUST_LOG") {
|
||||
match err {
|
||||
env::VarError::NotPresent => {
|
||||
env::set_var("RUST_LOG", "debug");
|
||||
}
|
||||
env::VarError::NotUnicode(_) => {
|
||||
return Err(anyhow::anyhow!("The value of 'RUST_LOG' does not contain valid unicode data."));
|
||||
}
|
||||
}
|
||||
}
|
||||
env_logger::init();
|
||||
|
||||
let shared_state = Arc::new(AppState::default());
|
||||
|
||||
let cors_layer = CorsLayer::new()
|
||||
.allow_methods([Method::GET, Method::POST])
|
||||
.allow_origin(Any);
|
||||
|
||||
let app = Router::new()
|
||||
.route("/login", post(login))
|
||||
.route("/logout", post(logout))
|
||||
.route("/users", post(create_user))
|
||||
.route("/users", get(get_user_info))
|
||||
.route_layer(cors_layer)
|
||||
.with_state(shared_state);
|
||||
|
||||
let addr = "0.0.0.0:3000".parse().unwrap();
|
||||
log::info!("Listen on {addr}");
|
||||
axum::Server::bind(&addr)
|
||||
.serve(app.into_make_service())
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
type Result<T> = std::result::Result<Json<T>, Error>;
|
||||
|
||||
/// API error
|
||||
#[derive(thiserror::Error, Debug)]
|
||||
#[non_exhaustive]
|
||||
enum Error {
|
||||
#[error(transparent)]
|
||||
CreateUser(#[from] CreateUserError),
|
||||
#[error(transparent)]
|
||||
Login(#[from] LoginError),
|
||||
#[error(transparent)]
|
||||
Logout(#[from] LogoutError),
|
||||
#[error(transparent)]
|
||||
Auth(#[from] AuthError),
|
||||
#[error(transparent)]
|
||||
Credentials(#[from] adapters::CredentialParsingError),
|
||||
}
|
||||
|
||||
async fn create_user(
|
||||
State(state): State<Arc<AppState>>,
|
||||
Json(credentials): Json<json::Credentials>,
|
||||
) -> Result<()> {
|
||||
let credentials = Credentials::try_from(credentials)?;
|
||||
state.create_user(credentials)?;
|
||||
Ok(Json(()))
|
||||
}
|
||||
|
||||
async fn login(
|
||||
State(state): State<Arc<AppState>>,
|
||||
Json(credentials): Json<json::Credentials>,
|
||||
) -> Result<json::ApiToken> {
|
||||
let json::Credentials { email, password } = credentials;
|
||||
log::debug!("{email} tries to login");
|
||||
let email = email.parse().map_err(|_|
|
||||
// Here we don't want to leak detailed info.
|
||||
LoginError::InvalidEmailOrPassword)?;
|
||||
let token = state.login(email, &password).map(|s| s.to_string())?;
|
||||
Ok(Json(json::ApiToken { token }))
|
||||
}
|
||||
|
||||
async fn logout(
|
||||
State(state): State<Arc<AppState>>,
|
||||
TypedHeader(auth): TypedHeader<Authorization<Bearer>>,
|
||||
) -> Result<()> {
|
||||
state.logout(auth.token())?;
|
||||
Ok(Json(()))
|
||||
}
|
||||
|
||||
async fn get_user_info(
|
||||
State(state): State<Arc<AppState>>,
|
||||
TypedHeader(auth): TypedHeader<Authorization<Bearer>>,
|
||||
) -> Result<json::UserInfo> {
|
||||
let user = state.authorize_user(auth.token())?;
|
||||
let CurrentUser { email, .. } = user;
|
||||
Ok(Json(json::UserInfo {
|
||||
email: email.into_string(),
|
||||
}))
|
||||
}
|
||||
13
examples/ssr_modes_axum/.gitignore
vendored
Normal file
13
examples/ssr_modes_axum/.gitignore
vendored
Normal file
@@ -0,0 +1,13 @@
|
||||
# Generated by Cargo
|
||||
# will have compiled files and executables
|
||||
/target/
|
||||
pkg
|
||||
|
||||
# These are backup files generated by rustfmt
|
||||
**/*.rs.bk
|
||||
|
||||
# node e2e test tools and outputs
|
||||
node_modules/
|
||||
test-results/
|
||||
end2end/playwright-report/
|
||||
playwright/.cache/
|
||||
91
examples/ssr_modes_axum/Cargo.toml
Normal file
91
examples/ssr_modes_axum/Cargo.toml
Normal file
@@ -0,0 +1,91 @@
|
||||
[package]
|
||||
name = "ssr_modes_axum"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib", "rlib"]
|
||||
|
||||
[dependencies]
|
||||
console_error_panic_hook = "0.1"
|
||||
console_log = "0.2"
|
||||
cfg-if = "1"
|
||||
lazy_static = "1"
|
||||
leptos = { path = "../../leptos", default-features = false, features = [
|
||||
"serde",
|
||||
] }
|
||||
leptos_meta = { path = "../../meta", default-features = false }
|
||||
leptos_axum = { path = "../../integrations/axum", default-features = false, optional = true }
|
||||
leptos_router = { path = "../../router", default-features = false }
|
||||
log = "0.4"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
simple_logger = "4"
|
||||
thiserror = "1"
|
||||
axum = { version = "0.6.1", optional = true }
|
||||
tower = { version = "0.4.13", optional = true }
|
||||
tower-http = { version = "0.3.4", features = ["fs"], optional = true }
|
||||
tokio = { version = "1", features = ["time"], optional = true}
|
||||
wasm-bindgen = "0.2"
|
||||
|
||||
[features]
|
||||
hydrate = ["leptos/hydrate", "leptos_meta/hydrate", "leptos_router/hydrate"]
|
||||
ssr = [
|
||||
"dep:axum",
|
||||
"dep:tower",
|
||||
"dep:tower-http",
|
||||
"dep:tokio",
|
||||
"leptos/ssr",
|
||||
"leptos_meta/ssr",
|
||||
"leptos_router/ssr",
|
||||
"dep:leptos_axum",
|
||||
]
|
||||
|
||||
[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"
|
||||
# The site root folder is where cargo-leptos generate all output. WARNING: all content of this folder will be erased on a rebuild. Use it in your server setup.
|
||||
site-root = "target/site"
|
||||
# The site-root relative folder where all compiled output (JS, WASM and CSS) is written
|
||||
# Defaults to pkg
|
||||
site-pkg-dir = "pkg"
|
||||
# [Optional] The source CSS file. If it ends with .sass or .scss then it will be compiled by dart-sass into CSS. The CSS is optimized by Lightning CSS before being written to <site-root>/<site-pkg>/app.css
|
||||
style-file = "style/main.scss"
|
||||
# Assets source dir. All files found here will be copied and synchronized to site-root.
|
||||
# The assets-dir cannot have a sub directory with the same name/path as site-pkg-dir.
|
||||
#
|
||||
# Optional. Env: LEPTOS_ASSETS_DIR.
|
||||
assets-dir = "assets"
|
||||
# The IP and port (ex: 127.0.0.1:3000) where the server serves the content. Use it in your server setup.
|
||||
site-addr = "127.0.0.1:3000"
|
||||
# The port to use for automatic reload monitoring
|
||||
reload-port = 3001
|
||||
# [Optional] Command to use when running end2end tests. It will run in the end2end dir.
|
||||
# [Windows] for non-WSL use "npx.cmd playwright test"
|
||||
# This binary name can be checked in Powershell with Get-Command npx
|
||||
end2end-cmd = "npx playwright test"
|
||||
end2end-dir = "end2end"
|
||||
# The browserlist query used for optimizing the CSS.
|
||||
browserquery = "defaults"
|
||||
# Set by cargo-leptos watch when building with that tool. Controls whether autoreload JS will be included in the head
|
||||
watch = false
|
||||
# The environment Leptos will run in, usually either "DEV" or "PROD"
|
||||
env = "DEV"
|
||||
# The features to use when compiling the bin target
|
||||
#
|
||||
# Optional. Can be over-ridden with the command line parameter --bin-features
|
||||
bin-features = ["ssr"]
|
||||
|
||||
# If the --no-default-features flag should be used when compiling the bin target
|
||||
#
|
||||
# Optional. Defaults to false.
|
||||
bin-default-features = false
|
||||
|
||||
# The features to use when compiling the lib target
|
||||
#
|
||||
# Optional. Can be over-ridden with the command line parameter --lib-features
|
||||
lib-features = ["hydrate"]
|
||||
|
||||
# If the --no-default-features flag should be used when compiling the lib target
|
||||
#
|
||||
# Optional. Defaults to false.
|
||||
lib-default-features = false
|
||||
21
examples/ssr_modes_axum/LICENSE
Normal file
21
examples/ssr_modes_axum/LICENSE
Normal file
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2022 henrik
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
54
examples/ssr_modes_axum/README.md
Normal file
54
examples/ssr_modes_axum/README.md
Normal file
@@ -0,0 +1,54 @@
|
||||
# Server-Side Rendering Modes
|
||||
|
||||
This example shows the different "rendering modes" that can be used while server-side
|
||||
rendering an application:
|
||||
1. **Synchronous**: Serve an HTML shell that includes `fallback` for any `Suspense`. Load data on the client, replacing `fallback` once they're loaded.
|
||||
- *Pros*: App shell appears very quickly: great TTFB (time to first byte).
|
||||
- *Cons*: Resources load relatively slowly; you need to wait for JS + Wasm to load before even making a request.
|
||||
2. **Out-of-order streaming**: Serve an HTML shell that includes `fallback` for any `Suspense`. Load data on the **server**, streaming it down to the client as it resolves, and streaming down HTML for `Suspense` nodes.
|
||||
- *Pros*: Combines the best of **synchronous** and **`async`**, with a very fast shell and resources that begin loading on the server.
|
||||
- *Cons*: Requires JS for suspended fragments to appear in correct order. Weaker meta tag support when it depends on data that's under suspense (has already streamed down `<head>`)
|
||||
3. **In-order streaming**: Walk through the tree, returning HTML synchronously as in synchronous rendering and out-of-order streaming until you hit a `Suspense`. At that point, wait for all its data to load, then render it, then the rest of the tree.
|
||||
- *Pros*: Does not require JS for HTML to appear in correct order.
|
||||
- *Cons*: Loads the shell more slowly than out-of-order streaming or synchronous rendering because it needs to pause at every `Suspense`. Cannot begin hydration until the entire page has loaded, so earlier pieces
|
||||
of the page will not be interactive until the suspended chunks have loaded.
|
||||
4. **`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.
|
||||
|
||||
## 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
|
||||
```
|
||||
|
||||
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
|
||||
```bash
|
||||
cargo run --no-default-features --features=ssr
|
||||
```
|
||||
|
||||
BIN
examples/ssr_modes_axum/assets/favicon.ico
Normal file
BIN
examples/ssr_modes_axum/assets/favicon.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 15 KiB |
189
examples/ssr_modes_axum/src/app.rs
Normal file
189
examples/ssr_modes_axum/src/app.rs
Normal file
@@ -0,0 +1,189 @@
|
||||
use lazy_static::lazy_static;
|
||||
use leptos::*;
|
||||
use leptos_meta::*;
|
||||
use leptos_router::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use thiserror::Error;
|
||||
|
||||
#[component]
|
||||
pub fn App(cx: Scope) -> impl IntoView {
|
||||
// Provides context that manages stylesheets, titles, meta tags, etc.
|
||||
provide_meta_context(cx);
|
||||
|
||||
view! { cx,
|
||||
<Stylesheet id="leptos" href="/pkg/ssr_modes.css"/>
|
||||
<Title text="Welcome to Leptos"/>
|
||||
|
||||
<Router>
|
||||
<main>
|
||||
<Routes>
|
||||
// We’ll 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
|
||||
/>
|
||||
<Route
|
||||
path="/post_in_order/:id"
|
||||
view=|cx| view! { cx, <Post/> }
|
||||
ssr=SsrMode::InOrder
|
||||
/>
|
||||
</Routes>
|
||||
</main>
|
||||
</Router>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
fn HomePage(cx: Scope) -> impl IntoView {
|
||||
// load the posts
|
||||
let posts =
|
||||
create_resource(cx, || (), |_| async { list_post_metadata().await });
|
||||
let posts_view = move || {
|
||||
posts.with(cx, |posts| posts
|
||||
.clone()
|
||||
.map(|posts| {
|
||||
posts.iter()
|
||||
.map(|post| view! { cx, <li><a href=format!("/post/{}", post.id)>{&post.title}</a> "|" <a href=format!("/post_in_order/{}", post.id)>{&post.title}"(in order)"</a></li>})
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
)
|
||||
};
|
||||
|
||||
view! { cx,
|
||||
<h1>"My Great Blog"</h1>
|
||||
<Suspense fallback=move || view! { cx, <p>"Loading posts..."</p> }>
|
||||
<ul>{posts_view}</ul>
|
||||
</Suspense>
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Params, Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub struct PostParams {
|
||||
id: usize,
|
||||
}
|
||||
|
||||
#[component]
|
||||
fn Post(cx: Scope) -> impl IntoView {
|
||||
let query = use_params::<PostParams>(cx);
|
||||
let id = move || {
|
||||
query.with(|q| {
|
||||
q.as_ref().map(|q| q.id).map_err(|_| PostError::InvalidId)
|
||||
})
|
||||
};
|
||||
let post = create_resource(cx, id, |id| async move {
|
||||
match id {
|
||||
Err(e) => Err(e),
|
||||
Ok(id) => get_post(id)
|
||||
.await
|
||||
.map(|data| data.ok_or(PostError::PostNotFound))
|
||||
.map_err(|_| PostError::ServerError)
|
||||
.flatten(),
|
||||
}
|
||||
});
|
||||
|
||||
let post_view = move || {
|
||||
post.with(cx, |post| {
|
||||
post.clone().map(|post| {
|
||||
view! { cx,
|
||||
// render content
|
||||
<h1>{&post.title}</h1>
|
||||
<p>{&post.content}</p>
|
||||
|
||||
// since we're using async rendering for this page,
|
||||
// this metadata should be included in the actual HTML <head>
|
||||
// when it's first served
|
||||
<Title text=post.title/>
|
||||
<Meta name="description" content=post.content/>
|
||||
}
|
||||
})
|
||||
})
|
||||
};
|
||||
|
||||
view! { cx,
|
||||
<Suspense fallback=move || view! { cx, <p>"Loading post..."</p> }>
|
||||
<ErrorBoundary fallback=|cx, errors| {
|
||||
view! { cx,
|
||||
<div class="error">
|
||||
<h1>"Something went wrong."</h1>
|
||||
<ul>
|
||||
{move || errors.get()
|
||||
.into_iter()
|
||||
.map(|(_, error)| view! { cx, <li>{error.to_string()} </li> })
|
||||
.collect::<Vec<_>>()
|
||||
}
|
||||
</ul>
|
||||
</div>
|
||||
}
|
||||
}>
|
||||
{post_view}
|
||||
</ErrorBoundary>
|
||||
</Suspense>
|
||||
}
|
||||
}
|
||||
|
||||
// Dummy API
|
||||
lazy_static! {
|
||||
static ref POSTS: Vec<Post> = vec![
|
||||
Post {
|
||||
id: 0,
|
||||
title: "My first post".to_string(),
|
||||
content: "This is my first post".to_string(),
|
||||
},
|
||||
Post {
|
||||
id: 1,
|
||||
title: "My second post".to_string(),
|
||||
content: "This is my second post".to_string(),
|
||||
},
|
||||
Post {
|
||||
id: 2,
|
||||
title: "My third post".to_string(),
|
||||
content: "This is my third post".to_string(),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
#[derive(Error, Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum PostError {
|
||||
#[error("Invalid post ID.")]
|
||||
InvalidId,
|
||||
#[error("Post not found.")]
|
||||
PostNotFound,
|
||||
#[error("Server error.")]
|
||||
ServerError,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Post {
|
||||
id: usize,
|
||||
title: String,
|
||||
content: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct PostMetadata {
|
||||
id: usize,
|
||||
title: String,
|
||||
}
|
||||
|
||||
#[server(ListPostMetadata, "/api")]
|
||||
pub async fn list_post_metadata() -> Result<Vec<PostMetadata>, ServerFnError> {
|
||||
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
|
||||
Ok(POSTS
|
||||
.iter()
|
||||
.map(|data| PostMetadata {
|
||||
id: data.id,
|
||||
title: data.title.clone(),
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
#[server(GetPost, "/api")]
|
||||
pub async fn get_post(id: usize) -> Result<Option<Post>, ServerFnError> {
|
||||
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
|
||||
Ok(POSTS.iter().find(|post| post.id == id).cloned())
|
||||
}
|
||||
45
examples/ssr_modes_axum/src/fallback.rs
Normal file
45
examples/ssr_modes_axum/src/fallback.rs
Normal file
@@ -0,0 +1,45 @@
|
||||
use cfg_if::cfg_if;
|
||||
|
||||
cfg_if! { if #[cfg(feature = "ssr")] {
|
||||
use axum::{
|
||||
body::{boxed, Body, BoxBody},
|
||||
extract::Extension,
|
||||
response::IntoResponse,
|
||||
http::{Request, Response, StatusCode, Uri},
|
||||
};
|
||||
use axum::response::Response as AxumResponse;
|
||||
use tower::ServiceExt;
|
||||
use tower_http::services::ServeDir;
|
||||
use std::sync::Arc;
|
||||
use leptos::{LeptosOptions, Errors, view};
|
||||
use crate::app::{App, AppProps};
|
||||
|
||||
pub async fn file_and_error_handler(uri: Uri, Extension(options): Extension<Arc<LeptosOptions>>, req: Request<Body>) -> AxumResponse {
|
||||
let options = &*options;
|
||||
let root = options.site_root.clone();
|
||||
let res = get_static_file(uri.clone(), &root).await.unwrap();
|
||||
|
||||
if res.status() == StatusCode::OK {
|
||||
res.into_response()
|
||||
} else{
|
||||
let handler = leptos_axum::render_app_to_stream(
|
||||
options.to_owned(),
|
||||
move |cx| view!{ cx, <App/> }
|
||||
);
|
||||
handler(req).await.into_response()
|
||||
}
|
||||
}
|
||||
|
||||
async fn get_static_file(uri: Uri, root: &str) -> Result<Response<BoxBody>, (StatusCode, String)> {
|
||||
let req = Request::builder().uri(uri.clone()).body(Body::empty()).unwrap();
|
||||
// `ServeDir` implements `tower::Service` so we can call it with `tower::ServiceExt::oneshot`
|
||||
// This path is relative to the cargo root
|
||||
match ServeDir::new(root).oneshot(req).await {
|
||||
Ok(res) => Ok(res.map(boxed)),
|
||||
Err(err) => Err((
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
format!("Something went wrong: {err}"),
|
||||
)),
|
||||
}
|
||||
}
|
||||
}}
|
||||
26
examples/ssr_modes_axum/src/lib.rs
Normal file
26
examples/ssr_modes_axum/src/lib.rs
Normal file
@@ -0,0 +1,26 @@
|
||||
#![feature(result_flattening)]
|
||||
|
||||
pub mod app;
|
||||
pub mod fallback;
|
||||
use cfg_if::cfg_if;
|
||||
|
||||
cfg_if! {
|
||||
if #[cfg(feature = "hydrate")] {
|
||||
|
||||
use wasm_bindgen::prelude::wasm_bindgen;
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub fn hydrate() {
|
||||
use app::*;
|
||||
use leptos::*;
|
||||
|
||||
// initializes logging using the `log` crate
|
||||
_ = console_log::init_with_level(log::Level::Debug);
|
||||
console_error_panic_hook::set_once();
|
||||
|
||||
leptos::mount_to_body(move |cx| {
|
||||
view! { cx, <App/> }
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
40
examples/ssr_modes_axum/src/main.rs
Normal file
40
examples/ssr_modes_axum/src/main.rs
Normal file
@@ -0,0 +1,40 @@
|
||||
#[cfg(feature = "ssr")]
|
||||
#[tokio::main]
|
||||
async fn main(){
|
||||
use leptos::*;
|
||||
use leptos_axum::{generate_route_list, LeptosRoutes};
|
||||
use axum::{extract::{Extension, Path}, Router, routing::{get, post}};
|
||||
use std::sync::Arc;
|
||||
use ssr_modes_axum::fallback::file_and_error_handler;
|
||||
use ssr_modes_axum::app::*;
|
||||
|
||||
let conf = get_configuration(None).await.unwrap();
|
||||
let addr = conf.leptos_options.site_addr;
|
||||
let leptos_options = conf.leptos_options;
|
||||
// Generate the list of routes in your Leptos App
|
||||
let routes = generate_route_list(|cx| view! { cx, <App/> }).await;
|
||||
|
||||
GetPost::register();
|
||||
ListPostMetadata::register();
|
||||
|
||||
let app = Router::new()
|
||||
.route("/api/*fn_name", post(leptos_axum::handle_server_fns))
|
||||
.leptos_routes(leptos_options.clone(), routes, |cx| view! { cx, <App/> })
|
||||
.fallback(file_and_error_handler)
|
||||
.layer(Extension(Arc::new(leptos_options)));
|
||||
|
||||
// run our app with hyper
|
||||
// `axum::Server` is a re-export of `hyper::Server`
|
||||
log!("listening on http://{}", &addr);
|
||||
axum::Server::bind(&addr)
|
||||
.serve(app.into_make_service())
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "ssr"))]
|
||||
pub fn main() {
|
||||
// no client-side main function
|
||||
// unless we want this to work with e.g., Trunk for pure client-side testing
|
||||
// see lib.rs for hydration function instead
|
||||
}
|
||||
3
examples/ssr_modes_axum/style/main.scss
Normal file
3
examples/ssr_modes_axum/style/main.scss
Normal file
@@ -0,0 +1,3 @@
|
||||
body {
|
||||
font-family: sans-serif;
|
||||
}
|
||||
99
examples/todo_app_sqlite_viz/Cargo.toml
Normal file
99
examples/todo_app_sqlite_viz/Cargo.toml
Normal file
@@ -0,0 +1,99 @@
|
||||
[package]
|
||||
name = "todo_app_sqlite_viz"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib", "rlib"]
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1.0.66"
|
||||
console_log = "0.2.0"
|
||||
console_error_panic_hook = "0.1.7"
|
||||
futures = "0.3.25"
|
||||
cfg-if = "1.0.0"
|
||||
leptos = { path = "../../leptos", default-features = false, features = [
|
||||
"serde",
|
||||
] }
|
||||
leptos_viz = { path = "../../integrations/viz", default-features = false, optional = true }
|
||||
leptos_meta = { path = "../../meta", default-features = false }
|
||||
leptos_router = { path = "../../router", default-features = false }
|
||||
leptos_reactive = { path = "../../leptos_reactive", default-features = false }
|
||||
log = "0.4.17"
|
||||
simple_logger = "4.0.0"
|
||||
serde = { version = "1.0.148", features = ["derive"] }
|
||||
serde_json = "1.0.89"
|
||||
gloo-net = { version = "0.2.5", features = ["http"] }
|
||||
reqwest = { version = "0.11.13", features = ["json"] }
|
||||
viz = { version = "0.4.8", features = ["serve"], optional = true }
|
||||
tokio = { version = "1.25.0", features = ["full"], optional = true }
|
||||
http = { version = "0.2.8" }
|
||||
sqlx = { version = "0.6.2", features = [
|
||||
"runtime-tokio-rustls",
|
||||
"sqlite",
|
||||
], optional = true }
|
||||
thiserror = "1.0.38"
|
||||
tracing = "0.1.37"
|
||||
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:viz",
|
||||
"dep:tokio",
|
||||
"dep:sqlx",
|
||||
"leptos/ssr",
|
||||
"leptos_meta/ssr",
|
||||
"leptos_router/ssr",
|
||||
"dep:leptos_viz"
|
||||
]
|
||||
|
||||
[package.metadata.cargo-all-features]
|
||||
denylist = ["viz", "tokio", "sqlx", "leptos_viz"]
|
||||
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
|
||||
output-name = "todo_app_sqlite_viz"
|
||||
# The site root folder is where cargo-leptos generate all output. WARNING: all content of this folder will be erased on a rebuild. Use it in your server setup.
|
||||
site-root = "target/site"
|
||||
# The site-root relative folder where all compiled output (JS, WASM and CSS) is written
|
||||
# Defaults to pkg
|
||||
site-pkg-dir = "pkg"
|
||||
# [Optional] The source CSS file. If it ends with .sass or .scss then it will be compiled by dart-sass into CSS. The CSS is optimized by Lightning CSS before being written to <site-root>/<site-pkg>/app.css
|
||||
style-file = "./style.css"
|
||||
# [Optional] Files in the asset-dir will be copied to the site-root directory
|
||||
assets-dir = "public"
|
||||
# The IP and port (ex: 127.0.0.1:3000) where the server serves the content. Use it in your server setup.
|
||||
site-addr = "127.0.0.1:3000"
|
||||
# The port to use for automatic reload monitoring
|
||||
reload-port = 3001
|
||||
# [Optional] Command to use when running end2end tests. It will run in the end2end dir.
|
||||
end2end-cmd = "npx playwright test"
|
||||
# The browserlist query used for optimizing the CSS.
|
||||
browserquery = "defaults"
|
||||
# Set by cargo-leptos watch when building with tha tool. Controls whether autoreload JS will be included in the head
|
||||
watch = false
|
||||
# The environment Leptos will run in, usually either "DEV" or "PROD"
|
||||
env = "DEV"
|
||||
# The features to use when compiling the bin target
|
||||
#
|
||||
# Optional. Can be over-ridden with the command line parameter --bin-features
|
||||
bin-features = ["ssr"]
|
||||
|
||||
# If the --no-default-features flag should be used when compiling the bin target
|
||||
#
|
||||
# Optional. Defaults to false.
|
||||
bin-default-features = false
|
||||
|
||||
# The features to use when compiling the lib target
|
||||
#
|
||||
# Optional. Can be over-ridden with the command line parameter --lib-features
|
||||
lib-features = ["hydrate"]
|
||||
|
||||
# If the --no-default-features flag should be used when compiling the lib target
|
||||
#
|
||||
# Optional. Defaults to false.
|
||||
lib-default-features = false
|
||||
21
examples/todo_app_sqlite_viz/LICENSE
Normal file
21
examples/todo_app_sqlite_viz/LICENSE
Normal file
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2022 Greg Johnston
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
9
examples/todo_app_sqlite_viz/Makefile.toml
Normal file
9
examples/todo_app_sqlite_viz/Makefile.toml
Normal file
@@ -0,0 +1,9 @@
|
||||
[tasks.build]
|
||||
command = "cargo"
|
||||
args = ["+nightly", "build-all-features"]
|
||||
install_crate = "cargo-all-features"
|
||||
|
||||
[tasks.check]
|
||||
command = "cargo"
|
||||
args = ["+nightly", "check-all-features"]
|
||||
install_crate = "cargo-all-features"
|
||||
42
examples/todo_app_sqlite_viz/README.md
Normal file
42
examples/todo_app_sqlite_viz/README.md
Normal file
@@ -0,0 +1,42 @@
|
||||
# Leptos Todo App Sqlite with Viz
|
||||
|
||||
This example creates a basic todo app with a Viz 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.
|
||||
|
||||
## 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
|
||||
```
|
||||
|
||||
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
|
||||
```bash
|
||||
cargo run --no-default-features --features=ssr
|
||||
```
|
||||
BIN
examples/todo_app_sqlite_viz/Todos.db
Normal file
BIN
examples/todo_app_sqlite_viz/Todos.db
Normal file
Binary file not shown.
@@ -0,0 +1,7 @@
|
||||
|
||||
CREATE TABLE IF NOT EXISTS todos
|
||||
(
|
||||
id INTEGER NOT NULL PRIMARY KEY,
|
||||
title VARCHAR,
|
||||
completed BOOLEAN
|
||||
);
|
||||
BIN
examples/todo_app_sqlite_viz/public/favicon.ico
Normal file
BIN
examples/todo_app_sqlite_viz/public/favicon.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 15 KiB |
61
examples/todo_app_sqlite_viz/src/error_template.rs
Normal file
61
examples/todo_app_sqlite_viz/src/error_template.rs
Normal file
@@ -0,0 +1,61 @@
|
||||
use crate::errors::TodoAppError;
|
||||
use cfg_if::cfg_if;
|
||||
use leptos::{Errors, *};
|
||||
#[cfg(feature = "ssr")]
|
||||
use leptos_viz::ResponseOptions;
|
||||
|
||||
// A basic function to display errors served by the error boundaries. Feel free to do more complicated things
|
||||
// here than just displaying them
|
||||
#[component]
|
||||
pub fn ErrorTemplate(
|
||||
cx: Scope,
|
||||
#[prop(optional)] outside_errors: Option<Errors>,
|
||||
#[prop(optional)] errors: Option<RwSignal<Errors>>,
|
||||
) -> impl IntoView {
|
||||
let errors = match outside_errors {
|
||||
Some(e) => create_rw_signal(cx, e),
|
||||
None => match errors {
|
||||
Some(e) => e,
|
||||
None => panic!("No Errors found and we expected errors!"),
|
||||
},
|
||||
};
|
||||
|
||||
// Get Errors from Signal
|
||||
// Downcast lets us take a type that implements `std::error::Error`
|
||||
let errors: Vec<TodoAppError> = errors
|
||||
.get()
|
||||
.into_iter()
|
||||
.filter_map(|(_k, v)| v.downcast_ref::<TodoAppError>().cloned())
|
||||
.collect();
|
||||
|
||||
// Only the response code for the first error is actually sent from the server
|
||||
// this may be customized by the specific application
|
||||
cfg_if! {
|
||||
if #[cfg(feature="ssr")]{
|
||||
let response = use_context::<ResponseOptions>(cx);
|
||||
if let Some(response) = response{
|
||||
response.set_status(errors[0].status_code());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
view! {cx,
|
||||
<h1>"Errors"</h1>
|
||||
<For
|
||||
// a function that returns the items we're iterating over; a signal is fine
|
||||
each= move || {errors.clone().into_iter().enumerate()}
|
||||
// a unique key for each item as a reference
|
||||
key=|(index, _error)| *index
|
||||
// renders each item to a view
|
||||
view= move |cx, error| {
|
||||
let error_string = error.1.to_string();
|
||||
let error_code= error.1.status_code();
|
||||
view! {
|
||||
cx,
|
||||
<h2>{error_code.to_string()}</h2>
|
||||
<p>"Error: " {error_string}</p>
|
||||
}
|
||||
}
|
||||
/>
|
||||
}
|
||||
}
|
||||
21
examples/todo_app_sqlite_viz/src/errors.rs
Normal file
21
examples/todo_app_sqlite_viz/src/errors.rs
Normal file
@@ -0,0 +1,21 @@
|
||||
use http::status::StatusCode;
|
||||
use thiserror::Error;
|
||||
|
||||
#[derive(Debug, Clone, Error)]
|
||||
pub enum TodoAppError {
|
||||
#[error("Not Found")]
|
||||
NotFound,
|
||||
#[error("Internal Server Error")]
|
||||
InternalServerError,
|
||||
}
|
||||
|
||||
impl TodoAppError {
|
||||
pub fn status_code(&self) -> StatusCode {
|
||||
match self {
|
||||
TodoAppError::NotFound => StatusCode::NOT_FOUND,
|
||||
TodoAppError::InternalServerError => {
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
58
examples/todo_app_sqlite_viz/src/fallback.rs
Normal file
58
examples/todo_app_sqlite_viz/src/fallback.rs
Normal file
@@ -0,0 +1,58 @@
|
||||
use cfg_if::cfg_if;
|
||||
|
||||
cfg_if! {
|
||||
if #[cfg(feature = "ssr")] {
|
||||
use crate::{
|
||||
error_template::{ErrorTemplate, ErrorTemplateProps},
|
||||
errors::TodoAppError,
|
||||
};
|
||||
use http::Uri;
|
||||
use leptos::{view, Errors, LeptosOptions};
|
||||
use std::sync::Arc;
|
||||
use viz::{
|
||||
handlers::serve, header::HeaderMap, types::RouteInfo, Body, Error, Handler,
|
||||
Request, RequestExt, Response, ResponseExt, Result,
|
||||
};
|
||||
|
||||
pub async fn file_and_error_handler(req: Request<Body>) -> Result<Response> {
|
||||
let uri = req.uri().clone();
|
||||
let headers = req.headers().clone();
|
||||
let route_info = req.route_info().clone();
|
||||
let options = &*req.state::<Arc<LeptosOptions>>().ok_or(
|
||||
Error::Responder(Response::text("missing state type LeptosOptions")),
|
||||
)?;
|
||||
let root = &options.site_root;
|
||||
let resp = get_static_file(uri, &root, headers, route_info).await?;
|
||||
let status = resp.status();
|
||||
|
||||
if status.is_success() || status.is_redirection() {
|
||||
Ok(resp)
|
||||
} else {
|
||||
let mut errors = Errors::default();
|
||||
errors.insert_with_default_key(TodoAppError::NotFound);
|
||||
let handler = leptos_viz::render_app_to_stream(
|
||||
options.to_owned(),
|
||||
move |cx| view! {cx, <ErrorTemplate outside_errors=errors.clone()/>},
|
||||
);
|
||||
handler(req).await
|
||||
}
|
||||
}
|
||||
|
||||
async fn get_static_file(
|
||||
uri: Uri,
|
||||
root: &str,
|
||||
headers: HeaderMap,
|
||||
route_info: Arc<RouteInfo>,
|
||||
) -> Result<Response> {
|
||||
let mut req = Request::builder()
|
||||
.uri(uri.clone())
|
||||
.extension(route_info)
|
||||
.body(Body::empty())
|
||||
.unwrap();
|
||||
*req.headers_mut() = headers;
|
||||
// This path is relative to the cargo root
|
||||
serve::Dir::new(root).call(req).await
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
25
examples/todo_app_sqlite_viz/src/lib.rs
Normal file
25
examples/todo_app_sqlite_viz/src/lib.rs
Normal file
@@ -0,0 +1,25 @@
|
||||
use cfg_if::cfg_if;
|
||||
use leptos::*;
|
||||
pub mod error_template;
|
||||
pub mod errors;
|
||||
pub mod fallback;
|
||||
pub mod todo;
|
||||
|
||||
// Needs to be in lib.rs AFAIK because wasm-bindgen needs us to be compiling a lib. I may be wrong.
|
||||
cfg_if! {
|
||||
if #[cfg(feature = "hydrate")] {
|
||||
use wasm_bindgen::prelude::wasm_bindgen;
|
||||
use crate::todo::*;
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub fn hydrate() {
|
||||
console_error_panic_hook::set_once();
|
||||
_ = console_log::init_with_level(log::Level::Debug);
|
||||
console_error_panic_hook::set_once();
|
||||
|
||||
leptos::mount_to_body(|cx| {
|
||||
view! { cx, <TodoApp/> }
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
80
examples/todo_app_sqlite_viz/src/main.rs
Normal file
80
examples/todo_app_sqlite_viz/src/main.rs
Normal file
@@ -0,0 +1,80 @@
|
||||
use cfg_if::cfg_if;
|
||||
use leptos::*;
|
||||
// boilerplate to run in different modes
|
||||
cfg_if! {
|
||||
if #[cfg(feature = "ssr")] {
|
||||
use crate::fallback::file_and_error_handler;
|
||||
use crate::todo::*;
|
||||
use leptos_viz::{generate_route_list, LeptosRoutes};
|
||||
use std::sync::Arc;
|
||||
use todo_app_sqlite_viz::*;
|
||||
use viz::{
|
||||
types::{State, StateError},
|
||||
Request, RequestExt, Response, Result, Router, ServiceMaker,
|
||||
};
|
||||
|
||||
//Define a handler to test extractor with state
|
||||
async fn custom_handler(req: Request) -> Result<Response> {
|
||||
let id = req.params::<String>()?;
|
||||
let options = &*req
|
||||
.state::<Arc<LeptosOptions>>()
|
||||
.ok_or(StateError::new::<LeptosOptions>())?;
|
||||
let handler = leptos_viz::render_app_to_stream_with_context(
|
||||
options.clone(),
|
||||
move |cx| {
|
||||
provide_context(cx, id.clone());
|
||||
},
|
||||
|cx| view! { cx, <TodoApp/> },
|
||||
);
|
||||
handler(req).await
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
simple_logger::init_with_level(log::Level::Debug)
|
||||
.expect("couldn't initialize logging");
|
||||
|
||||
let conn = db().await.expect("couldn't connect to DB");
|
||||
/* sqlx::migrate!()
|
||||
.run(&mut conn)
|
||||
.await
|
||||
.expect("could not run SQLx migrations"); */
|
||||
|
||||
crate::todo::register_server_functions();
|
||||
|
||||
// Setting this to None means we'll be using cargo-leptos and its env vars
|
||||
let conf = get_configuration(None).await.unwrap();
|
||||
let leptos_options = conf.leptos_options;
|
||||
let addr = leptos_options.site_addr;
|
||||
let routes = generate_route_list(|cx| view! { cx, <TodoApp/> }).await;
|
||||
|
||||
// build our application with a route
|
||||
let app = Router::new()
|
||||
.post("/api/:fn_name*", leptos_viz::handle_server_fns)
|
||||
.get("/special/:id", custom_handler)
|
||||
.leptos_routes(
|
||||
leptos_options.clone(),
|
||||
routes,
|
||||
|cx| view! { cx, <TodoApp/> },
|
||||
)
|
||||
.get("/*", file_and_error_handler)
|
||||
.with(State(Arc::new(leptos_options)));
|
||||
|
||||
// run our app with hyper
|
||||
// `viz::Server` is a re-export of `hyper::Server`
|
||||
log!("listening on http://{}", &addr);
|
||||
viz::Server::bind(&addr)
|
||||
.serve(ServiceMaker::from(app))
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
// client-only stuff for Trunk
|
||||
else {
|
||||
pub fn main() {
|
||||
// This example cannot be built as a trunk standalone CSR-only app.
|
||||
// Only the server may directly connect to the database.
|
||||
}
|
||||
}
|
||||
}
|
||||
220
examples/todo_app_sqlite_viz/src/todo.rs
Normal file
220
examples/todo_app_sqlite_viz/src/todo.rs
Normal file
@@ -0,0 +1,220 @@
|
||||
use crate::error_template::{ErrorTemplate, ErrorTemplateProps};
|
||||
use cfg_if::cfg_if;
|
||||
use leptos::*;
|
||||
use leptos_meta::*;
|
||||
use leptos_router::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
cfg_if! {
|
||||
if #[cfg(feature = "ssr")] {
|
||||
use sqlx::{Connection, SqliteConnection};
|
||||
// use http::{header::SET_COOKIE, HeaderMap, HeaderValue, StatusCode};
|
||||
|
||||
pub async fn db() -> Result<SqliteConnection, ServerFnError> {
|
||||
SqliteConnection::connect("sqlite:Todos.db").await.map_err(|e| ServerFnError::ServerError(e.to_string()))
|
||||
}
|
||||
|
||||
pub fn register_server_functions() {
|
||||
_ = GetTodos::register();
|
||||
_ = AddTodo::register();
|
||||
_ = DeleteTodo::register();
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, sqlx::FromRow)]
|
||||
pub struct Todo {
|
||||
id: u16,
|
||||
title: String,
|
||||
completed: bool,
|
||||
}
|
||||
} else {
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Todo {
|
||||
id: u16,
|
||||
title: String,
|
||||
completed: bool,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[server(GetTodos, "/api")]
|
||||
pub async fn get_todos(cx: Scope) -> Result<Vec<Todo>, ServerFnError> {
|
||||
// this is just an example of how to access server context injected in the handlers
|
||||
// http::Request doesn't implement Clone, so more work will be needed to do use_context() on this
|
||||
let req_parts = use_context::<leptos_viz::RequestParts>(cx);
|
||||
|
||||
if let Some(req_parts) = req_parts {
|
||||
println!("Uri = {:?}", req_parts.uri);
|
||||
}
|
||||
|
||||
use futures::TryStreamExt;
|
||||
|
||||
let mut conn = db().await?;
|
||||
|
||||
let mut todos = Vec::new();
|
||||
let mut rows = sqlx::query_as::<_, Todo>("SELECT * FROM todos").fetch(&mut conn);
|
||||
while let Some(row) = rows
|
||||
.try_next()
|
||||
.await
|
||||
.map_err(|e| ServerFnError::ServerError(e.to_string()))?
|
||||
{
|
||||
todos.push(row);
|
||||
}
|
||||
|
||||
// Add a random header(because why not)
|
||||
// let mut res_headers = HeaderMap::new();
|
||||
// res_headers.insert(SET_COOKIE, HeaderValue::from_str("fizz=buzz").unwrap());
|
||||
|
||||
// let res_parts = leptos_viz::ResponseParts {
|
||||
// headers: res_headers,
|
||||
// status: Some(StatusCode::IM_A_TEAPOT),
|
||||
// };
|
||||
|
||||
// let res_options_outer = use_context::<leptos_viz::ResponseOptions>(cx);
|
||||
// if let Some(res_options) = res_options_outer {
|
||||
// res_options.overwrite(res_parts).await;
|
||||
// }
|
||||
|
||||
Ok(todos)
|
||||
}
|
||||
|
||||
#[server(AddTodo, "/api")]
|
||||
pub async fn add_todo(title: String) -> Result<(), ServerFnError> {
|
||||
let mut conn = db().await?;
|
||||
|
||||
// fake API delay
|
||||
std::thread::sleep(std::time::Duration::from_millis(1250));
|
||||
|
||||
match sqlx::query("INSERT INTO todos (title, completed) VALUES ($1, false)")
|
||||
.bind(title)
|
||||
.execute(&mut conn)
|
||||
.await
|
||||
{
|
||||
Ok(_row) => Ok(()),
|
||||
Err(e) => Err(ServerFnError::ServerError(e.to_string())),
|
||||
}
|
||||
}
|
||||
|
||||
#[server(DeleteTodo, "/api")]
|
||||
pub async fn delete_todo(id: u16) -> Result<(), ServerFnError> {
|
||||
let mut conn = db().await?;
|
||||
|
||||
sqlx::query("DELETE FROM todos WHERE id = $1")
|
||||
.bind(id)
|
||||
.execute(&mut conn)
|
||||
.await
|
||||
.map(|_| ())
|
||||
.map_err(|e| ServerFnError::ServerError(e.to_string()))
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn TodoApp(cx: Scope) -> impl IntoView {
|
||||
//let id = use_context::<String>(cx);
|
||||
provide_meta_context(cx);
|
||||
view! {
|
||||
cx,
|
||||
<Link rel="shortcut icon" type_="image/ico" href="/favicon.ico"/>
|
||||
<Stylesheet id="leptos" href="/pkg/todo_app_sqlite_viz.css"/>
|
||||
<Router>
|
||||
<header>
|
||||
<h1>"My Tasks"</h1>
|
||||
</header>
|
||||
<main>
|
||||
<Routes>
|
||||
<Route path="" view=|cx| view! {
|
||||
cx,
|
||||
<ErrorBoundary fallback=|cx, errors| view!{cx, <ErrorTemplate errors=errors/>}>
|
||||
<Todos/>
|
||||
</ErrorBoundary>
|
||||
}/> //Route
|
||||
</Routes>
|
||||
</main>
|
||||
</Router>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn Todos(cx: Scope) -> impl IntoView {
|
||||
let add_todo = create_server_multi_action::<AddTodo>(cx);
|
||||
let delete_todo = create_server_action::<DeleteTodo>(cx);
|
||||
let submissions = add_todo.submissions();
|
||||
|
||||
// list of todos is loaded from the server in reaction to changes
|
||||
let todos = create_resource(
|
||||
cx,
|
||||
move || (add_todo.version().get(), delete_todo.version().get()),
|
||||
move |_| get_todos(cx),
|
||||
);
|
||||
|
||||
view! {
|
||||
cx,
|
||||
<div>
|
||||
<MultiActionForm action=add_todo>
|
||||
<label>
|
||||
"Add a Todo"
|
||||
<input type="text" name="title"/>
|
||||
</label>
|
||||
<input type="submit" value="Add"/>
|
||||
</MultiActionForm>
|
||||
<Transition fallback=move || view! {cx, <p>"Loading..."</p> }>
|
||||
{move || {
|
||||
let existing_todos = {
|
||||
move || {
|
||||
todos.read(cx)
|
||||
.map(move |todos| match todos {
|
||||
Err(e) => {
|
||||
vec![view! { cx, <pre class="error">"Server Error: " {e.to_string()}</pre>}.into_any()]
|
||||
}
|
||||
Ok(todos) => {
|
||||
if todos.is_empty() {
|
||||
vec![view! { cx, <p>"No tasks were found."</p> }.into_any()]
|
||||
} else {
|
||||
todos
|
||||
.into_iter()
|
||||
.map(move |todo| {
|
||||
view! {
|
||||
cx,
|
||||
<li>
|
||||
{todo.title}
|
||||
<ActionForm action=delete_todo>
|
||||
<input type="hidden" name="id" value={todo.id}/>
|
||||
<input type="submit" value="X"/>
|
||||
</ActionForm>
|
||||
</li>
|
||||
}
|
||||
.into_any()
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
}
|
||||
}
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
};
|
||||
|
||||
let pending_todos = move || {
|
||||
submissions
|
||||
.get()
|
||||
.into_iter()
|
||||
.filter(|submission| submission.pending().get())
|
||||
.map(|submission| {
|
||||
view! {
|
||||
cx,
|
||||
<li class="pending">{move || submission.input.get().map(|data| data.title) }</li>
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
|
||||
view! {
|
||||
cx,
|
||||
<ul>
|
||||
{existing_todos}
|
||||
{pending_todos}
|
||||
</ul>
|
||||
}
|
||||
}
|
||||
}
|
||||
</Transition>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
3
examples/todo_app_sqlite_viz/style.css
Normal file
3
examples/todo_app_sqlite_viz/style.css
Normal file
@@ -0,0 +1,3 @@
|
||||
.pending {
|
||||
color: purple;
|
||||
}
|
||||
@@ -912,7 +912,7 @@ where
|
||||
};
|
||||
|
||||
let (stream, runtime, scope) =
|
||||
render_to_stream_with_prefix_undisposed_with_context(
|
||||
render_to_stream_in_order_with_prefix_undisposed_with_context(
|
||||
app,
|
||||
|_| "".into(),
|
||||
add_context,
|
||||
|
||||
21
integrations/viz/Cargo.toml
Normal file
21
integrations/viz/Cargo.toml
Normal file
@@ -0,0 +1,21 @@
|
||||
[package]
|
||||
name = "leptos_viz"
|
||||
version = { workspace = true }
|
||||
edition = "2021"
|
||||
authors = ["Greg Johnston", "Fangdun Tsai"]
|
||||
license = "MIT"
|
||||
repository = "https://github.com/leptos-rs/leptos"
|
||||
description = "Viz integrations for the Leptos web framework."
|
||||
|
||||
[dependencies]
|
||||
viz = { version = "0.4.8" }
|
||||
futures = "0.3"
|
||||
http = "0.2.8"
|
||||
hyper = "0.14.23"
|
||||
leptos = { workspace = true, features = ["ssr"] }
|
||||
leptos_meta = { workspace = true, features = ["ssr"] }
|
||||
leptos_router = { workspace = true, features = ["ssr"] }
|
||||
leptos_config = { workspace = true }
|
||||
leptos_integration_utils = { workspace = true }
|
||||
tokio = { version = "1", features = ["full"] }
|
||||
parking_lot = "0.12.1"
|
||||
1077
integrations/viz/src/lib.rs
Normal file
1077
integrations/viz/src/lib.rs
Normal file
File diff suppressed because it is too large
Load Diff
@@ -58,8 +58,9 @@
|
||||
//! and [`hackernews_axum`](https://github.com/leptos-rs/leptos/tree/main/examples/hackernews_axum)
|
||||
//! integrate calls to a real external REST API, routing, server-side rendering and hydration to create
|
||||
//! a fully-functional that works as intended even before WASM has loaded and begun to run.
|
||||
//! - [`todo_app_sqlite`](https://github.com/leptos-rs/leptos/tree/main/examples/todo_app_sqlite) and
|
||||
//! [`todo_app_sqlite_axum`](https://github.com/leptos-rs/leptos/tree/main/examples/todo_app_sqlite_axum)
|
||||
//! - [`todo_app_sqlite`](https://github.com/leptos-rs/leptos/tree/main/examples/todo_app_sqlite),
|
||||
//! [`todo_app_sqlite_axum`](https://github.com/leptos-rs/leptos/tree/main/examples/todo_app_sqlite_axum), and
|
||||
//! [`todo_app_sqlite_viz`](https://github.com/leptos-rs/leptos/tree/main/examples/todo_app_sqlite_viz)
|
||||
//! show how to build a full-stack app using server functions and database connections.
|
||||
//! - [`tailwind`](https://github.com/leptos-rs/leptos/tree/main/examples/tailwind) shows how to integrate
|
||||
//! TailwindCSS with `cargo-leptos`.
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
use leptos_dom::{Fragment, IntoView, View};
|
||||
use leptos_macro::component;
|
||||
use leptos_reactive::{Scope, SignalSetter};
|
||||
use std::{cell::RefCell, rc::Rc};
|
||||
use leptos_reactive::{use_context, Scope, SignalSetter, SuspenseContext};
|
||||
use std::{
|
||||
cell::{Cell, RefCell},
|
||||
rc::Rc,
|
||||
};
|
||||
|
||||
/// If any [Resource](leptos_reactive::Resource)s are read in the `children` of this
|
||||
/// component, it will show the `fallback` while they are loading. Once all are resolved,
|
||||
@@ -74,18 +77,34 @@ where
|
||||
F: Fn() -> E + 'static,
|
||||
E: IntoView,
|
||||
{
|
||||
let prev_children = std::rc::Rc::new(RefCell::new(None::<Vec<View>>));
|
||||
let prev_children = Rc::new(RefCell::new(None::<Vec<View>>));
|
||||
|
||||
let first_run = Rc::new(std::cell::Cell::new(true));
|
||||
let child_runs = Cell::new(0);
|
||||
|
||||
crate::Suspense(
|
||||
cx,
|
||||
crate::SuspenseProps::builder()
|
||||
.fallback({
|
||||
let prev_child = Rc::clone(&prev_children);
|
||||
let first_run = Rc::clone(&first_run);
|
||||
move || {
|
||||
let suspense_context = use_context::<SuspenseContext>(cx)
|
||||
.expect("there to be a SuspenseContext");
|
||||
|
||||
let is_first_run =
|
||||
is_first_run(&first_run, &suspense_context);
|
||||
first_run.set(is_first_run);
|
||||
|
||||
if let Some(set_pending) = &set_pending {
|
||||
set_pending.set(true);
|
||||
}
|
||||
if let Some(prev_children) = &*prev_child.borrow() {
|
||||
prev_children.clone().into_view(cx)
|
||||
if is_first_run {
|
||||
fallback().into_view(cx)
|
||||
} else {
|
||||
prev_children.clone().into_view(cx)
|
||||
}
|
||||
} else {
|
||||
fallback().into_view(cx)
|
||||
}
|
||||
@@ -93,7 +112,21 @@ where
|
||||
})
|
||||
.children(Box::new(move |cx| {
|
||||
let frag = children(cx);
|
||||
*prev_children.borrow_mut() = Some(frag.nodes.clone());
|
||||
|
||||
let suspense_context = use_context::<SuspenseContext>(cx)
|
||||
.expect("there to be a SuspenseContext");
|
||||
|
||||
if is_first_run(&first_run, &suspense_context) {
|
||||
let has_local_only = suspense_context.has_local_only();
|
||||
*prev_children.borrow_mut() = Some(frag.nodes.clone());
|
||||
if (has_local_only && child_runs.get() > 0)
|
||||
|| !has_local_only
|
||||
{
|
||||
first_run.set(false);
|
||||
}
|
||||
}
|
||||
child_runs.set(child_runs.get() + 1);
|
||||
|
||||
if let Some(set_pending) = &set_pending {
|
||||
set_pending.set(false);
|
||||
}
|
||||
@@ -102,3 +135,22 @@ where
|
||||
.build(),
|
||||
)
|
||||
}
|
||||
|
||||
fn is_first_run(
|
||||
first_run: &Rc<Cell<bool>>,
|
||||
suspense_context: &SuspenseContext,
|
||||
) -> bool {
|
||||
match (
|
||||
first_run.get(),
|
||||
cfg!(feature = "hydrate"),
|
||||
suspense_context.has_local_only(),
|
||||
) {
|
||||
(false, _, _) => false,
|
||||
// is in hydrate mode, and has non-local resources (so, has streamed)
|
||||
(_, false, false) => false,
|
||||
// is in hydrate mode, but with only local resources (so, has not streamed)
|
||||
(_, false, true) => true,
|
||||
// either SSR or client mode: it's the first run
|
||||
(_, true, _) => true,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@ pub struct ConfFile {
|
||||
}
|
||||
|
||||
/// This struct serves as a convenient place to store details used for configuring Leptos.
|
||||
/// It's used in our actix and axum integrations to generate the
|
||||
/// It's used in our actix, axum, and viz integrations to generate the
|
||||
/// correct path for WASM, JS, and Websockets, as well as other configuration tasks.
|
||||
/// It shares keys with cargo-leptos, to allow for easy interoperability
|
||||
#[derive(TypedBuilder, Debug, Clone, serde::Deserialize)]
|
||||
|
||||
@@ -166,11 +166,11 @@ impl Mountable for EachRepr {
|
||||
pub(crate) struct EachItem {
|
||||
cx: Scope,
|
||||
#[cfg(all(target_arch = "wasm32", feature = "web"))]
|
||||
document_fragment: web_sys::DocumentFragment,
|
||||
document_fragment: Option<web_sys::DocumentFragment>,
|
||||
#[cfg(debug_assertions)]
|
||||
opening: Comment,
|
||||
pub(crate) child: View,
|
||||
closing: Comment,
|
||||
closing: Option<Comment>,
|
||||
#[cfg(not(all(target_arch = "wasm32", feature = "web")))]
|
||||
pub(crate) id: HydrationKey,
|
||||
}
|
||||
@@ -192,16 +192,22 @@ impl fmt::Debug for EachItem {
|
||||
impl EachItem {
|
||||
fn new(cx: Scope, child: View) -> Self {
|
||||
let id = HydrationCtx::id();
|
||||
let needs_closing = !matches!(child, View::Element(_));
|
||||
|
||||
let markers = (
|
||||
Comment::new(Cow::Borrowed("</EachItem>"), &id, true),
|
||||
if needs_closing {
|
||||
Some(Comment::new(Cow::Borrowed("</EachItem>"), &id, true))
|
||||
} else {
|
||||
None
|
||||
},
|
||||
#[cfg(debug_assertions)]
|
||||
Comment::new(Cow::Borrowed("<EachItem>"), &id, false),
|
||||
);
|
||||
|
||||
#[cfg(all(target_arch = "wasm32", feature = "web"))]
|
||||
let document_fragment = {
|
||||
let document_fragment = if needs_closing {
|
||||
let fragment = crate::document().create_document_fragment();
|
||||
let closing = markers.0.as_ref().unwrap();
|
||||
|
||||
// Insert the comments into the document fragment
|
||||
// so they can serve as our references when inserting
|
||||
@@ -209,14 +215,16 @@ impl EachItem {
|
||||
if !HydrationCtx::is_hydrating() {
|
||||
#[cfg(debug_assertions)]
|
||||
fragment
|
||||
.append_with_node_2(&markers.1.node, &markers.0.node)
|
||||
.append_with_node_2(&markers.1.node, &closing.node)
|
||||
.unwrap();
|
||||
fragment.append_with_node_1(&markers.0.node).unwrap();
|
||||
fragment.append_with_node_1(&closing.node).unwrap();
|
||||
}
|
||||
|
||||
mount_child(MountKind::Before(&markers.0.node), &child);
|
||||
mount_child(MountKind::Before(&closing.node), &child);
|
||||
|
||||
fragment
|
||||
Some(fragment)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
Self {
|
||||
@@ -243,7 +251,11 @@ impl Drop for EachItem {
|
||||
#[cfg(all(target_arch = "wasm32", feature = "web"))]
|
||||
impl Mountable for EachItem {
|
||||
fn get_mountable_node(&self) -> web_sys::Node {
|
||||
self.document_fragment.clone().unchecked_into()
|
||||
if let Some(fragment) = &self.document_fragment {
|
||||
fragment.clone().unchecked_into()
|
||||
} else {
|
||||
self.child.get_mountable_node()
|
||||
}
|
||||
}
|
||||
|
||||
fn get_opening_node(&self) -> web_sys::Node {
|
||||
@@ -255,7 +267,11 @@ impl Mountable for EachItem {
|
||||
}
|
||||
|
||||
fn get_closing_node(&self) -> web_sys::Node {
|
||||
self.closing.node.clone()
|
||||
if let Some(closing) = &self.closing {
|
||||
closing.node.clone().unchecked_into()
|
||||
} else {
|
||||
self.child.get_mountable_node().clone()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -264,20 +280,25 @@ impl EachItem {
|
||||
/// order to be reinserted somewhere else.
|
||||
#[cfg(all(target_arch = "wasm32", feature = "web"))]
|
||||
fn prepare_for_move(&self) {
|
||||
let start = self.get_opening_node();
|
||||
let end = &self.closing.node;
|
||||
if let Some(fragment) = &self.document_fragment {
|
||||
let start = self.get_opening_node();
|
||||
let end = &self.get_closing_node();
|
||||
|
||||
let mut sibling = start;
|
||||
let mut sibling = start;
|
||||
|
||||
while sibling != *end {
|
||||
let next_sibling = sibling.next_sibling().unwrap();
|
||||
while sibling != *end {
|
||||
let next_sibling = sibling.next_sibling().unwrap();
|
||||
|
||||
self.document_fragment.append_child(&sibling).unwrap();
|
||||
fragment.append_child(&sibling).unwrap();
|
||||
|
||||
sibling = next_sibling;
|
||||
sibling = next_sibling;
|
||||
}
|
||||
|
||||
fragment.append_with_node_1(end).unwrap();
|
||||
} else {
|
||||
let node = self.child.get_mountable_node();
|
||||
node.unchecked_into::<web_sys::Element>().remove();
|
||||
}
|
||||
|
||||
self.document_fragment.append_with_node_1(end).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -349,7 +370,7 @@ where
|
||||
|
||||
cfg_if::cfg_if! {
|
||||
if #[cfg(all(target_arch = "wasm32", feature = "web"))] {
|
||||
create_effect(cx, move |prev_hash_run| {
|
||||
create_effect(cx, move |prev_hash_run: Option<HashRun<FxIndexSet<K>>>| {
|
||||
let mut children_borrow = children.borrow_mut();
|
||||
|
||||
#[cfg(all(target_arch = "wasm32", feature = "web"))]
|
||||
@@ -359,39 +380,60 @@ where
|
||||
closing.clone()
|
||||
};
|
||||
|
||||
let items = items_fn();
|
||||
let items_iter = items_fn().into_iter();
|
||||
|
||||
let items = items.into_iter().collect::<SmallVec<[_; 128]>>();
|
||||
|
||||
let hashed_items =
|
||||
items.iter().map(&key_fn).collect::<FxIndexSet<_>>();
|
||||
let (capacity, _) = items_iter.size_hint();
|
||||
let mut hashed_items = FxIndexSet::with_capacity_and_hasher(
|
||||
capacity,
|
||||
BuildHasherDefault::<FxHasher>::default()
|
||||
);
|
||||
|
||||
if let Some(HashRun(prev_hash_run)) = prev_hash_run {
|
||||
let cmds = diff(&prev_hash_run, &hashed_items);
|
||||
if !prev_hash_run.is_empty() {
|
||||
let mut items = Vec::with_capacity(capacity);
|
||||
for item in items_iter {
|
||||
hashed_items.insert(key_fn(&item));
|
||||
items.push(Some(item));
|
||||
}
|
||||
|
||||
apply_cmds(
|
||||
cx,
|
||||
#[cfg(all(target_arch = "wasm32", feature = "web"))]
|
||||
&opening,
|
||||
#[cfg(all(target_arch = "wasm32", feature = "web"))]
|
||||
&closing,
|
||||
cmds,
|
||||
&mut children_borrow,
|
||||
items.into_iter().map(|t| Some(t)).collect(),
|
||||
&each_fn
|
||||
);
|
||||
} else {
|
||||
*children_borrow = Vec::with_capacity(items.len());
|
||||
let cmds = diff(&prev_hash_run, &hashed_items);
|
||||
|
||||
for item in items {
|
||||
apply_cmds(
|
||||
cx,
|
||||
#[cfg(all(target_arch = "wasm32", feature = "web"))]
|
||||
&opening,
|
||||
#[cfg(all(target_arch = "wasm32", feature = "web"))]
|
||||
&closing,
|
||||
cmds,
|
||||
&mut children_borrow,
|
||||
items,
|
||||
&each_fn
|
||||
);
|
||||
return HashRun(hashed_items);
|
||||
}
|
||||
}
|
||||
|
||||
// if previous run is empty
|
||||
*children_borrow = Vec::with_capacity(capacity);
|
||||
#[cfg(all(target_arch = "wasm32", feature = "web"))]
|
||||
let fragment = crate::document().create_document_fragment();
|
||||
|
||||
for item in items_iter {
|
||||
hashed_items.insert(key_fn(&item));
|
||||
let (each_item, _) = cx.run_child_scope(|cx| EachItem::new(cx, each_fn(cx, item).into_view(cx)));
|
||||
|
||||
#[cfg(all(target_arch = "wasm32", feature = "web"))]
|
||||
mount_child(MountKind::Before(&closing), &each_item);
|
||||
#[cfg(all(target_arch = "wasm32", feature = "web"))]
|
||||
{
|
||||
_ = fragment.append_child(&each_item.get_mountable_node());
|
||||
}
|
||||
|
||||
children_borrow.push(Some(each_item));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(target_arch = "wasm32", feature = "web"))]
|
||||
closing
|
||||
.unchecked_ref::<web_sys::Element>()
|
||||
.before_with_node_1(&fragment)
|
||||
.expect("before to not err");
|
||||
|
||||
HashRun(hashed_items)
|
||||
});
|
||||
@@ -421,6 +463,18 @@ fn diff<K: Eq + Hash>(from: &FxIndexSet<K>, to: &FxIndexSet<K>) -> Diff {
|
||||
clear: true,
|
||||
..Default::default()
|
||||
};
|
||||
} else if from.is_empty() {
|
||||
return Diff {
|
||||
added: to
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(at, _)| DiffOpAdd {
|
||||
at,
|
||||
mode: DiffOpAddMode::Append,
|
||||
})
|
||||
.collect(),
|
||||
..Default::default()
|
||||
};
|
||||
}
|
||||
|
||||
// Get removed items
|
||||
@@ -445,7 +499,7 @@ fn diff<K: Eq + Hash>(from: &FxIndexSet<K>, to: &FxIndexSet<K>) -> Diff {
|
||||
|
||||
// Get moved items
|
||||
let mut normalized_idx = 0;
|
||||
let mut move_cmds = SmallVec::<[_; 8]>::with_capacity(to.len());
|
||||
let mut move_cmds = Vec::new();
|
||||
let mut added_idx = added.next().map(|k| to.get_full(k).unwrap().0);
|
||||
let mut removed_idx = removed.next().map(|k| from.get_full(k).unwrap().0);
|
||||
|
||||
@@ -539,9 +593,9 @@ fn apply_opts<K: Eq + Hash>(
|
||||
#[derive(Debug, Default)]
|
||||
#[allow(unused)]
|
||||
struct Diff {
|
||||
removed: SmallVec<[DiffOpRemove; 8]>,
|
||||
moved: SmallVec<[DiffOpMove; 8]>,
|
||||
added: SmallVec<[DiffOpAdd; 8]>,
|
||||
removed: Vec<DiffOpRemove>,
|
||||
moved: Vec<DiffOpMove>,
|
||||
added: Vec<DiffOpAdd>,
|
||||
clear: bool,
|
||||
}
|
||||
|
||||
@@ -588,7 +642,7 @@ fn apply_cmds<T, EF, N>(
|
||||
closing: &web_sys::Node,
|
||||
mut cmds: Diff,
|
||||
children: &mut Vec<Option<EachItem>>,
|
||||
mut items: SmallVec<[Option<T>; 128]>,
|
||||
mut items: Vec<Option<T>>,
|
||||
each_fn: &EF,
|
||||
) where
|
||||
EF: Fn(Scope, T) -> N,
|
||||
|
||||
@@ -23,7 +23,12 @@ pub fn add_event_helper<E: crate::ev::EventDescriptor + 'static>(
|
||||
let event_name = event.name();
|
||||
|
||||
if event.bubbles() {
|
||||
add_event_listener(target, event_name, event_handler);
|
||||
add_event_listener(
|
||||
target,
|
||||
event.event_delegation_key(),
|
||||
event_name,
|
||||
event_handler,
|
||||
);
|
||||
} else {
|
||||
add_event_listener_undelegated(target, &event_name, event_handler);
|
||||
}
|
||||
@@ -34,6 +39,7 @@ pub fn add_event_helper<E: crate::ev::EventDescriptor + 'static>(
|
||||
#[cfg(all(target_arch = "wasm32", feature = "web"))]
|
||||
pub fn add_event_listener<E>(
|
||||
target: &web_sys::Element,
|
||||
key: Cow<'static, str>,
|
||||
event_name: Cow<'static, str>,
|
||||
#[cfg(debug_assertions)] mut cb: impl FnMut(E) + 'static,
|
||||
#[cfg(not(debug_assertions))] cb: impl FnMut(E) + 'static,
|
||||
@@ -51,9 +57,9 @@ pub fn add_event_listener<E>(
|
||||
}
|
||||
|
||||
let cb = Closure::wrap(Box::new(cb) as Box<dyn FnMut(E)>).into_js_value();
|
||||
let key = event_delegation_key(&event_name);
|
||||
let key = intern(&key);
|
||||
_ = js_sys::Reflect::set(target, &JsValue::from_str(&key), &cb);
|
||||
add_delegated_event_listener(event_name);
|
||||
add_delegated_event_listener(&key, event_name);
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
@@ -61,7 +67,8 @@ pub fn add_event_listener<E>(
|
||||
pub(crate) fn add_event_listener_undelegated<E>(
|
||||
target: &web_sys::Element,
|
||||
event_name: &str,
|
||||
mut cb: impl FnMut(E) + 'static,
|
||||
#[cfg(debug_assertions)] mut cb: impl FnMut(E) + 'static,
|
||||
#[cfg(not(debug_assertions))] cb: impl FnMut(E) + 'static,
|
||||
) where
|
||||
E: FromWasmAbi + 'static,
|
||||
{
|
||||
@@ -82,12 +89,15 @@ pub(crate) fn add_event_listener_undelegated<E>(
|
||||
|
||||
// cf eventHandler in ryansolid/dom-expressions
|
||||
#[cfg(all(target_arch = "wasm32", feature = "web"))]
|
||||
pub(crate) fn add_delegated_event_listener(event_name: Cow<'static, str>) {
|
||||
pub(crate) fn add_delegated_event_listener(
|
||||
key: &str,
|
||||
event_name: Cow<'static, str>,
|
||||
) {
|
||||
GLOBAL_EVENTS.with(|global_events| {
|
||||
let mut events = global_events.borrow_mut();
|
||||
if !events.contains(&event_name) {
|
||||
// create global handler
|
||||
let key = JsValue::from_str(&event_delegation_key(&event_name));
|
||||
let key = JsValue::from_str(&key);
|
||||
let handler = move |ev: web_sys::Event| {
|
||||
let target = ev.target();
|
||||
let node = ev.composed_path().get(0);
|
||||
@@ -163,11 +173,3 @@ pub(crate) fn add_delegated_event_listener(event_name: Cow<'static, str>) {
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(all(target_arch = "wasm32", feature = "web"))]
|
||||
pub(crate) fn event_delegation_key(event_name: &str) -> String {
|
||||
let event_name = intern(event_name);
|
||||
let mut n = String::from("$$$");
|
||||
n.push_str(event_name);
|
||||
n
|
||||
}
|
||||
|
||||
@@ -11,6 +11,9 @@ pub trait EventDescriptor: Clone {
|
||||
/// 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.
|
||||
///
|
||||
@@ -34,6 +37,10 @@ impl<Ev: EventDescriptor> EventDescriptor for undelegated<Ev> {
|
||||
self.0.name()
|
||||
}
|
||||
|
||||
fn event_delegation_key(&self) -> Cow<'static, str> {
|
||||
self.0.event_delegation_key()
|
||||
}
|
||||
|
||||
fn bubbles(&self) -> bool {
|
||||
false
|
||||
}
|
||||
@@ -61,6 +68,10 @@ impl<E: FromWasmAbi> EventDescriptor for Custom<E> {
|
||||
self.name.clone()
|
||||
}
|
||||
|
||||
fn event_delegation_key(&self) -> Cow<'static, str> {
|
||||
format!("$$${}", self.name).into()
|
||||
}
|
||||
|
||||
fn bubbles(&self) -> bool {
|
||||
false
|
||||
}
|
||||
@@ -97,6 +108,10 @@ macro_rules! generate_event_types {
|
||||
stringify!($event).into()
|
||||
}
|
||||
|
||||
fn event_delegation_key(&self) -> Cow<'static, str> {
|
||||
concat!("$$$", stringify!($event)).into()
|
||||
}
|
||||
|
||||
$(
|
||||
generate_event_types!($does_not_bubble);
|
||||
)?
|
||||
@@ -226,6 +241,7 @@ generate_event_types! {
|
||||
submit: SubmitEvent,
|
||||
suspend: Event,
|
||||
timeupdate: Event,
|
||||
#[does_not_bubble]
|
||||
toggle: Event,
|
||||
touchcancel: TouchEvent,
|
||||
touchend: TouchEvent,
|
||||
|
||||
@@ -623,9 +623,12 @@ impl<El: ElementDescriptor + 'static> HtmlElement<El> {
|
||||
}
|
||||
let event_name = event.name();
|
||||
|
||||
let key = event.event_delegation_key();
|
||||
|
||||
if event.bubbles() {
|
||||
add_event_listener(
|
||||
self.element.as_ref(),
|
||||
key,
|
||||
event_name,
|
||||
event_handler,
|
||||
);
|
||||
@@ -905,6 +908,11 @@ fn create_leptos_element(
|
||||
id: crate::HydrationKey,
|
||||
clone_element: fn() -> web_sys::HtmlElement,
|
||||
) -> web_sys::HtmlElement {
|
||||
#[cfg(not(debug_assertions))]
|
||||
{
|
||||
_ = tag;
|
||||
}
|
||||
|
||||
if HydrationCtx::is_hydrating() {
|
||||
if let Some(el) = crate::document().get_element_by_id(&format!("_{id}"))
|
||||
{
|
||||
|
||||
@@ -584,7 +584,7 @@ impl View {
|
||||
match &self {
|
||||
Self::Element(el) => {
|
||||
if event.bubbles() {
|
||||
add_event_listener(&el.element, event.name(), event_handler);
|
||||
add_event_listener(&el.element, event.event_delegation_key(), event.name(), event_handler);
|
||||
} else {
|
||||
add_event_listener_undelegated(
|
||||
&el.element,
|
||||
|
||||
@@ -348,31 +348,30 @@ impl Docs {
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(idx, attr)| {
|
||||
if let Meta::NameValue(MetaNameValue { lit: doc, .. }) =
|
||||
attr.parse_meta().unwrap()
|
||||
{
|
||||
let doc_str = quote!(#doc);
|
||||
match attr.parse_meta() {
|
||||
Ok(Meta::NameValue(MetaNameValue { lit: doc, .. })) => {
|
||||
let doc_str = quote!(#doc);
|
||||
|
||||
// We need to remove the leading and trailing `"`"
|
||||
let mut doc_str = doc_str.to_string();
|
||||
doc_str.pop();
|
||||
doc_str.remove(0);
|
||||
// We need to remove the leading and trailing `"`"
|
||||
let mut doc_str = doc_str.to_string();
|
||||
doc_str.pop();
|
||||
doc_str.remove(0);
|
||||
|
||||
let doc_str = if idx == 0 {
|
||||
format!(" - {doc_str}")
|
||||
} else {
|
||||
format!(" {doc_str}")
|
||||
};
|
||||
let doc_str = if idx == 0 {
|
||||
format!(" - {doc_str}")
|
||||
} else {
|
||||
format!(" {doc_str}")
|
||||
};
|
||||
|
||||
let docs = LitStr::new(&doc_str, doc.span());
|
||||
let docs = LitStr::new(&doc_str, doc.span());
|
||||
|
||||
if !doc_str.is_empty() {
|
||||
quote! { #[doc = #docs] }
|
||||
} else {
|
||||
quote! {}
|
||||
if !doc_str.is_empty() {
|
||||
quote! { #[doc = #docs] }
|
||||
} else {
|
||||
quote! {}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
unreachable!()
|
||||
_ => abort!(attr, "could not parse attributes"),
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
@@ -384,18 +383,17 @@ impl Docs {
|
||||
.0
|
||||
.iter()
|
||||
.map(|attr| {
|
||||
if let Meta::NameValue(MetaNameValue { lit: doc, .. }) =
|
||||
attr.parse_meta().unwrap()
|
||||
{
|
||||
let mut doc_str = quote!(#doc).to_string();
|
||||
match attr.parse_meta() {
|
||||
Ok(Meta::NameValue(MetaNameValue { lit: doc, .. })) => {
|
||||
let mut doc_str = quote!(#doc).to_string();
|
||||
|
||||
// Remove the leading and trailing `"`
|
||||
doc_str.pop();
|
||||
doc_str.remove(0);
|
||||
// Remove the leading and trailing `"`
|
||||
doc_str.pop();
|
||||
doc_str.remove(0);
|
||||
|
||||
doc_str
|
||||
} else {
|
||||
unreachable!()
|
||||
doc_str
|
||||
}
|
||||
_ => abort!(attr, "could not parse attributes"),
|
||||
}
|
||||
})
|
||||
.intersperse("\n".to_string())
|
||||
@@ -633,7 +631,7 @@ fn is_option(ty: &Type) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
fn unwrap_option(ty: &Type) -> Option<Type> {
|
||||
fn unwrap_option(ty: &Type) -> Type {
|
||||
const STD_OPTION_MSG: &str =
|
||||
"make sure you're not shadowing the `std::option::Option` type that \
|
||||
is automatically imported from the standard prelude";
|
||||
@@ -651,37 +649,19 @@ fn unwrap_option(ty: &Type) -> Option<Type> {
|
||||
{
|
||||
if let [first] = &args.iter().collect::<Vec<_>>()[..] {
|
||||
if let GenericArgument::Type(ty) = first {
|
||||
Some(ty.clone())
|
||||
} else {
|
||||
abort!(
|
||||
first,
|
||||
"`Option` must be `std::option::Option`";
|
||||
help = STD_OPTION_MSG
|
||||
);
|
||||
return ty.clone();
|
||||
}
|
||||
} else {
|
||||
abort!(
|
||||
first,
|
||||
"`Option` must be `std::option::Option`";
|
||||
help = STD_OPTION_MSG
|
||||
);
|
||||
}
|
||||
} else {
|
||||
abort!(
|
||||
first,
|
||||
"`Option` must be `std::option::Option`";
|
||||
help = STD_OPTION_MSG
|
||||
);
|
||||
}
|
||||
} else {
|
||||
None
|
||||
}
|
||||
} else {
|
||||
None
|
||||
}
|
||||
} else {
|
||||
None
|
||||
}
|
||||
|
||||
abort!(
|
||||
ty,
|
||||
"`Option` must be `std::option::Option`";
|
||||
help = STD_OPTION_MSG
|
||||
);
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
@@ -703,7 +683,7 @@ fn prop_to_doc(
|
||||
|| prop_opts.contains(&PropOpt::StripOption))
|
||||
&& is_option(ty)
|
||||
{
|
||||
unwrap_option(ty).unwrap()
|
||||
unwrap_option(ty)
|
||||
} else {
|
||||
ty.to_owned()
|
||||
};
|
||||
|
||||
@@ -9,7 +9,7 @@ use proc_macro2::TokenTree;
|
||||
use quote::ToTokens;
|
||||
use server::server_macro_impl;
|
||||
use syn::parse_macro_input;
|
||||
use syn_rsx::{parse, NodeElement};
|
||||
use syn_rsx::{parse, NodeAttribute, NodeElement};
|
||||
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum Mode {
|
||||
@@ -304,13 +304,10 @@ pub fn view(tokens: TokenStream) -> TokenStream {
|
||||
third.clone()
|
||||
}
|
||||
_ => {
|
||||
let error_msg = concat!(
|
||||
"To create a scope class with the view! macro \
|
||||
you must put a comma `,` after the value.\n",
|
||||
"e.g., view!{cx, class=\"my-class\", \
|
||||
<div>...</div>}"
|
||||
);
|
||||
panic!("{error_msg}")
|
||||
abort!(
|
||||
punct, "To create a scope class with the view! macro you must put a comma `,` after the value";
|
||||
help = r#"e.g., view!{cx, class="my-class", <div>...</div>}"#
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -338,7 +335,7 @@ pub fn view(tokens: TokenStream) -> TokenStream {
|
||||
.into()
|
||||
}
|
||||
_ => {
|
||||
panic!(
|
||||
abort_call_site!(
|
||||
"view! macro needs a context and RSX: e.g., view! {{ cx, \
|
||||
<div>...</div> }}"
|
||||
)
|
||||
@@ -372,7 +369,7 @@ pub fn template(tokens: TokenStream) -> TokenStream {
|
||||
.into()
|
||||
}
|
||||
_ => {
|
||||
panic!(
|
||||
abort_call_site!(
|
||||
"view! macro needs a context and RSX: e.g., view! {{ cx, \
|
||||
<div>...</div> }}"
|
||||
)
|
||||
@@ -693,8 +690,10 @@ pub fn server(args: proc_macro::TokenStream, s: TokenStream) -> TokenStream {
|
||||
pub fn params_derive(
|
||||
input: proc_macro::TokenStream,
|
||||
) -> proc_macro::TokenStream {
|
||||
let ast = syn::parse(input).unwrap();
|
||||
params::impl_params(&ast)
|
||||
match syn::parse(input) {
|
||||
Ok(ast) => params::impl_params(&ast),
|
||||
Err(err) => err.to_compile_error().into(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn is_component_node(node: &NodeElement) -> bool {
|
||||
@@ -702,3 +701,10 @@ pub(crate) fn is_component_node(node: &NodeElement) -> bool {
|
||||
.to_string()
|
||||
.starts_with(|c: char| c.is_ascii_uppercase())
|
||||
}
|
||||
|
||||
pub(crate) fn attribute_value(attr: &NodeAttribute) -> &syn::Expr {
|
||||
match &attr.value {
|
||||
Some(value) => value.as_ref(),
|
||||
None => abort!(attr.key, "attribute should have value"),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,10 +13,10 @@ pub fn impl_params(ast: &syn::DeriveInput) -> proc_macro::TokenStream {
|
||||
.named
|
||||
.iter()
|
||||
.map(|field| {
|
||||
let field_name_string = &field.ident.as_ref().unwrap().to_string();
|
||||
let field_name_string = &field.ident.as_ref().expect("expected named struct fields").to_string();
|
||||
let ident = &field.ident;
|
||||
let ty = &field.ty;
|
||||
let span = field.span().unwrap();
|
||||
let span = field.span();
|
||||
|
||||
quote_spanned! {
|
||||
span.into() => #ident: <#ty>::into_param(map.get(#field_name_string).map(|n| n.as_str()), #field_name_string)?
|
||||
|
||||
@@ -61,7 +61,7 @@ pub fn server_macro_impl(
|
||||
let fields = body.inputs.iter().filter(|f| !fn_arg_is_cx(f)).map(|f| {
|
||||
let typed_arg = match f {
|
||||
FnArg::Receiver(_) => {
|
||||
panic!("cannot use receiver types in server function macro")
|
||||
abort!(f, "cannot use receiver types in server function macro")
|
||||
}
|
||||
FnArg::Typed(t) => t,
|
||||
};
|
||||
@@ -96,7 +96,7 @@ pub fn server_macro_impl(
|
||||
let fn_args = body.inputs.iter().map(|f| {
|
||||
let typed_arg = match f {
|
||||
FnArg::Receiver(_) => {
|
||||
panic!("cannot use receiver types in server function macro")
|
||||
abort!(f, "cannot use receiver types in server function macro")
|
||||
}
|
||||
FnArg::Typed(t) => t,
|
||||
};
|
||||
@@ -131,22 +131,21 @@ pub fn server_macro_impl(
|
||||
let output_arrow = body.output_arrow;
|
||||
let return_ty = body.return_ty;
|
||||
|
||||
let output_ty = if let syn::Type::Path(pat) = &return_ty {
|
||||
if pat.path.segments[0].ident == "Result" {
|
||||
if let PathArguments::AngleBracketed(args) =
|
||||
&pat.path.segments[0].arguments
|
||||
{
|
||||
&args.args[0]
|
||||
} else {
|
||||
panic!(
|
||||
"server functions should return Result<T, ServerFnError>"
|
||||
);
|
||||
let output_ty = 'output_ty: {
|
||||
if let syn::Type::Path(pat) = &return_ty {
|
||||
if pat.path.segments[0].ident == "Result" {
|
||||
if let PathArguments::AngleBracketed(args) =
|
||||
&pat.path.segments[0].arguments
|
||||
{
|
||||
break 'output_ty &args.args[0];
|
||||
}
|
||||
}
|
||||
} else {
|
||||
panic!("server functions should return Result<T, ServerFnError>");
|
||||
}
|
||||
} else {
|
||||
panic!("server functions should return Result<T, ServerFnError>");
|
||||
|
||||
abort!(
|
||||
return_ty,
|
||||
"server functions should return Result<T, ServerFnError>"
|
||||
);
|
||||
};
|
||||
|
||||
Ok(quote::quote! {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::is_component_node;
|
||||
use crate::{attribute_value, is_component_node};
|
||||
use proc_macro2::{Ident, Span, TokenStream};
|
||||
use quote::{quote, quote_spanned};
|
||||
use syn::spanned::Spanned;
|
||||
@@ -11,21 +11,11 @@ pub(crate) fn render_template(cx: &Ident, nodes: &[Node]) -> TokenStream {
|
||||
Span::call_site(),
|
||||
);
|
||||
|
||||
if nodes.len() == 1 {
|
||||
first_node_to_tokens(cx, &template_uid, &nodes[0])
|
||||
} else {
|
||||
panic!("template! takes a single root element.")
|
||||
}
|
||||
}
|
||||
|
||||
fn first_node_to_tokens(
|
||||
cx: &Ident,
|
||||
template_uid: &Ident,
|
||||
node: &Node,
|
||||
) -> TokenStream {
|
||||
match node {
|
||||
Node::Element(node) => root_element_to_tokens(cx, template_uid, node),
|
||||
_ => panic!("template! takes a single root element."),
|
||||
match nodes.first() {
|
||||
Some(Node::Element(node)) => {
|
||||
root_element_to_tokens(cx, &template_uid, node)
|
||||
}
|
||||
_ => abort!(cx, "template! takes a single root element."),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -205,7 +195,11 @@ fn element_to_tokens(
|
||||
let mut prev_sib = prev_sib;
|
||||
for (idx, child) in node.children.iter().enumerate() {
|
||||
// set next sib (for any insertions)
|
||||
let next_sib = next_sibling_node(&node.children, idx + 1, next_el_id);
|
||||
let next_sib =
|
||||
match next_sibling_node(&node.children, idx + 1, next_el_id) {
|
||||
Ok(next_sib) => next_sib,
|
||||
Err(err) => abort!(span, "{}", err),
|
||||
};
|
||||
|
||||
let curr_id = child_to_tokens(
|
||||
cx,
|
||||
@@ -239,9 +233,9 @@ fn next_sibling_node(
|
||||
children: &[Node],
|
||||
idx: usize,
|
||||
next_el_id: &mut usize,
|
||||
) -> Option<Ident> {
|
||||
) -> Result<Option<Ident>, String> {
|
||||
if children.len() <= idx {
|
||||
None
|
||||
Ok(None)
|
||||
} else {
|
||||
let sibling = &children[idx];
|
||||
|
||||
@@ -250,16 +244,16 @@ fn next_sibling_node(
|
||||
if is_component_node(sibling) {
|
||||
next_sibling_node(children, idx + 1, next_el_id)
|
||||
} else {
|
||||
Some(child_ident(*next_el_id + 1, sibling.name.span()))
|
||||
Ok(Some(child_ident(*next_el_id + 1, sibling.name.span())))
|
||||
}
|
||||
}
|
||||
Node::Block(sibling) => {
|
||||
Some(child_ident(*next_el_id + 1, sibling.value.span()))
|
||||
Ok(Some(child_ident(*next_el_id + 1, sibling.value.span())))
|
||||
}
|
||||
Node::Text(sibling) => {
|
||||
Some(child_ident(*next_el_id + 1, sibling.value.span()))
|
||||
Ok(Some(child_ident(*next_el_id + 1, sibling.value.span())))
|
||||
}
|
||||
_ => panic!("expected either an element or a block"),
|
||||
_ => Err("expected either an element or a block".to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -272,16 +266,9 @@ fn attr_to_tokens(
|
||||
expressions: &mut Vec<TokenStream>,
|
||||
) {
|
||||
let name = node.key.to_string();
|
||||
let name = if name.starts_with('_') {
|
||||
name.replacen('_', "", 1)
|
||||
} else {
|
||||
name
|
||||
};
|
||||
let name = if name.starts_with("attr:") {
|
||||
name.replacen("attr:", "", 1)
|
||||
} else {
|
||||
name
|
||||
};
|
||||
let name = name.strip_prefix("_").unwrap_or(&name);
|
||||
let name = name.strip_prefix("attr:").unwrap_or(&name);
|
||||
|
||||
let value = match &node.value {
|
||||
Some(expr) => match expr.as_ref() {
|
||||
syn::Expr::Lit(expr_lit) => {
|
||||
@@ -300,7 +287,7 @@ fn attr_to_tokens(
|
||||
|
||||
// refs
|
||||
if name == "ref" {
|
||||
panic!("node_ref not yet supported in template! macro")
|
||||
abort!(span, "node_ref not yet supported in template! macro")
|
||||
}
|
||||
// Event Handlers
|
||||
else if name.starts_with("on:") {
|
||||
@@ -311,28 +298,20 @@ fn attr_to_tokens(
|
||||
})
|
||||
}
|
||||
// Properties
|
||||
else if name.starts_with("prop:") {
|
||||
let name = name.replacen("prop:", "", 1);
|
||||
let value = node
|
||||
.value
|
||||
.as_ref()
|
||||
.expect("prop: blocks need values")
|
||||
.as_ref();
|
||||
else if let Some(name) = name.strip_prefix("prop:") {
|
||||
let value = attribute_value(&node);
|
||||
|
||||
expressions.push(quote_spanned! {
|
||||
span => leptos_dom::property(#cx, #el_id.unchecked_ref(), #name, #value.into_property(#cx))
|
||||
});
|
||||
span => leptos_dom::property(#cx, #el_id.unchecked_ref(), #name, #value.into_property(#cx))
|
||||
});
|
||||
}
|
||||
// Classes
|
||||
else if name.starts_with("class:") {
|
||||
let name = name.replacen("class:", "", 1);
|
||||
let value = node
|
||||
.value
|
||||
.as_ref()
|
||||
.expect("class: attributes need values")
|
||||
.as_ref();
|
||||
else if let Some(name) = name.strip_prefix("class:") {
|
||||
let value = attribute_value(&node);
|
||||
|
||||
expressions.push(quote_spanned! {
|
||||
span => leptos::leptos_dom::class_helper(#el_id.unchecked_ref(), #name.into(), #value.into_class(#cx))
|
||||
});
|
||||
span => leptos::leptos_dom::class_helper(#el_id.unchecked_ref(), #name.into(), #value.into_class(#cx))
|
||||
});
|
||||
}
|
||||
// Attributes
|
||||
else {
|
||||
@@ -429,7 +408,7 @@ fn child_to_tokens(
|
||||
expressions,
|
||||
navigations,
|
||||
),
|
||||
_ => panic!("unexpected child node type"),
|
||||
_ => abort!(cx, "unexpected child node type"),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::{is_component_node, Mode};
|
||||
use crate::{attribute_value, is_component_node, Mode};
|
||||
use proc_macro2::{Ident, Span, TokenStream, TokenTree};
|
||||
use quote::{format_ident, quote, quote_spanned};
|
||||
use syn::{spanned::Spanned, Expr, ExprLit, ExprPath, Lit};
|
||||
@@ -576,11 +576,7 @@ fn set_class_attribute_ssr(
|
||||
} else {
|
||||
name
|
||||
};
|
||||
let value = node
|
||||
.value
|
||||
.as_ref()
|
||||
.expect("class: attributes need values")
|
||||
.as_ref();
|
||||
let value = attribute_value(node);
|
||||
let span = node.key.span();
|
||||
Some((span, name, value))
|
||||
} else {
|
||||
@@ -802,23 +798,14 @@ 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" {
|
||||
let value = node
|
||||
.value
|
||||
.as_ref()
|
||||
.and_then(|expr| expr_to_ident(expr))
|
||||
.expect("'_ref' needs to be passed a variable name");
|
||||
let value = expr_to_ident(attribute_value(node));
|
||||
let node_ref = quote_spanned! { span => node_ref };
|
||||
|
||||
quote! {
|
||||
.#node_ref(#value)
|
||||
}
|
||||
} else if let Some(name) = name.strip_prefix("on:") {
|
||||
let handler = node
|
||||
.value
|
||||
.as_ref()
|
||||
.expect("event listener attributes need a value")
|
||||
.as_ref();
|
||||
|
||||
let handler = attribute_value(node);
|
||||
let (name, is_force_undelegated) = parse_event(name);
|
||||
|
||||
let event_type = TYPED_EVENTS
|
||||
@@ -827,9 +814,10 @@ fn attribute_to_tokens(cx: &Ident, node: &NodeAttribute) -> TokenStream {
|
||||
.copied()
|
||||
.unwrap_or("Custom");
|
||||
let is_custom = event_type == "Custom";
|
||||
let event_type = event_type
|
||||
.parse::<TokenStream>()
|
||||
.expect("couldn't parse event name");
|
||||
|
||||
let Ok(event_type) = event_type.parse::<TokenStream>() else {
|
||||
abort!(event_type, "couldn't parse event name");
|
||||
};
|
||||
|
||||
let event_type = if is_custom {
|
||||
quote! { leptos::ev::Custom::new(#name) }
|
||||
@@ -896,11 +884,7 @@ fn attribute_to_tokens(cx: &Ident, node: &NodeAttribute) -> TokenStream {
|
||||
#on(#event_type, #handler)
|
||||
}
|
||||
} else if let Some(name) = name.strip_prefix("prop:") {
|
||||
let value = node
|
||||
.value
|
||||
.as_ref()
|
||||
.expect("prop: attributes need a value")
|
||||
.as_ref();
|
||||
let value = attribute_value(node);
|
||||
let prop = match &node.key {
|
||||
NodeName::Punctuated(parts) => &parts[0],
|
||||
_ => unreachable!(),
|
||||
@@ -915,11 +899,7 @@ fn attribute_to_tokens(cx: &Ident, node: &NodeAttribute) -> TokenStream {
|
||||
#prop(#name, (#cx, #[allow(unused_braces)] #value))
|
||||
}
|
||||
} else if let Some(name) = name.strip_prefix("class:") {
|
||||
let value = node
|
||||
.value
|
||||
.as_ref()
|
||||
.expect("class: attributes need a value")
|
||||
.as_ref();
|
||||
let value = attribute_value(node);
|
||||
let class = match &node.key {
|
||||
NodeName::Punctuated(parts) => &parts[0],
|
||||
_ => unreachable!(),
|
||||
@@ -1012,16 +992,11 @@ pub(crate) fn component_to_tokens(
|
||||
|
||||
let items_to_clone = attrs
|
||||
.clone()
|
||||
.filter(|attr| attr.key.to_string().starts_with("clone:"))
|
||||
.map(|attr| {
|
||||
let ident = attr
|
||||
.key
|
||||
.filter_map(|attr| {
|
||||
attr.key
|
||||
.to_string()
|
||||
.strip_prefix("clone:")
|
||||
.unwrap()
|
||||
.to_owned();
|
||||
|
||||
format_ident!("{ident}", span = attr.key.span())
|
||||
.map(|ident| format_ident!("{ident}", span = attr.key.span()))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
@@ -1085,14 +1060,14 @@ pub(crate) fn event_from_attribute_node(
|
||||
attr: &NodeAttribute,
|
||||
force_undelegated: bool,
|
||||
) -> (TokenStream, &Expr) {
|
||||
let event_name =
|
||||
attr.key.to_string().strip_prefix("on:").unwrap().to_owned();
|
||||
let event_name = attr
|
||||
.key
|
||||
.to_string()
|
||||
.strip_prefix("on:")
|
||||
.expect("expected `on:` directive")
|
||||
.to_owned();
|
||||
|
||||
let handler = attr
|
||||
.value
|
||||
.as_ref()
|
||||
.expect("event listener attributes need a value")
|
||||
.as_ref();
|
||||
let handler = attribute_value(attr);
|
||||
|
||||
#[allow(unused_variables)]
|
||||
let (name, name_undelegated) = parse_event(&event_name);
|
||||
@@ -1102,9 +1077,10 @@ pub(crate) fn event_from_attribute_node(
|
||||
.find(|e| **e == name)
|
||||
.copied()
|
||||
.unwrap_or("Custom");
|
||||
let event_type = event_type
|
||||
.parse::<TokenStream>()
|
||||
.expect("couldn't parse event name");
|
||||
|
||||
let Ok(event_type) = event_type.parse::<TokenStream>() else {
|
||||
abort!(attr.key, "couldn't parse event name");
|
||||
};
|
||||
|
||||
let event_type = if force_undelegated || name_undelegated {
|
||||
quote! { ::leptos::leptos_dom::ev::undelegated(::leptos::leptos_dom::ev::#event_type) }
|
||||
|
||||
@@ -130,6 +130,7 @@ where
|
||||
resolved: Rc::new(Cell::new(resolved)),
|
||||
scheduled: Rc::new(Cell::new(false)),
|
||||
suspense_contexts: Default::default(),
|
||||
serializable: true,
|
||||
});
|
||||
|
||||
let id = with_runtime(cx.runtime, |runtime| {
|
||||
@@ -253,6 +254,7 @@ where
|
||||
resolved: Rc::new(Cell::new(resolved)),
|
||||
scheduled: Rc::new(Cell::new(false)),
|
||||
suspense_contexts: Default::default(),
|
||||
serializable: false,
|
||||
});
|
||||
|
||||
let id = with_runtime(cx.runtime, |runtime| {
|
||||
@@ -548,6 +550,7 @@ where
|
||||
resolved: Rc<Cell<bool>>,
|
||||
scheduled: Rc<Cell<bool>>,
|
||||
suspense_contexts: Rc<RefCell<HashSet<SuspenseContext>>>,
|
||||
serializable: bool,
|
||||
}
|
||||
|
||||
impl<S, T> ResourceState<S, T>
|
||||
@@ -574,6 +577,13 @@ where
|
||||
let suspense_contexts = self.suspense_contexts.clone();
|
||||
let has_value = v.is_some();
|
||||
|
||||
let serializable = self.serializable;
|
||||
if let Some(suspense_cx) = &suspense_cx {
|
||||
if serializable {
|
||||
suspense_cx.has_local_only.set_value(false);
|
||||
}
|
||||
}
|
||||
|
||||
let increment = move |_: Option<()>| {
|
||||
if let Some(s) = &suspense_cx {
|
||||
if let Ok(ref mut contexts) = suspense_contexts.try_borrow_mut()
|
||||
@@ -585,7 +595,7 @@ where
|
||||
// because the context has been tracked here
|
||||
// on the first read, resource is already loading without having incremented
|
||||
if !has_value {
|
||||
s.increment();
|
||||
s.increment(serializable);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -626,10 +636,11 @@ where
|
||||
let suspense_contexts = self.suspense_contexts.clone();
|
||||
|
||||
for suspense_context in suspense_contexts.borrow().iter() {
|
||||
suspense_context.increment();
|
||||
suspense_context.increment(self.serializable);
|
||||
}
|
||||
|
||||
// run the Future
|
||||
let serializable = self.serializable;
|
||||
spawn_local({
|
||||
let resolved = self.resolved.clone();
|
||||
let set_value = self.set_value;
|
||||
@@ -643,7 +654,7 @@ where
|
||||
set_loading.update(|n| *n = false);
|
||||
|
||||
for suspense_context in suspense_contexts.borrow().iter() {
|
||||
suspense_context.decrement();
|
||||
suspense_context.decrement(serializable);
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
@@ -381,8 +381,11 @@ impl Scope {
|
||||
let (tx2, mut rx2) = futures::channel::mpsc::unbounded();
|
||||
|
||||
create_isomorphic_effect(*self, move |_| {
|
||||
let pending =
|
||||
context.pending_resources.try_with(|n| *n).unwrap_or(0);
|
||||
let pending = context
|
||||
.pending_serializable_resources
|
||||
.read_only()
|
||||
.try_with(|n| *n)
|
||||
.unwrap_or(0);
|
||||
if pending == 0 {
|
||||
_ = tx1.unbounded_send(());
|
||||
_ = tx2.unbounded_send(());
|
||||
@@ -415,9 +418,7 @@ impl Scope {
|
||||
{
|
||||
with_runtime(self.runtime, |runtime| {
|
||||
let mut shared_context = runtime.shared_context.borrow_mut();
|
||||
let f = std::mem::take(&mut shared_context.pending_fragments);
|
||||
println!("pending_fragments = {}", f.len());
|
||||
f
|
||||
std::mem::take(&mut shared_context.pending_fragments)
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
@@ -71,7 +71,7 @@ pub fn create_slice<T, O>(
|
||||
setter: impl Fn(&mut T, O) + Clone + Copy + 'static,
|
||||
) -> (Signal<O>, SignalSetter<O>)
|
||||
where
|
||||
O: Eq,
|
||||
O: PartialEq,
|
||||
{
|
||||
let getter = create_memo(cx, move |_| signal.with(getter));
|
||||
let setter = move |value| signal.update(|x| setter(x, value));
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
|
||||
#![forbid(unsafe_code)]
|
||||
use crate::{
|
||||
create_signal, queue_microtask, ReadSignal, Scope, SignalUpdate,
|
||||
WriteSignal,
|
||||
create_rw_signal, create_signal, queue_microtask, store_value, ReadSignal,
|
||||
RwSignal, Scope, SignalUpdate, StoredValue, WriteSignal,
|
||||
};
|
||||
use futures::Future;
|
||||
use std::{borrow::Cow, pin::Pin};
|
||||
@@ -15,6 +15,15 @@ pub struct SuspenseContext {
|
||||
/// The number of resources that are currently pending.
|
||||
pub pending_resources: ReadSignal<usize>,
|
||||
set_pending_resources: WriteSignal<usize>,
|
||||
pub(crate) pending_serializable_resources: RwSignal<usize>,
|
||||
pub(crate) has_local_only: StoredValue<bool>,
|
||||
}
|
||||
|
||||
impl SuspenseContext {
|
||||
/// Whether the suspense contains local resources at this moment, and therefore can't be
|
||||
pub fn has_local_only(&self) -> bool {
|
||||
self.has_local_only.get_value()
|
||||
}
|
||||
}
|
||||
|
||||
impl std::hash::Hash for SuspenseContext {
|
||||
@@ -35,29 +44,47 @@ impl SuspenseContext {
|
||||
/// Creates an empty suspense context.
|
||||
pub fn new(cx: Scope) -> Self {
|
||||
let (pending_resources, set_pending_resources) = create_signal(cx, 0);
|
||||
let pending_serializable_resources = create_rw_signal(cx, 0);
|
||||
let has_local_only = store_value(cx, true);
|
||||
Self {
|
||||
pending_resources,
|
||||
set_pending_resources,
|
||||
pending_serializable_resources,
|
||||
has_local_only,
|
||||
}
|
||||
}
|
||||
|
||||
/// Notifies the suspense context that a new resource is now pending.
|
||||
pub fn increment(&self) {
|
||||
pub fn increment(&self, serializable: bool) {
|
||||
let setter = self.set_pending_resources;
|
||||
let serializable_resources = self.pending_serializable_resources;
|
||||
let has_local_only = self.has_local_only;
|
||||
queue_microtask(move || {
|
||||
setter.update(|n| *n += 1);
|
||||
if serializable {
|
||||
serializable_resources.update(|n| *n += 1);
|
||||
has_local_only.set_value(false);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Notifies the suspense context that a resource has resolved.
|
||||
pub fn decrement(&self) {
|
||||
pub fn decrement(&self, serializable: bool) {
|
||||
let setter = self.set_pending_resources;
|
||||
let serializable_resources = self.pending_serializable_resources;
|
||||
queue_microtask(move || {
|
||||
setter.update(|n| {
|
||||
if *n > 0 {
|
||||
*n -= 1
|
||||
}
|
||||
});
|
||||
if serializable {
|
||||
serializable_resources.update(|n| {
|
||||
if *n > 0 {
|
||||
*n -= 1;
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "leptos_meta"
|
||||
version = "0.2.0-beta"
|
||||
version = "0.2.0"
|
||||
edition = "2021"
|
||||
authors = ["Greg Johnston"]
|
||||
license = "MIT"
|
||||
|
||||
@@ -8,18 +8,37 @@ use std::{cell::RefCell, rc::Rc};
|
||||
pub struct HtmlContext {
|
||||
lang: Rc<RefCell<Option<TextProp>>>,
|
||||
dir: Rc<RefCell<Option<TextProp>>>,
|
||||
class: Rc<RefCell<Option<TextProp>>>,
|
||||
}
|
||||
|
||||
impl HtmlContext {
|
||||
/// Converts the `<html>` metadata into an HTML string.
|
||||
pub fn as_string(&self) -> Option<String> {
|
||||
match (self.lang.borrow().as_ref(), self.dir.borrow().as_ref()) {
|
||||
(None, None) => None,
|
||||
(Some(lang), None) => Some(format!(" lang=\"{}\"", lang.get())),
|
||||
(None, Some(dir)) => Some(format!(" dir=\"{}\"", dir.get())),
|
||||
(Some(lang), Some(dir)) => {
|
||||
Some(format!(" lang=\"{}\" dir=\"{}\"", lang.get(), dir.get()))
|
||||
}
|
||||
let lang = self
|
||||
.lang
|
||||
.borrow()
|
||||
.as_ref()
|
||||
.map(|val| format!("lang=\"{}\"", val.get()));
|
||||
let dir = self
|
||||
.dir
|
||||
.borrow()
|
||||
.as_ref()
|
||||
.map(|val| format!("dir=\"{}\"", val.get()));
|
||||
let class = self
|
||||
.class
|
||||
.borrow()
|
||||
.as_ref()
|
||||
.map(|val| format!("class=\"{}\"", val.get()));
|
||||
let mut val = [lang, dir, class]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ");
|
||||
if val.is_empty() {
|
||||
None
|
||||
} else {
|
||||
val.insert(0, ' ');
|
||||
Some(val)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -57,6 +76,9 @@ pub fn Html(
|
||||
/// The `dir` attribute on the `<html>`.
|
||||
#[prop(optional, into)]
|
||||
dir: Option<TextProp>,
|
||||
/// The `class` attribute on the `<html>`.
|
||||
#[prop(optional, into)]
|
||||
class: Option<TextProp>,
|
||||
) -> impl IntoView {
|
||||
cfg_if! {
|
||||
if #[cfg(any(feature = "csr", feature = "hydrate"))] {
|
||||
@@ -71,15 +93,24 @@ pub fn Html(
|
||||
}
|
||||
|
||||
if let Some(dir) = dir {
|
||||
let el = el.clone();
|
||||
create_render_effect(cx, move |_| {
|
||||
let value = dir.get();
|
||||
_ = el.set_attribute("dir", &value);
|
||||
});
|
||||
}
|
||||
|
||||
if let Some(class) = class {
|
||||
create_render_effect(cx, move |_| {
|
||||
let value = class.get();
|
||||
_ = el.set_attribute("class", &value);
|
||||
});
|
||||
}
|
||||
} else {
|
||||
let meta = crate::use_head(cx);
|
||||
*meta.html.lang.borrow_mut() = lang;
|
||||
*meta.html.dir.borrow_mut() = dir;
|
||||
*meta.html.class.borrow_mut() = class;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -87,7 +87,7 @@ pub fn Link(
|
||||
|
||||
let builder_el = leptos::leptos_dom::html::link(cx)
|
||||
.attr("id", &id)
|
||||
.attr("as_", as_)
|
||||
.attr("as", as_)
|
||||
.attr("crossorigin", crossorigin)
|
||||
.attr("disabled", disabled.unwrap_or(false))
|
||||
.attr("fetchpriority", fetchpriority)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "leptos_router"
|
||||
version = "0.2.0-beta"
|
||||
version = "0.2.0"
|
||||
edition = "2021"
|
||||
authors = ["Greg Johnston"]
|
||||
license = "MIT"
|
||||
|
||||
@@ -11,7 +11,7 @@ use std::rc::Rc;
|
||||
/// an absolute path, prefix it with `/`).
|
||||
///
|
||||
/// **Note**: Support for server-side redirects is provided by the server framework
|
||||
/// integrations (`leptos_actix` and `leptos_axum`). If you’re not using one of those
|
||||
/// integrations (`leptos_actix`, `leptos_axum`, and `leptos_viz`). If you’re not using one of those
|
||||
/// integrations, you should manually provide a way of redirecting on the server
|
||||
/// using [provide_server_redirect].
|
||||
#[component]
|
||||
|
||||
@@ -7,7 +7,7 @@ use std::{cell::RefCell, rc::Rc};
|
||||
pub struct PossibleBranchContext(pub(crate) Rc<RefCell<Vec<Branch>>>);
|
||||
|
||||
/// Generates a list of all routes this application could possibly serve. This returns the raw routes in the leptos_router
|
||||
/// format. Odds are you want `generate_route_list()` from either the actix or axum integrations if you want
|
||||
/// format. Odds are you want `generate_route_list()` from either the actix, axum, or viz integrations if you want
|
||||
/// to work with their router
|
||||
pub fn generate_route_list_inner<IV>(
|
||||
app_fn: impl FnOnce(Scope) -> IV + 'static,
|
||||
|
||||
Reference in New Issue
Block a user