mirror of
https://github.com/leptos-rs/leptos.git
synced 2025-12-28 10:11:56 -05:00
Compare commits
3 Commits
new-exampl
...
keys
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2aa14e5e65 | ||
|
|
40f6ed9252 | ||
|
|
9d9ed45565 |
28
.github/workflows/check-examples.yml
vendored
28
.github/workflows/check-examples.yml
vendored
@@ -14,7 +14,6 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
matrix: ${{ steps.set-matrix.outputs.matrix }}
|
||||
source_changed: ${{ steps.set-source-changed.outputs.source_changed }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v3
|
||||
@@ -35,36 +34,9 @@ jobs:
|
||||
echo "Example Directories: $examples"
|
||||
echo "matrix={\"directory\":$examples}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Get source files that changed
|
||||
id: changed-source
|
||||
uses: tj-actions/changed-files@v36
|
||||
with:
|
||||
files: |
|
||||
integrations
|
||||
leptos
|
||||
leptos_config
|
||||
leptos_dom
|
||||
leptos_hot_reload
|
||||
leptos_macro
|
||||
leptos_reactive
|
||||
leptos_server
|
||||
meta
|
||||
router
|
||||
server_fn
|
||||
server_fn_macro
|
||||
|
||||
- name: List source files that changed
|
||||
run: echo '${{ steps.changed-source.outputs.all_changed_files }}'
|
||||
|
||||
- name: Set source_changed
|
||||
id: set-source-changed
|
||||
run: |
|
||||
echo "source_changed=${{ steps.changed-source.outputs.any_changed }}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
matrix-job:
|
||||
name: Check
|
||||
needs: [setup]
|
||||
if: needs.setup.outputs.source_changed == 'true'
|
||||
strategy:
|
||||
matrix: ${{ fromJSON(needs.setup.outputs.matrix) }}
|
||||
fail-fast: false
|
||||
|
||||
37
.github/workflows/ci.yml
vendored
37
.github/workflows/ci.yml
vendored
@@ -9,45 +9,8 @@ on:
|
||||
- main
|
||||
|
||||
jobs:
|
||||
setup:
|
||||
name: Detect Changes
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
source_changed: ${{ steps.set-source-changed.outputs.source_changed }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v3
|
||||
|
||||
- name: Get source files that changed
|
||||
id: changed-source
|
||||
uses: tj-actions/changed-files@v36
|
||||
with:
|
||||
files: |
|
||||
integrations
|
||||
leptos
|
||||
leptos_config
|
||||
leptos_dom
|
||||
leptos_hot_reload
|
||||
leptos_macro
|
||||
leptos_reactive
|
||||
leptos_server
|
||||
meta
|
||||
router
|
||||
server_fn
|
||||
server_fn_macro
|
||||
|
||||
- name: List source files that changed
|
||||
run: echo '${{ steps.changed-source.outputs.all_changed_files }}'
|
||||
|
||||
- name: Set source_changed
|
||||
id: set-source-changed
|
||||
run: |
|
||||
echo "source_changed=${{ steps.changed-source.outputs.any_changed }}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
matrix-job:
|
||||
name: CI
|
||||
needs: [setup]
|
||||
if: needs.setup.outputs.source_changed == 'true'
|
||||
strategy:
|
||||
matrix:
|
||||
directory:
|
||||
|
||||
@@ -220,8 +220,8 @@ for reference: they include large amounts of manual SSR route handling, etc.
|
||||
## `cargo-leptos` helpers
|
||||
|
||||
`leptos_config` and `leptos_hot_reload` exist to support two different features
|
||||
of `cargo-leptos`, namely its configuration and its view-patching/hot-reloading
|
||||
features.
|
||||
of `cargo-leptos`, namely its configuration and its view-patching/hot-
|
||||
reloading features.
|
||||
|
||||
It’s important to say that the main feature `cargo-leptos` remains its ability
|
||||
to conveniently tie together different build tooling, compiling your app to
|
||||
|
||||
@@ -70,25 +70,6 @@ are a few guidelines that will make it a better experience for everyone:
|
||||
`cargo-make` and using `cargo make check && cargo make test && cargo make
|
||||
check-examples`.
|
||||
|
||||
## Before Submitting a PR
|
||||
|
||||
We have a fairly extensive CI setup that runs both lints (like `rustfmt` and `clippy`)
|
||||
and tests on PRs. You can run most of these locally if you have `cargo-make` installed.
|
||||
|
||||
If you added an example, make sure to add it to the list in `examples/Makefile.toml`.
|
||||
|
||||
From the root directory of the repo, run
|
||||
- `cargo +nightly fmt`
|
||||
- `cargo +nightly make check`
|
||||
- `cargo +nightly make test`
|
||||
- `cargo +nightly make check-examples`
|
||||
- `cargo +nightly make --profile=github-actions ci`
|
||||
|
||||
If you modified an example:
|
||||
- `cd examples/your_example`
|
||||
- `cargo +nightly fmt -- --config-path ../..`
|
||||
- `cargo +nightly make --profile=github-actions verify-flow`
|
||||
|
||||
## Architecture
|
||||
|
||||
See [ARCHITECTURE.md](./ARCHITECTURE.md).
|
||||
|
||||
28
Cargo.toml
28
Cargo.toml
@@ -26,22 +26,22 @@ members = [
|
||||
exclude = ["benchmarks", "examples"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.4.5"
|
||||
version = "0.4.3"
|
||||
|
||||
[workspace.dependencies]
|
||||
leptos = { path = "./leptos", version = "0.4.5" }
|
||||
leptos_dom = { path = "./leptos_dom", version = "0.4.5" }
|
||||
leptos_hot_reload = { path = "./leptos_hot_reload", version = "0.4.5" }
|
||||
leptos_macro = { path = "./leptos_macro", version = "0.4.5" }
|
||||
leptos_reactive = { path = "./leptos_reactive", version = "0.4.5" }
|
||||
leptos_server = { path = "./leptos_server", version = "0.4.5" }
|
||||
server_fn = { path = "./server_fn", version = "0.4.5" }
|
||||
server_fn_macro = { path = "./server_fn_macro", version = "0.4.5" }
|
||||
server_fn_macro_default = { path = "./server_fn/server_fn_macro_default", version = "0.4.5" }
|
||||
leptos_config = { path = "./leptos_config", version = "0.4.5" }
|
||||
leptos_router = { path = "./router", version = "0.4.5" }
|
||||
leptos_meta = { path = "./meta", version = "0.4.5" }
|
||||
leptos_integration_utils = { path = "./integrations/utils", version = "0.4.5" }
|
||||
leptos = { path = "./leptos", version = "0.4.3" }
|
||||
leptos_dom = { path = "./leptos_dom", version = "0.4.3" }
|
||||
leptos_hot_reload = { path = "./leptos_hot_reload", version = "0.4.3" }
|
||||
leptos_macro = { path = "./leptos_macro", version = "0.4.3" }
|
||||
leptos_reactive = { path = "./leptos_reactive", version = "0.4.3" }
|
||||
leptos_server = { path = "./leptos_server", version = "0.4.3" }
|
||||
server_fn = { path = "./server_fn", version = "0.4.3" }
|
||||
server_fn_macro = { path = "./server_fn_macro", version = "0.4.3" }
|
||||
server_fn_macro_default = { path = "./server_fn/server_fn_macro_default", version = "0.4.3" }
|
||||
leptos_config = { path = "./leptos_config", version = "0.4.3" }
|
||||
leptos_router = { path = "./router", version = "0.4.3" }
|
||||
leptos_meta = { path = "./meta", version = "0.4.3" }
|
||||
leptos_integration_utils = { path = "./integrations/utils", version = "0.4.3" }
|
||||
|
||||
[profile.release]
|
||||
codegen-units = 1
|
||||
|
||||
@@ -107,7 +107,7 @@ Open browser to [http://localhost:3000/](http://localhost:3000/).
|
||||
|
||||
### What’s up with the name?
|
||||
|
||||
_Leptos_ (λεπτός) is an ancient Greek word meaning “thin, light, refined, fine-grained.” To me, a classicist and not a dog owner, it evokes the lightweight reactive system that powers the framework. I've since learned the same word is at the root of the medical term “leptospirosis,” a blood infection that affects humans and animals... My bad. No dogs were harmed in the creation of this framework.
|
||||
_Leptos_ (λεπτός) is an ancient Greek word meaning “thin, light, refine, fine-grained.” To me, a classicist and not a dog owner, it evokes the lightweight reactive system that powers the framework. I've since learned the same word is at the root of the medical term “leptospirosis,” a blood infection that affects humans and animals... My bad. No dogs were harmed in the creation of this framework.
|
||||
|
||||
### Is it production ready?
|
||||
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
[tasks.lint]
|
||||
dependencies = ["check-format-flow", "clippy-each-feature"]
|
||||
[tasks.pre-clippy]
|
||||
env = { CARGO_MAKE_CLIPPY_ARGS = "--all-targets --all-features -- -D warnings" }
|
||||
|
||||
[tasks.check-style]
|
||||
dependencies = ["check-format-flow", "clippy-flow"]
|
||||
|
||||
[tasks.check-format]
|
||||
env = { LEPTOS_PROJECT_DIRECTORY = "../" }
|
||||
args = ["fmt", "--", "--check", "--config-path", "${LEPTOS_PROJECT_DIRECTORY}"]
|
||||
|
||||
[tasks.clippy-each-feature]
|
||||
dependencies = ["install-clippy"]
|
||||
command = "cargo"
|
||||
args = ["hack", "clippy", "--all", "--each-feature", "--no-dev-deps"]
|
||||
|
||||
@@ -13,3 +13,6 @@ RUSTFLAGS = "-D warnings"
|
||||
|
||||
[tasks.ci]
|
||||
dependencies = ["lint", "test"]
|
||||
|
||||
[tasks.lint]
|
||||
dependencies = ["check-format-flow"]
|
||||
|
||||
@@ -136,7 +136,7 @@ view! { cx,
|
||||
|
||||
In this example, clicking the button will cause the text inside `<p>` to be updated, cloning `state.name` again! Because signals are the atomic unit of reactivity, updating any field of the signal triggers updates to everything that depends on the signal.
|
||||
|
||||
There’s a better way. You can take fine-grained, reactive slices by using [`create_memo`](https://docs.rs/leptos/latest/leptos/fn.create_memo.html) or [`create_slice`](https://docs.rs/leptos/latest/leptos/fn.create_slice.html) (which uses `create_memo` but also provides a setter). “Memoizing” a value means creating a new reactive value which will only update when it changes. “Memoizing a slice” means creating a new reactive value which will only update when some field of the state struct updates.
|
||||
There’s a better way. You can use take fine-grained, reactive slices by using [`create_memo`](https://docs.rs/leptos/latest/leptos/fn.create_memo.html) or [`create_slice`](https://docs.rs/leptos/latest/leptos/fn.create_slice.html) (which uses `create_memo` but also provides a setter). “Memoizing” a value means creating a new reactive value which will only update when it changes. “Memoizing a slice” means creating a new reactive value which will only update when some field of the state struct updates.
|
||||
|
||||
Here, instead of reading from the state signal directly, we create “slices” of that state with fine-grained updates via `create_slice`. Each slice signal only updates when the particular piece of the larger struct it accesses updates. This means you can create a single root signal, and then take independent, fine-grained slices of it in different components, each of which can update without notifying the others of changes.
|
||||
|
||||
@@ -183,222 +183,3 @@ data flow and of fine-grained reactive updates.
|
||||
[Click to open CodeSandbox.](https://codesandbox.io/p/sandbox/1-basic-component-forked-8bte19?selection=%5B%7B%22endColumn%22%3A1%2C%22endLineNumber%22%3A2%2C%22startColumn%22%3A1%2C%22startLineNumber%22%3A2%7D%5D&file=%2Fsrc%2Fmain.rs)
|
||||
|
||||
<iframe src="https://codesandbox.io/p/sandbox/1-basic-component-forked-8bte19?selection=%5B%7B%22endColumn%22%3A1%2C%22endLineNumber%22%3A2%2C%22startColumn%22%3A1%2C%22startLineNumber%22%3A2%7D%5D&file=%2Fsrc%2Fmain.rs" width="100%" height="1000px" style="max-height: 100vh"></iframe>
|
||||
|
||||
<details>
|
||||
<summary>CodeSandbox Source</summary>
|
||||
|
||||
```rust
|
||||
use leptos::*;
|
||||
|
||||
// So far, we've only been working with local state in components
|
||||
// We've only seen how to communicate between parent and child components
|
||||
// But there are also more general ways to manage global state
|
||||
//
|
||||
// The three best approaches to global state are
|
||||
// 1. Using the router to drive global state via the URL
|
||||
// 2. Passing signals through context
|
||||
// 3. Creating a global state struct and creating lenses into it with `create_slice`
|
||||
//
|
||||
// Option #1: URL as Global State
|
||||
// The next few sections of the tutorial will be about the router.
|
||||
// So for now, we'll just look at options #2 and #3.
|
||||
|
||||
// Option #2: Pass Signals through Context
|
||||
//
|
||||
// In virtual DOM libraries like React, using the Context API to manage global
|
||||
// state is a bad idea: because the entire app exists in a tree, changing
|
||||
// some value provided high up in the tree can cause the whole app to render.
|
||||
//
|
||||
// In fine-grained reactive libraries like Leptos, this is simply not the case.
|
||||
// You can create a signal in the root of your app and pass it down to other
|
||||
// components using provide_context(). Changing it will only cause rerendering
|
||||
// in the specific places it is actually used, not the whole app.
|
||||
#[component]
|
||||
fn Option2(cx: Scope) -> impl IntoView {
|
||||
// here we create a signal in the root that can be consumed
|
||||
// anywhere in the app.
|
||||
let (count, set_count) = create_signal(cx, 0);
|
||||
// we'll pass the setter to specific components,
|
||||
// but provide the count itself to the whole app via context
|
||||
provide_context(cx, count);
|
||||
|
||||
view! { cx,
|
||||
<h1>"Option 2: Passing Signals"</h1>
|
||||
// SetterButton is allowed to modify the count
|
||||
<SetterButton set_count/>
|
||||
// These consumers can only read from it
|
||||
// But we could give them write access by passing `set_count` if we wanted
|
||||
<div style="display: flex">
|
||||
<FancyMath/>
|
||||
<ListItems/>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
|
||||
/// A button that increments our global counter.
|
||||
#[component]
|
||||
fn SetterButton(cx: Scope, set_count: WriteSignal<u32>) -> impl IntoView {
|
||||
view! { cx,
|
||||
<div class="provider red">
|
||||
<button on:click=move |_| set_count.update(|count| *count += 1)>
|
||||
"Increment Global Count"
|
||||
</button>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
|
||||
/// A component that does some "fancy" math with the global count
|
||||
#[component]
|
||||
fn FancyMath(cx: Scope) -> impl IntoView {
|
||||
// here we consume the global count signal with `use_context`
|
||||
let count = use_context::<ReadSignal<u32>>(cx)
|
||||
// we know we just provided this in the parent component
|
||||
.expect("there to be a `count` signal provided");
|
||||
let is_even = move || count() & 1 == 0;
|
||||
|
||||
view! { cx,
|
||||
<div class="consumer blue">
|
||||
"The number "
|
||||
<strong>{count}</strong>
|
||||
{move || if is_even() {
|
||||
" is"
|
||||
} else {
|
||||
" is not"
|
||||
}}
|
||||
" even."
|
||||
</div>
|
||||
}
|
||||
}
|
||||
|
||||
/// A component that shows a list of items generated from the global count.
|
||||
#[component]
|
||||
fn ListItems(cx: Scope) -> impl IntoView {
|
||||
// again, consume the global count signal with `use_context`
|
||||
let count = use_context::<ReadSignal<u32>>(cx).expect("there to be a `count` signal provided");
|
||||
|
||||
let squares = move || {
|
||||
(0..count())
|
||||
.map(|n| view! { cx, <li>{n}<sup>"2"</sup> " is " {n * n}</li> })
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
|
||||
view! { cx,
|
||||
<div class="consumer green">
|
||||
<ul>{squares}</ul>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
|
||||
// Option #3: Create a Global State Struct
|
||||
//
|
||||
// You can use this approach to build a single global data structure
|
||||
// that holds the state for your whole app, and then access it by
|
||||
// taking fine-grained slices using `create_slice` or `create_memo`,
|
||||
// so that changing one part of the state doesn't cause parts of your
|
||||
// app that depend on other parts of the state to change.
|
||||
|
||||
#[derive(Default, Clone, Debug)]
|
||||
struct GlobalState {
|
||||
count: u32,
|
||||
name: String,
|
||||
}
|
||||
|
||||
#[component]
|
||||
fn Option3(cx: Scope) -> impl IntoView {
|
||||
// we'll provide a single signal that holds the whole state
|
||||
// each component will be responsible for creating its own "lens" into it
|
||||
let state = create_rw_signal(cx, GlobalState::default());
|
||||
provide_context(cx, state);
|
||||
|
||||
view! { cx,
|
||||
<h1>"Option 3: Passing Signals"</h1>
|
||||
<div class="red consumer" style="width: 100%">
|
||||
<h2>"Current Global State"</h2>
|
||||
<pre>
|
||||
{move || {
|
||||
format!("{:#?}", state.get())
|
||||
}}
|
||||
</pre>
|
||||
</div>
|
||||
<div style="display: flex">
|
||||
<GlobalStateCounter/>
|
||||
<GlobalStateInput/>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
|
||||
/// A component that updates the count in the global state.
|
||||
#[component]
|
||||
fn GlobalStateCounter(cx: Scope) -> impl IntoView {
|
||||
let state = use_context::<RwSignal<GlobalState>>(cx).expect("state to have been provided");
|
||||
|
||||
// `create_slice` lets us create a "lens" into the data
|
||||
let (count, set_count) = create_slice(
|
||||
cx,
|
||||
// we take a slice *from* `state`
|
||||
state,
|
||||
// our getter returns a "slice" of the data
|
||||
|state| state.count,
|
||||
// our setter describes how to mutate that slice, given a new value
|
||||
|state, n| state.count = n,
|
||||
);
|
||||
|
||||
view! { cx,
|
||||
<div class="consumer blue">
|
||||
<button
|
||||
on:click=move |_| {
|
||||
set_count(count() + 1);
|
||||
}
|
||||
>
|
||||
"Increment Global Count"
|
||||
</button>
|
||||
<br/>
|
||||
<span>"Count is: " {count}</span>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
|
||||
/// A component that updates the count in the global state.
|
||||
#[component]
|
||||
fn GlobalStateInput(cx: Scope) -> impl IntoView {
|
||||
let state = use_context::<RwSignal<GlobalState>>(cx).expect("state to have been provided");
|
||||
|
||||
// this slice is completely independent of the `count` slice
|
||||
// that we created in the other component
|
||||
// neither of them will cause the other to rerun
|
||||
let (name, set_name) = create_slice(
|
||||
cx,
|
||||
// we take a slice *from* `state`
|
||||
state,
|
||||
// our getter returns a "slice" of the data
|
||||
|state| state.name.clone(),
|
||||
// our setter describes how to mutate that slice, given a new value
|
||||
|state, n| state.name = n,
|
||||
);
|
||||
|
||||
view! { cx,
|
||||
<div class="consumer green">
|
||||
<input
|
||||
type="text"
|
||||
prop:value=name
|
||||
on:input=move |ev| {
|
||||
set_name(event_target_value(&ev));
|
||||
}
|
||||
/>
|
||||
<br/>
|
||||
<span>"Name is: " {name}</span>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
// This `main` function is the entry point into the app
|
||||
// It just mounts our component to the <body>
|
||||
// Because we defined it as `fn App`, we can now use it in a
|
||||
// template as <App/>
|
||||
fn main() {
|
||||
leptos::mount_to_body(|cx| view! { cx, <Option2/><Option3/> })
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</details>
|
||||
</preview>
|
||||
|
||||
@@ -53,89 +53,3 @@ Resources also provide a `refetch()` method that allows you to manually reload t
|
||||
[Click to open CodeSandbox.](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)
|
||||
|
||||
<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" style="max-height: 100vh"></iframe>
|
||||
|
||||
<details>
|
||||
<summary>CodeSandbox Source</summary>
|
||||
|
||||
```rust
|
||||
use gloo_timers::future::TimeoutFuture;
|
||||
use leptos::*;
|
||||
|
||||
// Here we define an async function
|
||||
// This could be anything: a network request, database read, etc.
|
||||
// Here, we just multiply a number by 10
|
||||
async fn load_data(value: i32) -> i32 {
|
||||
// fake a one-second delay
|
||||
TimeoutFuture::new(1_000).await;
|
||||
value * 10
|
||||
}
|
||||
|
||||
#[component]
|
||||
fn App(cx: Scope) -> impl IntoView {
|
||||
// this count is our synchronous, local state
|
||||
let (count, set_count) = create_signal(cx, 0);
|
||||
|
||||
// create_resource takes two arguments after its scope
|
||||
let async_data = create_resource(
|
||||
cx,
|
||||
// the first is the "source signal"
|
||||
count,
|
||||
// the second is the loader
|
||||
// it takes the source signal's value as its argument
|
||||
// and does some async work
|
||||
|value| async move { load_data(value).await },
|
||||
);
|
||||
// whenever the source signal changes, the loader reloads
|
||||
|
||||
// you can also create resources that only load once
|
||||
// just return the unit type () from the source signal
|
||||
// that doesn't depend on anything: we just load it once
|
||||
let stable = create_resource(cx, || (), |_| async move { load_data(1).await });
|
||||
|
||||
// we can access the resource values with .read()
|
||||
// this will reactively return None before the Future has resolved
|
||||
// and update to Some(T) when it has resolved
|
||||
let async_result = move || {
|
||||
async_data
|
||||
.read(cx)
|
||||
.map(|value| format!("Server returned {value:?}"))
|
||||
// This loading state will only show before the first load
|
||||
.unwrap_or_else(|| "Loading...".into())
|
||||
};
|
||||
|
||||
// the resource's loading() method gives us a
|
||||
// signal to indicate whether it's currently loading
|
||||
let loading = async_data.loading();
|
||||
let is_loading = move || if loading() { "Loading..." } else { "Idle." };
|
||||
|
||||
view! { cx,
|
||||
<button
|
||||
on:click=move |_| {
|
||||
set_count.update(|n| *n += 1);
|
||||
}
|
||||
>
|
||||
"Click me"
|
||||
</button>
|
||||
<p>
|
||||
<code>"stable"</code>": " {move || stable.read(cx)}
|
||||
</p>
|
||||
<p>
|
||||
<code>"count"</code>": " {count}
|
||||
</p>
|
||||
<p>
|
||||
<code>"async_value"</code>": "
|
||||
{async_result}
|
||||
<br/>
|
||||
{is_loading}
|
||||
</p>
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
leptos::mount_to_body(|cx| view! { cx, <App/> })
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</details>
|
||||
</preview>
|
||||
|
||||
@@ -72,58 +72,3 @@ This inversion of the flow of control makes it easier to add or remove individua
|
||||
[Click to open CodeSandbox.](https://codesandbox.io/p/sandbox/11-suspense-907niv?file=%2Fsrc%2Fmain.rs)
|
||||
|
||||
<iframe src="https://codesandbox.io/p/sandbox/11-suspense-907niv?file=%2Fsrc%2Fmain.rs" width="100%" height="1000px" style="max-height: 100vh"></iframe>
|
||||
|
||||
<details>
|
||||
<summary>CodeSandbox Source</summary>
|
||||
|
||||
```rust
|
||||
use gloo_timers::future::TimeoutFuture;
|
||||
use leptos::*;
|
||||
|
||||
async fn important_api_call(name: String) -> String {
|
||||
TimeoutFuture::new(1_000).await;
|
||||
name.to_ascii_uppercase()
|
||||
}
|
||||
|
||||
#[component]
|
||||
fn App(cx: Scope) -> impl IntoView {
|
||||
let (name, set_name) = create_signal(cx, "Bill".to_string());
|
||||
|
||||
// this will reload every time `name` changes
|
||||
let async_data = create_resource(
|
||||
cx,
|
||||
name,
|
||||
|name| async move { important_api_call(name).await },
|
||||
);
|
||||
|
||||
view! { cx,
|
||||
<input
|
||||
on:input=move |ev| {
|
||||
set_name(event_target_value(&ev));
|
||||
}
|
||||
prop:value=name
|
||||
/>
|
||||
<p><code>"name:"</code> {name}</p>
|
||||
<Suspense
|
||||
// the fallback will show whenever a resource
|
||||
// read "under" the suspense is loading
|
||||
fallback=move || view! { cx, <p>"Loading..."</p> }
|
||||
>
|
||||
// the children will be rendered once initially,
|
||||
// and then whenever any resources has been resolved
|
||||
<p>
|
||||
"Your shouting name is "
|
||||
{move || async_data.read(cx)}
|
||||
</p>
|
||||
</Suspense>
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
leptos::mount_to_body(|cx| view! { cx, <App/> })
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</details>
|
||||
</preview>
|
||||
|
||||
@@ -9,76 +9,3 @@ This example shows how you can create a simple tabbed contact list with `<Transi
|
||||
[Click to open CodeSandbox.](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)
|
||||
|
||||
<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" style="max-height: 100vh"></iframe>
|
||||
|
||||
<details>
|
||||
<summary>CodeSandbox Source</summary>
|
||||
|
||||
```rust
|
||||
use gloo_timers::future::TimeoutFuture;
|
||||
use leptos::*;
|
||||
|
||||
async fn important_api_call(id: usize) -> String {
|
||||
TimeoutFuture::new(1_000).await;
|
||||
match id {
|
||||
0 => "Alice",
|
||||
1 => "Bob",
|
||||
2 => "Carol",
|
||||
_ => "User not found",
|
||||
}
|
||||
.to_string()
|
||||
}
|
||||
|
||||
#[component]
|
||||
fn App(cx: Scope) -> impl IntoView {
|
||||
let (tab, set_tab) = create_signal(cx, 0);
|
||||
|
||||
// this will reload every time `tab` changes
|
||||
let user_data = create_resource(cx, tab, |tab| async move { important_api_call(tab).await });
|
||||
|
||||
view! { cx,
|
||||
<div class="buttons">
|
||||
<button
|
||||
on:click=move |_| set_tab(0)
|
||||
class:selected=move || tab() == 0
|
||||
>
|
||||
"Tab A"
|
||||
</button>
|
||||
<button
|
||||
on:click=move |_| set_tab(1)
|
||||
class:selected=move || tab() == 1
|
||||
>
|
||||
"Tab B"
|
||||
</button>
|
||||
<button
|
||||
on:click=move |_| set_tab(2)
|
||||
class:selected=move || tab() == 2
|
||||
>
|
||||
"Tab C"
|
||||
</button>
|
||||
{move || if user_data.loading().get() {
|
||||
"Loading..."
|
||||
} else {
|
||||
""
|
||||
}}
|
||||
</div>
|
||||
<Transition
|
||||
// the fallback will show initially
|
||||
// on subsequent reloads, the current child will
|
||||
// continue showing
|
||||
fallback=move || view! { cx, <p>"Loading..."</p> }
|
||||
>
|
||||
<p>
|
||||
{move || user_data.read(cx)}
|
||||
</p>
|
||||
</Transition>
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
leptos::mount_to_body(|cx| view! { cx, <App/> })
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</details>
|
||||
</preview>
|
||||
|
||||
@@ -94,83 +94,3 @@ Now, there’s a chance this all seems a little over-complicated, or maybe too r
|
||||
[Click to open CodeSandbox.](https://codesandbox.io/p/sandbox/10-async-resources-forked-hgpfp0?selection=%5B%7B%22endColumn%22%3A1%2C%22endLineNumber%22%3A4%2C%22startColumn%22%3A1%2C%22startLineNumber%22%3A4%7D%5D&file=%2Fsrc%2Fmain.rs)
|
||||
|
||||
<iframe src="https://codesandbox.io/p/sandbox/10-async-resources-forked-hgpfp0?selection=%5B%7B%22endColumn%22%3A1%2C%22endLineNumber%22%3A4%2C%22startColumn%22%3A1%2C%22startLineNumber%22%3A4%7D%5D&file=%2Fsrc%2Fmain.rs" width="100%" height="1000px" style="max-height: 100vh"></iframe>
|
||||
|
||||
<details>
|
||||
<summary>CodeSandbox Source</summary>
|
||||
|
||||
```rust
|
||||
use gloo_timers::future::TimeoutFuture;
|
||||
use leptos::{html::Input, *};
|
||||
use uuid::Uuid;
|
||||
|
||||
// Here we define an async function
|
||||
// This could be anything: a network request, database read, etc.
|
||||
// Think of it as a mutation: some imperative async action you run,
|
||||
// whereas a resource would be some async data you load
|
||||
async fn add_todo(text: &str) -> Uuid {
|
||||
_ = text;
|
||||
// fake a one-second delay
|
||||
TimeoutFuture::new(1_000).await;
|
||||
// pretend this is a post ID or something
|
||||
Uuid::new_v4()
|
||||
}
|
||||
|
||||
#[component]
|
||||
fn App(cx: Scope) -> impl IntoView {
|
||||
// an action takes an async function with single argument
|
||||
// it can be a simple type, a struct, or ()
|
||||
let add_todo = create_action(cx, |input: &String| {
|
||||
// the input is a reference, but we need the Future to own it
|
||||
// this is important: we need to clone and move into the Future
|
||||
// so it has a 'static lifetime
|
||||
let input = input.to_owned();
|
||||
async move { add_todo(&input).await }
|
||||
});
|
||||
|
||||
// actions provide a bunch of synchronous, reactive variables
|
||||
// that tell us different things about the state of the action
|
||||
let submitted = add_todo.input();
|
||||
let pending = add_todo.pending();
|
||||
let todo_id = add_todo.value();
|
||||
|
||||
let input_ref = create_node_ref::<Input>(cx);
|
||||
|
||||
view! { cx,
|
||||
<form
|
||||
on:submit=move |ev| {
|
||||
ev.prevent_default(); // don't reload the page...
|
||||
let input = input_ref.get().expect("input to exist");
|
||||
add_todo.dispatch(input.value());
|
||||
}
|
||||
>
|
||||
<label>
|
||||
"What do you need to do?"
|
||||
<input type="text"
|
||||
node_ref=input_ref
|
||||
/>
|
||||
</label>
|
||||
<button type="submit">"Add Todo"</button>
|
||||
</form>
|
||||
<p>{move || pending().then(|| "Loading...")}</p>
|
||||
<p>
|
||||
"Submitted: "
|
||||
<code>{move || format!("{:#?}", submitted())}</code>
|
||||
</p>
|
||||
<p>
|
||||
"Pending: "
|
||||
<code>{move || format!("{:#?}", pending())}</code>
|
||||
</p>
|
||||
<p>
|
||||
"Todo ID: "
|
||||
<code>{move || format!("{:#?}", todo_id())}</code>
|
||||
</p>
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
leptos::mount_to_body(|cx| view! { cx, <App/> })
|
||||
}
|
||||
```
|
||||
|
||||
</details>
|
||||
</preview>
|
||||
|
||||
@@ -112,195 +112,3 @@ Every time `count` is updated, this effect wil rerun. This is what allows reacti
|
||||
[Click to open CodeSandbox.](https://codesandbox.io/p/sandbox/serene-thompson-40974n?file=%2Fsrc%2Fmain.rs&selection=%5B%7B%22endColumn%22%3A1%2C%22endLineNumber%22%3A2%2C%22startColumn%22%3A1%2C%22startLineNumber%22%3A2%7D%5D)
|
||||
|
||||
<iframe src="https://codesandbox.io/p/sandbox/serene-thompson-40974n?file=%2Fsrc%2Fmain.rs&selection=%5B%7B%22endColumn%22%3A1%2C%22endLineNumber%22%3A2%2C%22startColumn%22%3A1%2C%22startLineNumber%22%3A2%7D%5D" width="100%" height="1000px" style="max-height: 100vh"></iframe>
|
||||
|
||||
<details>
|
||||
<summary>CodeSandbox Source</summary>
|
||||
|
||||
```rust
|
||||
use leptos::html::Input;
|
||||
use leptos::*;
|
||||
|
||||
#[component]
|
||||
fn App(cx: Scope) -> impl IntoView {
|
||||
// Just making a visible log here
|
||||
// You can ignore this...
|
||||
let log = create_rw_signal::<Vec<String>>(cx, vec![]);
|
||||
let logged = move || log().join("\n");
|
||||
provide_context(cx, log);
|
||||
|
||||
view! { cx,
|
||||
<CreateAnEffect/>
|
||||
<pre>{logged}</pre>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
fn CreateAnEffect(cx: Scope) -> impl IntoView {
|
||||
let (first, set_first) = create_signal(cx, String::new());
|
||||
let (last, set_last) = create_signal(cx, String::new());
|
||||
let (use_last, set_use_last) = create_signal(cx, true);
|
||||
|
||||
// this will add the name to the log
|
||||
// any time one of the source signals changes
|
||||
create_effect(cx, move |_| {
|
||||
log(
|
||||
cx,
|
||||
if use_last() {
|
||||
format!("{} {}", first(), last())
|
||||
} else {
|
||||
first()
|
||||
},
|
||||
)
|
||||
});
|
||||
|
||||
view! { cx,
|
||||
<h1><code>"create_effect"</code> " Version"</h1>
|
||||
<form>
|
||||
<label>
|
||||
"First Name"
|
||||
<input type="text" name="first" prop:value=first
|
||||
on:change=move |ev| set_first(event_target_value(&ev))
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
"Last Name"
|
||||
<input type="text" name="last" prop:value=last
|
||||
on:change=move |ev| set_last(event_target_value(&ev))
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
"Show Last Name"
|
||||
<input type="checkbox" name="use_last" prop:checked=use_last
|
||||
on:change=move |ev| set_use_last(event_target_checked(&ev))
|
||||
/>
|
||||
</label>
|
||||
</form>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
fn ManualVersion(cx: Scope) -> impl IntoView {
|
||||
let first = create_node_ref::<Input>(cx);
|
||||
let last = create_node_ref::<Input>(cx);
|
||||
let use_last = create_node_ref::<Input>(cx);
|
||||
|
||||
let mut prev_name = String::new();
|
||||
let on_change = move |_| {
|
||||
log(cx, " listener");
|
||||
let first = first.get().unwrap();
|
||||
let last = last.get().unwrap();
|
||||
let use_last = use_last.get().unwrap();
|
||||
let this_one = if use_last.checked() {
|
||||
format!("{} {}", first.value(), last.value())
|
||||
} else {
|
||||
first.value()
|
||||
};
|
||||
|
||||
if this_one != prev_name {
|
||||
log(cx, &this_one);
|
||||
prev_name = this_one;
|
||||
}
|
||||
};
|
||||
|
||||
view! { cx,
|
||||
<h1>"Manual Version"</h1>
|
||||
<form on:change=on_change>
|
||||
<label>
|
||||
"First Name"
|
||||
<input type="text" name="first"
|
||||
node_ref=first
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
"Last Name"
|
||||
<input type="text" name="last"
|
||||
node_ref=last
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
"Show Last Name"
|
||||
<input type="checkbox" name="use_last"
|
||||
checked
|
||||
node_ref=use_last
|
||||
/>
|
||||
</label>
|
||||
</form>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
fn EffectVsDerivedSignal(cx: Scope) -> impl IntoView {
|
||||
let (my_value, set_my_value) = create_signal(cx, String::new());
|
||||
// Don't do this.
|
||||
/*let (my_optional_value, set_optional_my_value) = create_signal(cx, Option::<String>::None);
|
||||
|
||||
create_effect(cx, move |_| {
|
||||
if !my_value.get().is_empty() {
|
||||
set_optional_my_value(Some(my_value.get()));
|
||||
} else {
|
||||
set_optional_my_value(None);
|
||||
}
|
||||
});*/
|
||||
|
||||
// Do this
|
||||
let my_optional_value =
|
||||
move || (!my_value.with(String::is_empty)).then(|| Some(my_value.get()));
|
||||
|
||||
view! { cx,
|
||||
<input
|
||||
prop:value=my_value
|
||||
on:input= move |ev| set_my_value(event_target_value(&ev))
|
||||
/>
|
||||
|
||||
<p>
|
||||
<code>"my_optional_value"</code>
|
||||
" is "
|
||||
<code>
|
||||
<Show
|
||||
when=move || my_optional_value().is_some()
|
||||
fallback=|cx| view! { cx, "None" }
|
||||
>
|
||||
"Some(\"" {my_optional_value().unwrap()} "\")"
|
||||
</Show>
|
||||
</code>
|
||||
</p>
|
||||
}
|
||||
}
|
||||
|
||||
/*#[component]
|
||||
pub fn Show<F, W, IV>(
|
||||
/// The scope the component is running in
|
||||
cx: Scope,
|
||||
/// The components Show wraps
|
||||
children: Box<dyn Fn(Scope) -> Fragment>,
|
||||
/// A closure that returns a bool that determines whether this thing runs
|
||||
when: W,
|
||||
/// A closure that returns what gets rendered if the when statement is false
|
||||
fallback: F,
|
||||
) -> impl IntoView
|
||||
where
|
||||
W: Fn() -> bool + 'static,
|
||||
F: Fn(Scope) -> IV + 'static,
|
||||
IV: IntoView,
|
||||
{
|
||||
let memoized_when = create_memo(cx, move |_| when());
|
||||
|
||||
move || match memoized_when.get() {
|
||||
true => children(cx).into_view(cx),
|
||||
false => fallback(cx).into_view(cx),
|
||||
}
|
||||
}*/
|
||||
|
||||
fn log(cx: Scope, msg: impl std::fmt::Display) {
|
||||
let log = use_context::<RwSignal<Vec<String>>>(cx).unwrap();
|
||||
log.update(|log| log.push(msg.to_string()));
|
||||
}
|
||||
|
||||
fn main() {
|
||||
leptos::mount_to_body(|cx| view! { cx, <App/> })
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</details>
|
||||
</preview>
|
||||
|
||||
@@ -68,7 +68,7 @@ pub fn SimpleCounter(cx: Scope) -> impl IntoView {
|
||||
|
||||
The `SimpleCounter` function itself runs once. The `value` signal is created once. The framework hands off the `increment` function to the browser as an event listener. When you click the button, the browser calls `increment`, which updates `value` via `set_value`. And that updates the single text node represented in our view by `{value}`.
|
||||
|
||||
Closures are key to reactivity. They provide the framework with the ability to rerun the smallest possible unit of your application in response to a change.
|
||||
Closures are key to reactivity. They provide the framework with the ability to rerun the smallest possible unit of your application in responsive to a change.
|
||||
|
||||
So remember two things:
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@ use leptos_router::*;
|
||||
|
||||
Routing behavior is provided by the [`<Router/>`](https://docs.rs/leptos_router/latest/leptos_router/fn.Router.html) component. This should usually be somewhere near the root of your application, the rest of the app.
|
||||
|
||||
> You shouldn’t try to use multiple `<Router/>`s in your app. Remember that the router drives global state: if you have multiple routers, which one decides what to do when the URL changes?
|
||||
> You shouldn’t try to use multiple `<Router/>`s in your app. Remember that the router drives global state: if you have multiple routers, which ones decides what to do when the URL changes?
|
||||
|
||||
Let’s start with a simple `<App/>` component using the router:
|
||||
|
||||
@@ -87,17 +87,15 @@ The `view` is a function that takes a `Scope` and returns a view.
|
||||
|
||||
```rust
|
||||
<Routes>
|
||||
<Route path="/" view=Home/>
|
||||
<Route path="/users" view=Users/>
|
||||
<Route path="/users/:id" view=UserProfile/>
|
||||
<Route path="/*any" view=NotFound/>
|
||||
<Route path="/" view=|cx| view! { cx, <Home/> }/>
|
||||
<Route path="/users" view=|cx| view! { cx, <Users/> }/>
|
||||
<Route path="/users/:id" view=|cx| view! { cx, <UserProfile/> }/>
|
||||
<Route path="/*any" view=|cx| view! { cx, <NotFound/> }/>
|
||||
</Routes>
|
||||
```
|
||||
|
||||
> `view` takes a `Fn(Scope) -> impl IntoView`. If a component has no props, it is a function that takes `Scope` and returns `impl IntoView`, so it can be passed directly into the `view`. In this case, `view=Home` is just a shorthand for `|cx| view! { cx, <Home/> }`.
|
||||
> The router scores each route to see how good a match it is, so you can define your routes in any order.
|
||||
|
||||
Now if you navigate to `/` or to `/users` you’ll get the home page or the `<Users/>`. If you go to `/users/3` or `/blahblah` you’ll get a user profile or your 404 page (`<NotFound/>`). On every navigation, the router determines which `<Route/>` should be matched, and therefore what content should be displayed where the `<Routes/>` component is defined.
|
||||
|
||||
Note that you can define your routes in any order. The router scores each route to see how good a match it is, rather than simply trying to match them top to bottom.
|
||||
|
||||
Simple enough?
|
||||
|
||||
@@ -4,10 +4,10 @@ We just defined the following set of routes:
|
||||
|
||||
```rust
|
||||
<Routes>
|
||||
<Route path="/" view=Home/>
|
||||
<Route path="/users" view=Users/>
|
||||
<Route path="/users/:id" view=UserProfile/>
|
||||
<Route path="/*any" view=NotFound/>
|
||||
<Route path="/" view=|cx| view! { cx, <Home /> }/>
|
||||
<Route path="/users" view=|cx| view! { cx, <Users /> }/>
|
||||
<Route path="/users/:id" view=|cx| view! { cx, <UserProfile /> }/>
|
||||
<Route path="/*any" view=|cx| view! { cx, <NotFound /> }/>
|
||||
</Routes>
|
||||
```
|
||||
|
||||
@@ -17,11 +17,11 @@ Well... you can!
|
||||
|
||||
```rust
|
||||
<Routes>
|
||||
<Route path="/" view=Home/>
|
||||
<Route path="/users" view=Users>
|
||||
<Route path=":id" view=UserProfile/>
|
||||
<Route path="/" view=|cx| view! { cx, <Home /> }/>
|
||||
<Route path="/users" view=|cx| view! { cx, <Users /> }>
|
||||
<Route path=":id" view=|cx| view! { cx, <UserProfile /> }/>
|
||||
</Route>
|
||||
<Route path="/*any" view=NotFound/>
|
||||
<Route path="/*any" view=|cx| view! { cx, <NotFound /> }/>
|
||||
</Routes>
|
||||
```
|
||||
|
||||
@@ -39,8 +39,8 @@ Let’s look back at our practical example.
|
||||
|
||||
```rust
|
||||
<Routes>
|
||||
<Route path="/users" view=Users/>
|
||||
<Route path="/users/:id" view=UserProfile/>
|
||||
<Route path="/users" view=|cx| view! { cx, <Users /> }/>
|
||||
<Route path="/users/:id" view=|cx| view! { cx, <UserProfile /> }/>
|
||||
</Routes>
|
||||
```
|
||||
|
||||
@@ -53,8 +53,8 @@ Let’s say I use nested routes instead:
|
||||
|
||||
```rust
|
||||
<Routes>
|
||||
<Route path="/users" view=Users>
|
||||
<Route path=":id" view=UserProfile/>
|
||||
<Route path="/users" view=|cx| view! { cx, <Users /> }>
|
||||
<Route path=":id" view=|cx| view! { cx, <UserProfile /> }/>
|
||||
</Route>
|
||||
</Routes>
|
||||
```
|
||||
@@ -68,9 +68,9 @@ I actually need to add a fallback route
|
||||
|
||||
```rust
|
||||
<Routes>
|
||||
<Route path="/users" view=Users>
|
||||
<Route path=":id" view=UserProfile/>
|
||||
<Route path="" view=NoUser/>
|
||||
<Route path="/users" view=|cx| view! { cx, <Users /> }>
|
||||
<Route path=":id" view=|cx| view! { cx, <UserProfile /> }/>
|
||||
<Route path="" view=|cx| view! { cx, <NoUser /> }/>
|
||||
</Route>
|
||||
</Routes>
|
||||
```
|
||||
@@ -94,8 +94,8 @@ You can easily define this with nested routes
|
||||
|
||||
```rust
|
||||
<Routes>
|
||||
<Route path="/contacts" view=ContactList>
|
||||
<Route path=":id" view=ContactInfo/>
|
||||
<Route path="/contacts" view=|cx| view! { cx, <ContactList/> }>
|
||||
<Route path=":id" view=|cx| view! { cx, <ContactInfo/> }/>
|
||||
<Route path="" view=|cx| view! { cx,
|
||||
<p>"Select a contact to view more info."</p>
|
||||
}/>
|
||||
@@ -107,11 +107,11 @@ You can go even deeper. Say you want to have tabs for each contact’s address,
|
||||
|
||||
```rust
|
||||
<Routes>
|
||||
<Route path="/contacts" view=ContactList>
|
||||
<Route path=":id" view=ContactInfo>
|
||||
<Route path="" view=EmailAndPhone/>
|
||||
<Route path="address" view=Address/>
|
||||
<Route path="messages" view=Messages/>
|
||||
<Route path="/contacts" view=|cx| view! { cx, <ContactList/> }>
|
||||
<Route path=":id" view=|cx| view! { cx, <ContactInfo/> }>
|
||||
<Route path="" view=|cx| view! { cx, <EmailAndPhone/> }/>
|
||||
<Route path="address" view=|cx| view! { cx, <Address/> }/>
|
||||
<Route path="messages" view=|cx| view! { cx, <Messages/> }/>
|
||||
</Route>
|
||||
<Route path="" view=|cx| view! { cx,
|
||||
<p>"Select a contact to view more info."</p>
|
||||
@@ -170,118 +170,3 @@ In fact, in this case, we don’t even need to rerender the `<Contact/>` compone
|
||||
[Click to open CodeSandbox.](https://codesandbox.io/p/sandbox/16-router-fy4tjv?file=%2Fsrc%2Fmain.rs&selection=%5B%7B%22endColumn%22%3A1%2C%22endLineNumber%22%3A3%2C%22startColumn%22%3A1%2C%22startLineNumber%22%3A3%7D%5D)
|
||||
|
||||
<iframe src="https://codesandbox.io/p/sandbox/16-router-fy4tjv?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" style="max-height: 100vh"></iframe>
|
||||
|
||||
<details>
|
||||
<summary>CodeSandbox Source</summary>
|
||||
|
||||
```rust
|
||||
use leptos::*;
|
||||
use leptos_router::*;
|
||||
|
||||
#[component]
|
||||
fn App(cx: Scope) -> impl IntoView {
|
||||
view! { cx,
|
||||
<Router>
|
||||
<h1>"Contact App"</h1>
|
||||
// this <nav> will show on every routes,
|
||||
// because it's outside the <Routes/>
|
||||
// note: we can just use normal <a> tags
|
||||
// and the router will use client-side navigation
|
||||
<nav>
|
||||
<h2>"Navigation"</h2>
|
||||
<a href="/">"Home"</a>
|
||||
<a href="/contacts">"Contacts"</a>
|
||||
</nav>
|
||||
<main>
|
||||
<Routes>
|
||||
// / just has an un-nested "Home"
|
||||
<Route path="/" view=|cx| view! { cx,
|
||||
<h3>"Home"</h3>
|
||||
}/>
|
||||
// /contacts has nested routes
|
||||
<Route
|
||||
path="/contacts"
|
||||
view=ContactList
|
||||
// if no id specified, fall back
|
||||
<Route path=":id" view=ContactInfo>
|
||||
<Route path="" view=|cx| view! { cx,
|
||||
<div class="tab">
|
||||
"(Contact Info)"
|
||||
</div>
|
||||
}/>
|
||||
<Route path="conversations" view=|cx| view! { cx,
|
||||
<div class="tab">
|
||||
"(Conversations)"
|
||||
</div>
|
||||
}/>
|
||||
</Route>
|
||||
// if no id specified, fall back
|
||||
<Route path="" view=|cx| view! { cx,
|
||||
<div class="select-user">
|
||||
"Select a user to view contact info."
|
||||
</div>
|
||||
}/>
|
||||
</Route>
|
||||
</Routes>
|
||||
</main>
|
||||
</Router>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
fn ContactList(cx: Scope) -> impl IntoView {
|
||||
view! { cx,
|
||||
<div class="contact-list">
|
||||
// here's our contact list component itself
|
||||
<div class="contact-list-contacts">
|
||||
<h3>"Contacts"</h3>
|
||||
<A href="alice">"Alice"</A>
|
||||
<A href="bob">"Bob"</A>
|
||||
<A href="steve">"Steve"</A>
|
||||
</div>
|
||||
|
||||
// <Outlet/> will show the nested child route
|
||||
// we can position this outlet wherever we want
|
||||
// within the layout
|
||||
<Outlet/>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
fn ContactInfo(cx: Scope) -> impl IntoView {
|
||||
// we can access the :id param reactively with `use_params_map`
|
||||
let params = use_params_map(cx);
|
||||
let id = move || params.with(|params| params.get("id").cloned().unwrap_or_default());
|
||||
|
||||
// imagine we're loading data from an API here
|
||||
let name = move || match id().as_str() {
|
||||
"alice" => "Alice",
|
||||
"bob" => "Bob",
|
||||
"steve" => "Steve",
|
||||
_ => "User not found.",
|
||||
};
|
||||
|
||||
view! { cx,
|
||||
<div class="contact-info">
|
||||
<h4>{name}</h4>
|
||||
<div class="tabs">
|
||||
<A href="" exact=true>"Contact Info"</A>
|
||||
<A href="conversations">"Conversations"</A>
|
||||
</div>
|
||||
|
||||
// <Outlet/> here is the tabs that are nested
|
||||
// underneath the /contacts/:id route
|
||||
<Outlet/>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
leptos::mount_to_body(|cx| view! { cx, <App/> })
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</details>
|
||||
</preview>
|
||||
|
||||
@@ -36,14 +36,6 @@ struct ContactSearch {
|
||||
```
|
||||
|
||||
> Note: The `Params` derive macro is located at `leptos::Params`, and the `Params` trait is at `leptos_router::Params`. If you avoid using glob imports like `use leptos::*;`, make sure you’re importing the right one for the derive macro.
|
||||
>
|
||||
> If you are not using the `nightly` feature, you will get the error
|
||||
>
|
||||
> ```
|
||||
> no function or associated item named `into_param` found for struct `std::string::String` in the current scope
|
||||
> ```
|
||||
>
|
||||
> At the moment, supporting both `T: FromStr` and `Option<T>` for typed params requires a nightly feature. You can fix this by simply changing the struct to use `q: Option<String>` instead of `q: String`.
|
||||
|
||||
Now we can use them in a component. Imagine a URL that has both params and a query, like `/contacts/:id?q=Search`.
|
||||
|
||||
@@ -85,119 +77,3 @@ This can get a little messy: deriving a signal that wraps an `Option<_>` or `Res
|
||||
[Click to open CodeSandbox.](https://codesandbox.io/p/sandbox/16-router-fy4tjv?file=%2Fsrc%2Fmain.rs&selection=%5B%7B%22endColumn%22%3A1%2C%22endLineNumber%22%3A3%2C%22startColumn%22%3A1%2C%22startLineNumber%22%3A3%7D%5D)
|
||||
|
||||
<iframe src="https://codesandbox.io/p/sandbox/16-router-fy4tjv?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" style="max-height: 100vh"></iframe>
|
||||
|
||||
<details>
|
||||
<summary>CodeSandbox Source</summary>
|
||||
|
||||
```rust
|
||||
use leptos::*;
|
||||
use leptos_router::*;
|
||||
|
||||
#[component]
|
||||
fn App(cx: Scope) -> impl IntoView {
|
||||
view! { cx,
|
||||
<Router>
|
||||
<h1>"Contact App"</h1>
|
||||
// this <nav> will show on every routes,
|
||||
// because it's outside the <Routes/>
|
||||
// note: we can just use normal <a> tags
|
||||
// and the router will use client-side navigation
|
||||
<nav>
|
||||
<h2>"Navigation"</h2>
|
||||
<a href="/">"Home"</a>
|
||||
<a href="/contacts">"Contacts"</a>
|
||||
</nav>
|
||||
<main>
|
||||
<Routes>
|
||||
// / just has an un-nested "Home"
|
||||
<Route path="/" view=|cx| view! { cx,
|
||||
<h3>"Home"</h3>
|
||||
}/>
|
||||
// /contacts has nested routes
|
||||
<Route
|
||||
path="/contacts"
|
||||
view=ContactList
|
||||
>
|
||||
// if no id specified, fall back
|
||||
<Route path=":id" view=ContactInfo>
|
||||
<Route path="" view=|cx| view! { cx,
|
||||
<div class="tab">
|
||||
"(Contact Info)"
|
||||
</div>
|
||||
}/>
|
||||
<Route path="conversations" view=|cx| view! { cx,
|
||||
<div class="tab">
|
||||
"(Conversations)"
|
||||
</div>
|
||||
}/>
|
||||
</Route>
|
||||
// if no id specified, fall back
|
||||
<Route path="" view=|cx| view! { cx,
|
||||
<div class="select-user">
|
||||
"Select a user to view contact info."
|
||||
</div>
|
||||
}/>
|
||||
</Route>
|
||||
</Routes>
|
||||
</main>
|
||||
</Router>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
fn ContactList(cx: Scope) -> impl IntoView {
|
||||
view! { cx,
|
||||
<div class="contact-list">
|
||||
// here's our contact list component itself
|
||||
<div class="contact-list-contacts">
|
||||
<h3>"Contacts"</h3>
|
||||
<A href="alice">"Alice"</A>
|
||||
<A href="bob">"Bob"</A>
|
||||
<A href="steve">"Steve"</A>
|
||||
</div>
|
||||
|
||||
// <Outlet/> will show the nested child route
|
||||
// we can position this outlet wherever we want
|
||||
// within the layout
|
||||
<Outlet/>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
fn ContactInfo(cx: Scope) -> impl IntoView {
|
||||
// we can access the :id param reactively with `use_params_map`
|
||||
let params = use_params_map(cx);
|
||||
let id = move || params.with(|params| params.get("id").cloned().unwrap_or_default());
|
||||
|
||||
// imagine we're loading data from an API here
|
||||
let name = move || match id().as_str() {
|
||||
"alice" => "Alice",
|
||||
"bob" => "Bob",
|
||||
"steve" => "Steve",
|
||||
_ => "User not found.",
|
||||
};
|
||||
|
||||
view! { cx,
|
||||
<div class="contact-info">
|
||||
<h4>{name}</h4>
|
||||
<div class="tabs">
|
||||
<A href="" exact=true>"Contact Info"</A>
|
||||
<A href="conversations">"Conversations"</A>
|
||||
</div>
|
||||
|
||||
// <Outlet/> here is the tabs that are nested
|
||||
// underneath the /contacts/:id route
|
||||
<Outlet/>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
leptos::mount_to_body(|cx| view! { cx, <App/> })
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</details>
|
||||
</preview>
|
||||
|
||||
@@ -11,8 +11,6 @@ The router will bail out of handling an `<a>` click under a number of situations
|
||||
|
||||
In other words, the router will only try to do a client-side navigation when it’s pretty sure it can handle it, and it will upgrade every `<a>` element to get this special behavior.
|
||||
|
||||
> This also means that if you need to opt out of client-side routing, you can do so easily. For example, if you have a link to another page on the same domain, but which isn’t part of your Leptos app, you can just use `<a rel="external">` to tell the router it isn’t something it can handle.
|
||||
|
||||
The router also provides an [`<A>`](https://docs.rs/leptos_router/latest/leptos_router/fn.A.html) component, which does two additional things:
|
||||
|
||||
1. Correctly resolves relative nested routes. Relative routing with ordinary `<a>` tags can be tricky. For example, if you have a route like `/post/:id`, `<A href="1">` will generate the correct relative route, but `<a href="1">` likely will not (depending on where it appears in your view.) `<A/>` resolves routes relative to the path of the nested route within which it appears.
|
||||
@@ -23,119 +21,3 @@ The router also provides an [`<A>`](https://docs.rs/leptos_router/latest/leptos_
|
||||
[Click to open CodeSandbox.](https://codesandbox.io/p/sandbox/16-router-fy4tjv?file=%2Fsrc%2Fmain.rs&selection=%5B%7B%22endColumn%22%3A1%2C%22endLineNumber%22%3A3%2C%22startColumn%22%3A1%2C%22startLineNumber%22%3A3%7D%5D)
|
||||
|
||||
<iframe src="https://codesandbox.io/p/sandbox/16-router-fy4tjv?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" style="max-height: 100vh"></iframe>
|
||||
|
||||
<details>
|
||||
<summary>CodeSandbox Source</summary>
|
||||
|
||||
```rust
|
||||
use leptos::*;
|
||||
use leptos_router::*;
|
||||
|
||||
#[component]
|
||||
fn App(cx: Scope) -> impl IntoView {
|
||||
view! { cx,
|
||||
<Router>
|
||||
<h1>"Contact App"</h1>
|
||||
// this <nav> will show on every routes,
|
||||
// because it's outside the <Routes/>
|
||||
// note: we can just use normal <a> tags
|
||||
// and the router will use client-side navigation
|
||||
<nav>
|
||||
<h2>"Navigation"</h2>
|
||||
<a href="/">"Home"</a>
|
||||
<a href="/contacts">"Contacts"</a>
|
||||
</nav>
|
||||
<main>
|
||||
<Routes>
|
||||
// / just has an un-nested "Home"
|
||||
<Route path="/" view=|cx| view! { cx,
|
||||
<h3>"Home"</h3>
|
||||
}/>
|
||||
// /contacts has nested routes
|
||||
<Route
|
||||
path="/contacts"
|
||||
view=ContactList
|
||||
>
|
||||
// if no id specified, fall back
|
||||
<Route path=":id" view=ContactInfo>
|
||||
<Route path="" view=|cx| view! { cx,
|
||||
<div class="tab">
|
||||
"(Contact Info)"
|
||||
</div>
|
||||
}/>
|
||||
<Route path="conversations" view=|cx| view! { cx,
|
||||
<div class="tab">
|
||||
"(Conversations)"
|
||||
</div>
|
||||
}/>
|
||||
</Route>
|
||||
// if no id specified, fall back
|
||||
<Route path="" view=|cx| view! { cx,
|
||||
<div class="select-user">
|
||||
"Select a user to view contact info."
|
||||
</div>
|
||||
}/>
|
||||
</Route>
|
||||
</Routes>
|
||||
</main>
|
||||
</Router>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
fn ContactList(cx: Scope) -> impl IntoView {
|
||||
view! { cx,
|
||||
<div class="contact-list">
|
||||
// here's our contact list component itself
|
||||
<div class="contact-list-contacts">
|
||||
<h3>"Contacts"</h3>
|
||||
<A href="alice">"Alice"</A>
|
||||
<A href="bob">"Bob"</A>
|
||||
<A href="steve">"Steve"</A>
|
||||
</div>
|
||||
|
||||
// <Outlet/> will show the nested child route
|
||||
// we can position this outlet wherever we want
|
||||
// within the layout
|
||||
<Outlet/>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
fn ContactInfo(cx: Scope) -> impl IntoView {
|
||||
// we can access the :id param reactively with `use_params_map`
|
||||
let params = use_params_map(cx);
|
||||
let id = move || params.with(|params| params.get("id").cloned().unwrap_or_default());
|
||||
|
||||
// imagine we're loading data from an API here
|
||||
let name = move || match id().as_str() {
|
||||
"alice" => "Alice",
|
||||
"bob" => "Bob",
|
||||
"steve" => "Steve",
|
||||
_ => "User not found.",
|
||||
};
|
||||
|
||||
view! { cx,
|
||||
<div class="contact-info">
|
||||
<h4>{name}</h4>
|
||||
<div class="tabs">
|
||||
<A href="" exact=true>"Contact Info"</A>
|
||||
<A href="conversations">"Conversations"</A>
|
||||
</div>
|
||||
|
||||
// <Outlet/> here is the tabs that are nested
|
||||
// underneath the /contacts/:id route
|
||||
<Outlet/>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
leptos::mount_to_body(|cx| view! { cx, <App/> })
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</details>
|
||||
</preview>
|
||||
|
||||
@@ -65,117 +65,3 @@ You’ll notice that this version drops the `Submit` button. Instead, we add an
|
||||
[Click to open CodeSandbox.](https://codesandbox.io/p/sandbox/16-router-forked-hrrt3h?file=%2Fsrc%2Fmain.rs)
|
||||
|
||||
<iframe src="https://codesandbox.io/p/sandbox/16-router-forked-hrrt3h?file=%2Fsrc%2Fmain.rs" width="100%" height="1000px" style="max-height: 100vh"></iframe>
|
||||
|
||||
<details>
|
||||
<summary>CodeSandbox Source</summary>
|
||||
|
||||
```rust
|
||||
use leptos::*;
|
||||
use leptos_router::*;
|
||||
|
||||
#[component]
|
||||
fn App(cx: Scope) -> impl IntoView {
|
||||
view! { cx,
|
||||
<Router>
|
||||
<h1><code>"<Form/>"</code></h1>
|
||||
<main>
|
||||
<Routes>
|
||||
<Route path="" view=FormExample/>
|
||||
</Routes>
|
||||
</main>
|
||||
</Router>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn FormExample(cx: Scope) -> impl IntoView {
|
||||
// reactive access to URL query
|
||||
let query = use_query_map(cx);
|
||||
let name = move || query().get("name").cloned().unwrap_or_default();
|
||||
let number = move || query().get("number").cloned().unwrap_or_default();
|
||||
let select = move || query().get("select").cloned().unwrap_or_default();
|
||||
|
||||
view! { cx,
|
||||
// read out the URL query strings
|
||||
<table>
|
||||
<tr>
|
||||
<td><code>"name"</code></td>
|
||||
<td>{name}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>"number"</code></td>
|
||||
<td>{number}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><code>"select"</code></td>
|
||||
<td>{select}</td>
|
||||
</tr>
|
||||
</table>
|
||||
// <Form/> will navigate whenever submitted
|
||||
<h2>"Manual Submission"</h2>
|
||||
<Form method="GET" action="">
|
||||
// input names determine query string key
|
||||
<input type="text" name="name" value=name/>
|
||||
<input type="number" name="number" value=number/>
|
||||
<select name="select">
|
||||
// `selected` will set which starts as selected
|
||||
<option selected=move || select() == "A">
|
||||
"A"
|
||||
</option>
|
||||
<option selected=move || select() == "B">
|
||||
"B"
|
||||
</option>
|
||||
<option selected=move || select() == "C">
|
||||
"C"
|
||||
</option>
|
||||
</select>
|
||||
// submitting should cause a client-side
|
||||
// navigation, not a full reload
|
||||
<input type="submit"/>
|
||||
</Form>
|
||||
// This <Form/> uses some JavaScript to submit
|
||||
// on every input
|
||||
<h2>"Automatic Submission"</h2>
|
||||
<Form method="GET" action="">
|
||||
<input
|
||||
type="text"
|
||||
name="name"
|
||||
value=name
|
||||
// this oninput attribute will cause the
|
||||
// form to submit on every input to the field
|
||||
oninput="this.form.requestSubmit()"
|
||||
/>
|
||||
<input
|
||||
type="number"
|
||||
name="number"
|
||||
value=number
|
||||
oninput="this.form.requestSubmit()"
|
||||
/>
|
||||
<select name="select"
|
||||
onchange="this.form.requestSubmit()"
|
||||
>
|
||||
<option selected=move || select() == "A">
|
||||
"A"
|
||||
</option>
|
||||
<option selected=move || select() == "B">
|
||||
"B"
|
||||
</option>
|
||||
<option selected=move || select() == "C">
|
||||
"C"
|
||||
</option>
|
||||
</select>
|
||||
// submitting should cause a client-side
|
||||
// navigation, not a full reload
|
||||
<input type="submit"/>
|
||||
</Form>
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
leptos::mount_to_body(|cx| view! { cx, <App/> })
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</details>
|
||||
</preview>
|
||||
|
||||
@@ -113,7 +113,7 @@ Server functions are a cool technology, but it’s very important to remember. *
|
||||
|
||||
So far, everything I’ve said is actually framework agnostic. (And in fact, the Leptos server function crate has been integrated into Dioxus as well!) Server functions are simply a way of defining a function-like RPC call that leans on Web standards like HTTP requests and URL encoding.
|
||||
|
||||
But in a way, they also provide the last missing primitive in our story so far. Because a server function is just a plain Rust async function, it integrates perfectly with the async Leptos primitives we discussed [earlier](https://leptos-rs.github.io/leptos/async/index.html). So you can easily integrate your server functions with the rest of your applications:
|
||||
But in a way, they also provide the last missing primitive in our story so far. Because a server function is just a plain Rust async function, it integrates perfectly with the async Leptos primitives we discussed [earlier](../async/README.md). So you can easily integrate your server functions with the rest of your applications:
|
||||
|
||||
- Create **resources** that call the server function to load data from the server
|
||||
- Read these resources under `<Suspense/>` or `<Transition/>` to enable streaming SSR and fallback states while data loads.
|
||||
|
||||
@@ -6,9 +6,9 @@ The server functions we looked at in the last chapter showed how to run code on
|
||||
|
||||
We call Leptos a “full-stack” framework, but “full-stack” is always a misnomer (after all, it never means everything from the browser to your power company.) For us, “full stack” means that your Leptos app can run in the browser, and can run on the server, and can integrate the two, drawing together the unique features available in each; as we’ve seen in the book so far, a button click on the browser can drive a database read on the server, both written in the same Rust module. But Leptos itself doesn’t provide the server (or the database, or the operating system, or the firmware, or the electrical cables...)
|
||||
|
||||
Instead, Leptos provides integrations for the two most popular Rust web server frameworks, Actix Web ([`leptos_actix`](https://docs.rs/leptos_actix/latest/leptos_actix/)) and Axum ([`leptos_axum`](https://docs.rs/leptos_axum/latest/leptos_axum/)). We’ve built integrations with each server’s router so that you can simply plug your Leptos app into an existing server with `.leptos_routes()`, and easily handle server function calls.
|
||||
Instead, Leptos provides integrations for the two most popular Rust web server frameworks, Actix Web ([`leptos_actix`](https://docs.rs/leptos_actix/latest/leptos_actix/)) and Axum ([`leptos_axum`](https://docs.rs/leptos_actix/latest/leptos_axum/)). We’ve built integrations with each server’s router so that you can simply plug your Leptos app into an existing server with `.leptos_routes()`, and easily handle server function calls.
|
||||
|
||||
> If you haven’t seen our [Actix](https://github.com/leptos-rs/start) and [Axum](https://github.com/leptos-rs/start-axum) templates, now’s a good time to check them out.
|
||||
> If haven’t seen our [Actix](https://github.com/leptos-rs/start) and [Axum](https://github.com/leptos-rs/start-axum) templates, now’s a good time to check them out.
|
||||
|
||||
## Using Extractors
|
||||
|
||||
@@ -43,7 +43,7 @@ pub async fn actix_extract(cx: Scope) -> Result<String, ServerFnError> {
|
||||
|
||||
## Axum Extractors
|
||||
|
||||
The syntax for the [`leptos_axum::extract`](https://docs.rs/leptos_axum/latest/leptos_axum/fn.extract.html) function is very similar. (**Note**: This is available on the git main branch, but has not been released as of writing.) Note that Axum extractors return a `Result`, so you’ll need to add something to handle the error case.
|
||||
The syntax for the `leptos_axum::extract` function is very similar. (**Note**: This is available on the git main branch, but has not been released as of writing.) Note that Axum extractors return a `Result`, so you’ll need to add something to handle the error case.
|
||||
|
||||
```rust
|
||||
#[server(AxumExtract, "/api")]
|
||||
|
||||
@@ -8,12 +8,7 @@ If you’ve ever listened to streaming music or watched a video online, I’m su
|
||||
|
||||
Let me say a little more about what I mean.
|
||||
|
||||
Leptos supports all four different modes of rendering HTML that includes asynchronous data:
|
||||
|
||||
1. [Synchronous Rendering](#synchronous-rendering)
|
||||
1. [Async Rendering](#async-rendering)
|
||||
1. [In-Order streaming](#in-order-streaming)
|
||||
1. [Out-of-Order Streaming](#out-of-order-streaming)
|
||||
Leptos supports all four different of these different ways to render HTML that includes asynchronous data.
|
||||
|
||||
## Synchronous Rendering
|
||||
|
||||
@@ -69,7 +64,7 @@ If you’re using server-side rendering, the synchronous mode is almost never wh
|
||||
|
||||
5. **Partially-blocked streaming**: “Partially-blocked” streaming is useful when you have multiple separate `<Suspense/>` components on the page. If one of them reads from one or more “blocking resources” (see below), the fallback will not be sent; rather, the server will wait until that `<Suspense/>` has resolved and then replace the fallback with the resolved fragment on the server, which means that it is included in the initial HTML response and appears even if JavaScript is disabled or not supported. Other `<Suspense/>` stream in out of order as usual.
|
||||
|
||||
This is useful when you have multiple `<Suspense/>` on the page, and one is more important than the other: think of a blog post and comments, or product information and reviews. It is _not_ useful if there’s only one `<Suspense/>`, or if every `<Suspense/>` reads from blocking resources. In those cases it is a slower form of `async` rendering.
|
||||
This is useful when you have multiple `<Suspense/>` on the page, and one is more important than the other: think of a blog post and comments, or product information and reviews. It is *not* useful if there’s only one `<Suspense/>`, or if every `<Suspense/>` reads from blocking resources. In those cases it is a slower form of `async` rendering.
|
||||
|
||||
- _Pros_: Works if JavaScript is disabled or not supported on the user’s device.
|
||||
- _Cons_
|
||||
@@ -84,13 +79,13 @@ Because it offers the best blend of performance characteristics, Leptos defaults
|
||||
```rust
|
||||
<Routes>
|
||||
// We’ll load the home page with out-of-order streaming and <Suspense/>
|
||||
<Route path="" view=HomePage
|
||||
<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=Post
|
||||
view=|cx| view! { cx, <Post/> }
|
||||
ssr=SsrMode::Async
|
||||
/>
|
||||
</Routes>
|
||||
|
||||
@@ -76,7 +76,7 @@ wasm-pack test --firefox
|
||||
### Writing Your Tests
|
||||
|
||||
Most tests will involve some combination of vanilla DOM manipulation and comparison to a `view`. For example, here’s a test [for the
|
||||
`counter` example](https://github.com/leptos-rs/leptos/blob/main/examples/counter/tests/web.rs).
|
||||
`counter` example](https://github.com/leptos-rs/leptos/blob/main/examples/counter/tests/mod.rs).
|
||||
|
||||
First, we set up the testing environment.
|
||||
|
||||
|
||||
@@ -139,7 +139,7 @@ view! { cx,
|
||||
Remember—and this is _very important_—only functions are reactive. This means that
|
||||
`{count}` and `{count()}` do very different things in your view. `{count}` passes
|
||||
in a function, telling the framework to update the view every time `count` changes.
|
||||
`{count()}` accesses the value of `count` once, and passes an `i32` into the view,
|
||||
`{count()}` access the value of `count` once, and passes an `i32` into the view,
|
||||
rendering it once, unreactively. You can see the difference in the CodeSandbox below!
|
||||
|
||||
Let’s make one final change. `set_count(3)` is a pretty useless thing for a click handler to do. Let’s replace “set this value to 3” with “increment this value by 1”:
|
||||
@@ -160,67 +160,3 @@ Other Previews > 8080.` Hover over any of the variables to show Rust-Analyzer de
|
||||
[Click to open CodeSandbox.](https://codesandbox.io/p/sandbox/1-basic-component-3d74p3?file=%2Fsrc%2Fmain.rs&selection=%5B%7B%22endColumn%22%3A31%2C%22endLineNumber%22%3A19%2C%22startColumn%22%3A31%2C%22startLineNumber%22%3A19%7D%5D)
|
||||
|
||||
<iframe src="https://codesandbox.io/p/sandbox/1-basic-component-3d74p3?file=%2Fsrc%2Fmain.rs&selection=%5B%7B%22endColumn%22%3A31%2C%22endLineNumber%22%3A19%2C%22startColumn%22%3A31%2C%22startLineNumber%22%3A19%7D%5D" width="100%" height="1000px" style="max-height: 100vh"></iframe>
|
||||
|
||||
<details>
|
||||
<summary>CodeSandbox Source</summary>
|
||||
|
||||
```rust
|
||||
use leptos::*;
|
||||
|
||||
// The #[component] macro marks a function as a reusable component
|
||||
// Components are the building blocks of your user interface
|
||||
// They define a reusable unit of behavior
|
||||
#[component]
|
||||
fn App(cx: Scope) -> impl IntoView {
|
||||
// here we create a reactive signal
|
||||
// and get a (getter, setter) pair
|
||||
// signals are the basic unit of change in the framework
|
||||
// we'll talk more about them later
|
||||
let (count, set_count) = create_signal(cx, 0);
|
||||
|
||||
// the `view` macro is how we define the user interface
|
||||
// it uses an HTML-like format that can accept certain Rust values
|
||||
view! { cx,
|
||||
<button
|
||||
// on:click will run whenever the `click` event fires
|
||||
// every event handler is defined as `on:{eventname}`
|
||||
|
||||
// we're able to move `set_count` into the closure
|
||||
// because signals are Copy and 'static
|
||||
on:click=move |_| {
|
||||
set_count.update(|n| *n += 1);
|
||||
}
|
||||
>
|
||||
// text nodes in RSX should be wrapped in quotes,
|
||||
// like a normal Rust string
|
||||
"Click me"
|
||||
</button>
|
||||
<p>
|
||||
<strong>"Reactive: "</strong>
|
||||
// you can insert Rust expressions as values in the DOM
|
||||
// by wrapping them in curly braces
|
||||
// if you pass in a function, it will reactively update
|
||||
{move || count.get()}
|
||||
</p>
|
||||
<p>
|
||||
<strong>"Reactive shorthand: "</strong>
|
||||
// signals are functions, so we can remove the wrapping closure
|
||||
{count}
|
||||
</p>
|
||||
<p>
|
||||
<strong>"Not reactive: "</strong>
|
||||
// NOTE: if you write {count()}, this will *not* be reactive
|
||||
// it simply gets the value of count once
|
||||
{count()}
|
||||
</p>
|
||||
}
|
||||
}
|
||||
|
||||
// This `main` function is the entry point into the app
|
||||
// It just mounts our component to the <body>
|
||||
// Because we defined it as `fn App`, we can now use it in a
|
||||
// template as <App/>
|
||||
fn main() {
|
||||
leptos::mount_to_body(|cx| view! { cx, <App/> })
|
||||
}
|
||||
```
|
||||
|
||||
@@ -152,67 +152,3 @@ places in your application with minimal overhead.
|
||||
[Click to open CodeSandbox.](https://codesandbox.io/p/sandbox/2-dynamic-attribute-pqyvzl?file=%2Fsrc%2Fmain.rs&selection=%5B%7B%22endColumn%22%3A1%2C%22endLineNumber%22%3A2%2C%22startColumn%22%3A1%2C%22startLineNumber%22%3A2%7D%5D)
|
||||
|
||||
<iframe src="https://codesandbox.io/p/sandbox/2-dynamic-attribute-pqyvzl?file=%2Fsrc%2Fmain.rs&selection=%5B%7B%22endColumn%22%3A1%2C%22endLineNumber%22%3A2%2C%22startColumn%22%3A1%2C%22startLineNumber%22%3A2%7D%5D" width="100%" height="1000px" style="max-height: 100vh"></iframe>
|
||||
|
||||
<details>
|
||||
<summary>Code Sandbox Source</summary>
|
||||
|
||||
```rust
|
||||
use leptos::*;
|
||||
|
||||
#[component]
|
||||
fn App(cx: Scope) -> impl IntoView {
|
||||
let (count, set_count) = create_signal(cx, 0);
|
||||
|
||||
// a "derived signal" is a function that accesses other signals
|
||||
// we can use this to create reactive values that depend on the
|
||||
// values of one or more other signals
|
||||
let double_count = move || count() * 2;
|
||||
|
||||
view! { cx,
|
||||
<button
|
||||
on:click=move |_| {
|
||||
set_count.update(|n| *n += 1);
|
||||
}
|
||||
// the class: syntax reactively updates a single class
|
||||
// here, we'll set the `red` class when `count` is odd
|
||||
class:red=move || count() % 2 == 1
|
||||
>
|
||||
"Click me"
|
||||
</button>
|
||||
// NOTE: self-closing tags like <br> need an explicit /
|
||||
<br/>
|
||||
|
||||
// We'll update this progress bar every time `count` changes
|
||||
<progress
|
||||
// static attributes work as in HTML
|
||||
max="50"
|
||||
|
||||
// passing a function to an attribute
|
||||
// reactively sets that attribute
|
||||
// signals are functions, so this <=> `move || count.get()`
|
||||
value=count
|
||||
>
|
||||
</progress>
|
||||
<br/>
|
||||
|
||||
// This progress bar will use `double_count`
|
||||
// so it should move twice as fast!
|
||||
<progress
|
||||
max="50"
|
||||
// derived signals are functions, so they can also
|
||||
// reactive update the DOM
|
||||
value=double_count
|
||||
>
|
||||
</progress>
|
||||
<p>"Count: " {count}</p>
|
||||
<p>"Double Count: " {double_count}</p>
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
leptos::mount_to_body(|cx| view! { cx, <App/> })
|
||||
}
|
||||
```
|
||||
|
||||
</details>
|
||||
</preview>
|
||||
|
||||
@@ -219,25 +219,9 @@ where
|
||||
This is a perfectly reasonable way to write this component: `progress` now takes
|
||||
any value that implements this `Fn()` trait.
|
||||
|
||||
This generic can also be specified inline:
|
||||
|
||||
```rust
|
||||
#[component]
|
||||
fn ProgressBar<F: Fn() -> i32 + 'static>(
|
||||
cx: Scope,
|
||||
#[prop(default = 100)] max: u16,
|
||||
progress: F,
|
||||
) -> impl IntoView {
|
||||
view! { cx,
|
||||
<progress
|
||||
max=max
|
||||
value=progress
|
||||
/>
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
> Note that generic component props _can’t_ be specified with an `impl` yet (`progress: impl Fn() -> i32 + 'static,`), in part because they’re actually used to generate a `struct ProgressBarProps`, and struct fields cannot be `impl` types. The `#[component]` macro may be further improved in the future to allow inline `impl` generic props.
|
||||
> Note that generic component props _cannot_ be specified inline (as `<F: Fn() -> i32>`)
|
||||
> or as `progress: impl Fn() -> i32 + 'static,`, in part because they’re actually used to generate
|
||||
> a `struct ProgressBarProps`, and struct fields cannot be `impl` types.
|
||||
|
||||
### `into` Props
|
||||
|
||||
@@ -287,81 +271,6 @@ fn App(cx: Scope) -> impl IntoView {
|
||||
}
|
||||
```
|
||||
|
||||
### Optional Generic Props
|
||||
|
||||
Note that you can’t specify optional generic props for a component. Let’s see what would happen if you try:
|
||||
|
||||
```rust,compile_fail
|
||||
#[component]
|
||||
fn ProgressBar<F: Fn() -> i32 + 'static>(
|
||||
cx: Scope,
|
||||
#[prop(optional)] progress: Option<F>,
|
||||
) -> impl IntoView {
|
||||
progress.map(|progress| {
|
||||
view! { cx,
|
||||
<progress
|
||||
max=100
|
||||
value=progress
|
||||
/>
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn App(cx: Scope) -> impl IntoView {
|
||||
view! { cx,
|
||||
<ProgressBar/>
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Rust helpfully gives the error
|
||||
|
||||
```
|
||||
xx | <ProgressBar/>
|
||||
| ^^^^^^^^^^^ cannot infer type of the type parameter `F` declared on the function `ProgressBar`
|
||||
|
|
||||
help: consider specifying the generic argument
|
||||
|
|
||||
xx | <ProgressBar::<F>/>
|
||||
| +++++
|
||||
```
|
||||
|
||||
There are just two problems:
|
||||
|
||||
1. Leptos’s view macro doesn’t support specifying a generic on a component with this turbofish syntax.
|
||||
2. Even if you could, specifying the correct type here is not possible; closures and functions in general are unnameable types. The compiler can display them with a shorthand, but you can’t specify them.
|
||||
|
||||
However, you can get around this by providing a concrete type using `Box<dyn _>` or `&dyn _`:
|
||||
|
||||
```rust
|
||||
#[component]
|
||||
fn ProgressBar(
|
||||
cx: Scope,
|
||||
#[prop(optional)] progress: Option<Box<dyn Fn() -> i32>>,
|
||||
) -> impl IntoView {
|
||||
progress.map(|progress| {
|
||||
view! { cx,
|
||||
<progress
|
||||
max=100
|
||||
value=progress
|
||||
/>
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn App(cx: Scope) -> impl IntoView {
|
||||
view! { cx,
|
||||
<ProgressBar/>
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Because the Rust compiler now knows the concrete type of the prop, and therefore its size in memory even in the `None` case, this compiles fine.
|
||||
|
||||
> In this particular case, `&dyn Fn() -> i32` will cause lifetime issues, but in other cases, it may be a possibility.
|
||||
|
||||
## Documenting Components
|
||||
|
||||
This is one of the least essential but most important sections of this book.
|
||||
@@ -400,77 +309,3 @@ and see the power of the `#[component]` macro combined with rust-analyzer here.
|
||||
[Click to open CodeSandbox.](https://codesandbox.io/p/sandbox/3-components-50t2e7?file=%2Fsrc%2Fmain.rs&selection=%5B%7B%22endColumn%22%3A1%2C%22endLineNumber%22%3A7%2C%22startColumn%22%3A1%2C%22startLineNumber%22%3A7%7D%5D)
|
||||
|
||||
<iframe src="https://codesandbox.io/p/sandbox/3-components-50t2e7?file=%2Fsrc%2Fmain.rs&selection=%5B%7B%22endColumn%22%3A1%2C%22endLineNumber%22%3A7%2C%22startColumn%22%3A1%2C%22startLineNumber%22%3A7%7D%5D" width="100%" height="1000px" style="max-height: 100vh"></iframe>
|
||||
|
||||
<details>
|
||||
<summary>CodeSandbox Source</summary>
|
||||
|
||||
```rust
|
||||
use leptos::*;
|
||||
|
||||
// Composing different components together is how we build
|
||||
// user interfaces. Here, we'll define a resuable <ProgressBar/>.
|
||||
// You'll see how doc comments can be used to document components
|
||||
// and their properties.
|
||||
|
||||
/// Shows progress toward a goal.
|
||||
#[component]
|
||||
fn ProgressBar(
|
||||
// All components take a reactive `Scope` as the first argument
|
||||
cx: Scope,
|
||||
// Marks this as an optional prop. It will default to the default
|
||||
// value of its type, i.e., 0.
|
||||
#[prop(default = 100)]
|
||||
/// The maximum value of the progress bar.
|
||||
max: u16,
|
||||
// Will run `.into()` on the value passed into the prop.
|
||||
#[prop(into)]
|
||||
// `Signal<T>` is a wrapper for several reactive types.
|
||||
// It can be helpful in component APIs like this, where we
|
||||
// might want to take any kind of reactive value
|
||||
/// How much progress should be displayed.
|
||||
progress: Signal<i32>,
|
||||
) -> impl IntoView {
|
||||
view! { cx,
|
||||
<progress
|
||||
max={max}
|
||||
value=progress
|
||||
/>
|
||||
<br/>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
fn App(cx: Scope) -> impl IntoView {
|
||||
let (count, set_count) = create_signal(cx, 0);
|
||||
|
||||
let double_count = move || count() * 2;
|
||||
|
||||
view! { cx,
|
||||
<button
|
||||
on:click=move |_| {
|
||||
set_count.update(|n| *n += 1);
|
||||
}
|
||||
>
|
||||
"Click me"
|
||||
</button>
|
||||
<br/>
|
||||
// If you have this open in CodeSandbox or an editor with
|
||||
// rust-analyzer support, try hovering over `ProgressBar`,
|
||||
// `max`, or `progress` to see the docs we defined above
|
||||
<ProgressBar max=50 progress=count/>
|
||||
// Let's use the default max value on this one
|
||||
// the default is 100, so it should move half as fast
|
||||
<ProgressBar progress=count/>
|
||||
// Signal::derive creates a Signal wrapper from our derived signal
|
||||
// using double_count means it should move twice as fast
|
||||
<ProgressBar max=50 progress=Signal::derive(cx, double_count)/>
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
leptos::mount_to_body(|cx| view! { cx, <App/> })
|
||||
}
|
||||
```
|
||||
|
||||
</details>
|
||||
</preview>
|
||||
|
||||
@@ -106,162 +106,3 @@ Check out the `<DynamicList/>` component below for an example.
|
||||
[Click to open CodeSandbox.](https://codesandbox.io/p/sandbox/4-iteration-sglt1o?file=%2Fsrc%2Fmain.rs&selection=%5B%7B%22endColumn%22%3A6%2C%22endLineNumber%22%3A55%2C%22startColumn%22%3A5%2C%22startLineNumber%22%3A31%7D%5D)
|
||||
|
||||
<iframe src="https://codesandbox.io/p/sandbox/4-iteration-sglt1o?file=%2Fsrc%2Fmain.rs&selection=%5B%7B%22endColumn%22%3A6%2C%22endLineNumber%22%3A55%2C%22startColumn%22%3A5%2C%22startLineNumber%22%3A31%7D%5D" width="100%" height="1000px" style="max-height: 100vh"></iframe>
|
||||
|
||||
<details>
|
||||
<summary>CodeSandbox Source</summary>
|
||||
|
||||
```rust
|
||||
use leptos::*;
|
||||
|
||||
// Iteration is a very common task in most applications.
|
||||
// So how do you take a list of data and render it in the DOM?
|
||||
// This example will show you the two ways:
|
||||
// 1) for mostly-static lists, using Rust iterators
|
||||
// 2) for lists that grow, shrink, or move items, using <For/>
|
||||
|
||||
#[component]
|
||||
fn App(cx: Scope) -> impl IntoView {
|
||||
view! { cx,
|
||||
<h1>"Iteration"</h1>
|
||||
<h2>"Static List"</h2>
|
||||
<p>"Use this pattern if the list itself is static."</p>
|
||||
<StaticList length=5/>
|
||||
<h2>"Dynamic List"</h2>
|
||||
<p>"Use this pattern if the rows in your list will change."</p>
|
||||
<DynamicList initial_length=5/>
|
||||
}
|
||||
}
|
||||
|
||||
/// A list of counters, without the ability
|
||||
/// to add or remove any.
|
||||
#[component]
|
||||
fn StaticList(
|
||||
cx: Scope,
|
||||
/// How many counters to include in this list.
|
||||
length: usize,
|
||||
) -> impl IntoView {
|
||||
// create counter signals that start at incrementing numbers
|
||||
let counters = (1..=length).map(|idx| create_signal(cx, idx));
|
||||
|
||||
// when you have a list that doesn't change, you can
|
||||
// manipulate it using ordinary Rust iterators
|
||||
// and collect it into a Vec<_> to insert it into the DOM
|
||||
let counter_buttons = counters
|
||||
.map(|(count, set_count)| {
|
||||
view! { cx,
|
||||
<li>
|
||||
<button
|
||||
on:click=move |_| set_count.update(|n| *n += 1)
|
||||
>
|
||||
{count}
|
||||
</button>
|
||||
</li>
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
// Note that if `counter_buttons` were a reactive list
|
||||
// and its value changed, this would be very inefficient:
|
||||
// it would rerender every row every time the list changed.
|
||||
view! { cx,
|
||||
<ul>{counter_buttons}</ul>
|
||||
}
|
||||
}
|
||||
|
||||
/// A list of counters that allows you to add or
|
||||
/// remove counters.
|
||||
#[component]
|
||||
fn DynamicList(
|
||||
cx: Scope,
|
||||
/// The number of counters to begin with.
|
||||
initial_length: usize,
|
||||
) -> impl IntoView {
|
||||
// This dynamic list will use the <For/> component.
|
||||
// <For/> is a keyed list. This means that each row
|
||||
// has a defined key. If the key does not change, the row
|
||||
// will not be re-rendered. When the list changes, only
|
||||
// the minimum number of changes will be made to the DOM.
|
||||
|
||||
// `next_counter_id` will let us generate unique IDs
|
||||
// we do this by simply incrementing the ID by one
|
||||
// each time we create a counter
|
||||
let mut next_counter_id = initial_length;
|
||||
|
||||
// we generate an initial list as in <StaticList/>
|
||||
// but this time we include the ID along with the signal
|
||||
let initial_counters = (0..initial_length)
|
||||
.map(|id| (id, create_signal(cx, id + 1)))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
// now we store that initial list in a signal
|
||||
// this way, we'll be able to modify the list over time,
|
||||
// adding and removing counters, and it will change reactively
|
||||
let (counters, set_counters) = create_signal(cx, initial_counters);
|
||||
|
||||
let add_counter = move |_| {
|
||||
// create a signal for the new counter
|
||||
let sig = create_signal(cx, next_counter_id + 1);
|
||||
// add this counter to the list of counters
|
||||
set_counters.update(move |counters| {
|
||||
// since `.update()` gives us `&mut T`
|
||||
// we can just use normal Vec methods like `push`
|
||||
counters.push((next_counter_id, sig))
|
||||
});
|
||||
// increment the ID so it's always unique
|
||||
next_counter_id += 1;
|
||||
};
|
||||
|
||||
view! { cx,
|
||||
<div>
|
||||
<button on:click=add_counter>
|
||||
"Add Counter"
|
||||
</button>
|
||||
<ul>
|
||||
// The <For/> component is central here
|
||||
// This allows for efficient, key list rendering
|
||||
<For
|
||||
// `each` takes any function that returns an iterator
|
||||
// this should usually be a signal or derived signal
|
||||
// if it's not reactive, just render a Vec<_> instead of <For/>
|
||||
each=counters
|
||||
// the key should be unique and stable for each row
|
||||
// using an index is usually a bad idea, unless your list
|
||||
// can only grow, because moving items around inside the list
|
||||
// means their indices will change and they will all rerender
|
||||
key=|counter| counter.0
|
||||
// the view function receives each item from your `each` iterator
|
||||
// and returns a view
|
||||
view=move |cx, (id, (count, set_count))| {
|
||||
view! { cx,
|
||||
<li>
|
||||
<button
|
||||
on:click=move |_| set_count.update(|n| *n += 1)
|
||||
>
|
||||
{count}
|
||||
</button>
|
||||
<button
|
||||
on:click=move |_| {
|
||||
set_counters.update(|counters| {
|
||||
counters.retain(|(counter_id, _)| counter_id != &id)
|
||||
});
|
||||
}
|
||||
>
|
||||
"Remove"
|
||||
</button>
|
||||
</li>
|
||||
}
|
||||
}
|
||||
/>
|
||||
</ul>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
leptos::mount_to_body(|cx| view! { cx, <App/> })
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</details>
|
||||
</preview>
|
||||
|
||||
@@ -112,112 +112,3 @@ The view should be pretty self-explanatory by now. Note two things:
|
||||
[Click to open CodeSandbox.](https://codesandbox.io/p/sandbox/5-form-inputs-ih9m62?file=%2Fsrc%2Fmain.rs&selection=%5B%7B%22endColumn%22%3A1%2C%22endLineNumber%22%3A12%2C%22startColumn%22%3A1%2C%22startLineNumber%22%3A12%7D%5D)
|
||||
|
||||
<iframe src="https://codesandbox.io/p/sandbox/5-form-inputs-ih9m62?file=%2Fsrc%2Fmain.rs&selection=%5B%7B%22endColumn%22%3A1%2C%22endLineNumber%22%3A12%2C%22startColumn%22%3A1%2C%22startLineNumber%22%3A12%7D%5D" width="100%" height="1000px" style="max-height: 100vh"></iframe>
|
||||
|
||||
<details>
|
||||
<summary>CodeSandbox Source</summary>
|
||||
|
||||
```rust
|
||||
use leptos::{ev::SubmitEvent, *};
|
||||
|
||||
#[component]
|
||||
fn App(cx: Scope) -> impl IntoView {
|
||||
view! { cx,
|
||||
<h2>"Controlled Component"</h2>
|
||||
<ControlledComponent/>
|
||||
<h2>"Uncontrolled Component"</h2>
|
||||
<UncontrolledComponent/>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
fn ControlledComponent(cx: Scope) -> impl IntoView {
|
||||
// create a signal to hold the value
|
||||
let (name, set_name) = create_signal(cx, "Controlled".to_string());
|
||||
|
||||
view! { cx,
|
||||
<input type="text"
|
||||
// fire an event whenever the input changes
|
||||
on:input=move |ev| {
|
||||
// event_target_value is a Leptos helper function
|
||||
// it functions the same way as event.target.value
|
||||
// in JavaScript, but smooths out some of the typecasting
|
||||
// necessary to make this work in Rust
|
||||
set_name(event_target_value(&ev));
|
||||
}
|
||||
|
||||
// the `prop:` syntax lets you update a DOM property,
|
||||
// rather than an attribute.
|
||||
//
|
||||
// IMPORTANT: the `value` *attribute* only sets the
|
||||
// initial value, until you have made a change.
|
||||
// The `value` *property* sets the current value.
|
||||
// This is a quirk of the DOM; I didn't invent it.
|
||||
// Other frameworks gloss this over; I think it's
|
||||
// more important to give you access to the browser
|
||||
// as it really works.
|
||||
//
|
||||
// tl;dr: use prop:value for form inputs
|
||||
prop:value=name
|
||||
/>
|
||||
<p>"Name is: " {name}</p>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
fn UncontrolledComponent(cx: Scope) -> impl IntoView {
|
||||
// import the type for <input>
|
||||
use leptos::html::Input;
|
||||
|
||||
let (name, set_name) = create_signal(cx, "Uncontrolled".to_string());
|
||||
|
||||
// we'll use a NodeRef to store a reference to the input element
|
||||
// this will be filled when the element is created
|
||||
let input_element: NodeRef<Input> = create_node_ref(cx);
|
||||
|
||||
// fires when the form `submit` event happens
|
||||
// this will store the value of the <input> in our signal
|
||||
let on_submit = move |ev: SubmitEvent| {
|
||||
// stop the page from reloading!
|
||||
ev.prevent_default();
|
||||
|
||||
// here, we'll extract the value from the input
|
||||
let value = input_element()
|
||||
// event handlers can only fire after the view
|
||||
// is mounted to the DOM, so the `NodeRef` will be `Some`
|
||||
.expect("<input> to exist")
|
||||
// `NodeRef` implements `Deref` for the DOM element type
|
||||
// this means we can call`HtmlInputElement::value()`
|
||||
// to get the current value of the input
|
||||
.value();
|
||||
set_name(value);
|
||||
};
|
||||
|
||||
view! { cx,
|
||||
<form on:submit=on_submit>
|
||||
<input type="text"
|
||||
// here, we use the `value` *attribute* to set only
|
||||
// the initial value, letting the browser maintain
|
||||
// the state after that
|
||||
value=name
|
||||
|
||||
// store a reference to this input in `input_element`
|
||||
node_ref=input_element
|
||||
/>
|
||||
<input type="submit" value="Submit"/>
|
||||
</form>
|
||||
<p>"Name is: " {name}</p>
|
||||
}
|
||||
}
|
||||
|
||||
// This `main` function is the entry point into the app
|
||||
// It just mounts our component to the <body>
|
||||
// Because we defined it as `fn App`, we can now use it in a
|
||||
// template as <App/>
|
||||
fn main() {
|
||||
leptos::mount_to_body(|cx| view! { cx, <App/> })
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</details>
|
||||
</preview>
|
||||
|
||||
@@ -285,100 +285,3 @@ view! { cx,
|
||||
[Click to open CodeSandbox.](https://codesandbox.io/p/sandbox/6-control-flow-in-view-zttwfx?file=%2Fsrc%2Fmain.rs&selection=%5B%7B%22endColumn%22%3A1%2C%22endLineNumber%22%3A2%2C%22startColumn%22%3A1%2C%22startLineNumber%22%3A2%7D%5D)
|
||||
|
||||
<iframe src="https://codesandbox.io/p/sandbox/6-control-flow-in-view-zttwfx?file=%2Fsrc%2Fmain.rs&selection=%5B%7B%22endColumn%22%3A1%2C%22endLineNumber%22%3A2%2C%22startColumn%22%3A1%2C%22startLineNumber%22%3A2%7D%5D" width="100%" height="1000px" style="max-height: 100vh"></iframe>
|
||||
|
||||
<details>
|
||||
<summary>CodeSandbox Source</summary>
|
||||
|
||||
```rust
|
||||
use leptos::*;
|
||||
|
||||
#[component]
|
||||
fn App(cx: Scope) -> impl IntoView {
|
||||
let (value, set_value) = create_signal(cx, 0);
|
||||
let is_odd = move || value() & 1 == 1;
|
||||
let odd_text = move || if is_odd() { Some("How odd!") } else { None };
|
||||
|
||||
view! { cx,
|
||||
<h1>"Control Flow"</h1>
|
||||
|
||||
// Simple UI to update and show a value
|
||||
<button on:click=move |_| set_value.update(|n| *n += 1)>
|
||||
"+1"
|
||||
</button>
|
||||
<p>"Value is: " {value}</p>
|
||||
|
||||
<hr/>
|
||||
|
||||
<h2><code>"Option<T>"</code></h2>
|
||||
// For any `T` that implements `IntoView`,
|
||||
// so does `Option<T>`
|
||||
|
||||
<p>{odd_text}</p>
|
||||
// This means you can use `Option` methods on it
|
||||
<p>{move || odd_text().map(|text| text.len())}</p>
|
||||
|
||||
<h2>"Conditional Logic"</h2>
|
||||
// You can do dynamic conditional if-then-else
|
||||
// logic in several ways
|
||||
//
|
||||
// a. An "if" expression in a function
|
||||
// This will simply re-render every time the value
|
||||
// changes, which makes it good for lightweight UI
|
||||
<p>
|
||||
{move || if is_odd() {
|
||||
"Odd"
|
||||
} else {
|
||||
"Even"
|
||||
}}
|
||||
</p>
|
||||
|
||||
// b. Toggling some kind of class
|
||||
// This is smart for an element that's going to
|
||||
// toggled often, because it doesn't destroy
|
||||
// it in between states
|
||||
// (you can find the `hidden` class in `index.html`)
|
||||
<p class:hidden=is_odd>"Appears if even."</p>
|
||||
|
||||
// c. The <Show/> component
|
||||
// This only renders the fallback and the child
|
||||
// once, lazily, and toggles between them when
|
||||
// needed. This makes it more efficient in many cases
|
||||
// than a {move || if ...} block
|
||||
<Show when=is_odd
|
||||
fallback=|cx| view! { cx, <p>"Even steven"</p> }
|
||||
>
|
||||
<p>"Oddment"</p>
|
||||
</Show>
|
||||
|
||||
// d. Because `bool::then()` converts a `bool` to
|
||||
// `Option`, you can use it to create a show/hide toggled
|
||||
{move || is_odd().then(|| view! { cx, <p>"Oddity!"</p> })}
|
||||
|
||||
<h2>"Converting between Types"</h2>
|
||||
// e. Note: if branches return different types,
|
||||
// you can convert between them with
|
||||
// `.into_any()` (for different HTML element types)
|
||||
// or `.into_view(cx)` (for all view types)
|
||||
{move || match is_odd() {
|
||||
true if value() == 1 => {
|
||||
// <pre> returns HtmlElement<Pre>
|
||||
view! { cx, <pre>"One"</pre> }.into_any()
|
||||
},
|
||||
false if value() == 2 => {
|
||||
// <p> returns HtmlElement<P>
|
||||
// so we convert into a more generic type
|
||||
view! { cx, <p>"Two"</p> }.into_any()
|
||||
}
|
||||
_ => view! { cx, <textarea>{value()}</textarea> }.into_any()
|
||||
}}
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
leptos::mount_to_body(|cx| view! { cx, <App/> })
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</details>
|
||||
</preview>
|
||||
|
||||
@@ -113,64 +113,3 @@ an `<ErrorBoundary/>` will appear again.
|
||||
[Click to open CodeSandbox.](https://codesandbox.io/p/sandbox/7-error-handling-and-error-boundaries-sroncx?file=%2Fsrc%2Fmain.rs&selection=%5B%7B%22endColumn%22%3A1%2C%22endLineNumber%22%3A2%2C%22startColumn%22%3A1%2C%22startLineNumber%22%3A2%7D%5D)
|
||||
|
||||
<iframe src="https://codesandbox.io/p/sandbox/7-error-handling-and-error-boundaries-sroncx?file=%2Fsrc%2Fmain.rs&selection=%5B%7B%22endColumn%22%3A1%2C%22endLineNumber%22%3A2%2C%22startColumn%22%3A1%2C%22startLineNumber%22%3A2%7D%5D" width="100%" height="1000px" style="max-height: 100vh"></iframe>
|
||||
|
||||
<details>
|
||||
<summary>CodeSandbox Source</summary>
|
||||
|
||||
```rust
|
||||
use leptos::*;
|
||||
|
||||
#[component]
|
||||
fn App(cx: Scope) -> impl IntoView {
|
||||
let (value, set_value) = create_signal(cx, Ok(0));
|
||||
|
||||
// when input changes, try to parse a number from the input
|
||||
let on_input = move |ev| set_value(event_target_value(&ev).parse::<i32>());
|
||||
|
||||
view! { cx,
|
||||
<h1>"Error Handling"</h1>
|
||||
<label>
|
||||
"Type a number (or something that's not a number!)"
|
||||
<input type="number" on:input=on_input/>
|
||||
// If an `Err(_) had been rendered inside the <ErrorBoundary/>,
|
||||
// the fallback will be displayed. Otherwise, the children of the
|
||||
// <ErrorBoundary/> will be displayed.
|
||||
<ErrorBoundary
|
||||
// the fallback receives a signal containing current errors
|
||||
fallback=|cx, errors| view! { cx,
|
||||
<div class="error">
|
||||
<p>"Not a number! Errors: "</p>
|
||||
// we can render a list of errors
|
||||
// as strings, if we'd like
|
||||
<ul>
|
||||
{move || errors.get()
|
||||
.into_iter()
|
||||
.map(|(_, e)| view! { cx, <li>{e.to_string()}</li>})
|
||||
.collect::<Vec<_>>()
|
||||
}
|
||||
</ul>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<p>
|
||||
"You entered "
|
||||
// because `value` is `Result<i32, _>`,
|
||||
// it will render the `i32` if it is `Ok`,
|
||||
// and render nothing and trigger the error boundary
|
||||
// if it is `Err`. It's a signal, so this will dynamically
|
||||
// update when `value` changes
|
||||
<strong>{value}</strong>
|
||||
</p>
|
||||
</ErrorBoundary>
|
||||
</label>
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
leptos::mount_to_body(|cx| view! { cx, <App/> })
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</details>
|
||||
</preview>
|
||||
|
||||
@@ -288,150 +288,3 @@ signals and effects, all the way down.
|
||||
[Click to open CodeSandbox.](https://codesandbox.io/p/sandbox/8-parent-child-communication-84we8m?file=%2Fsrc%2Fmain.rs&selection=%5B%7B%22endColumn%22%3A1%2C%22endLineNumber%22%3A3%2C%22startColumn%22%3A1%2C%22startLineNumber%22%3A3%7D%5D)
|
||||
|
||||
<iframe src="https://codesandbox.io/p/sandbox/8-parent-child-communication-84we8m?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" style="max-height: 100vh"></iframe>
|
||||
|
||||
<details>
|
||||
<summary>CodeSandbox Source</summary>
|
||||
|
||||
```rust
|
||||
use leptos::{ev::MouseEvent, *};
|
||||
|
||||
// This highlights four different ways that child components can communicate
|
||||
// with their parent:
|
||||
// 1) <ButtonA/>: passing a WriteSignal as one of the child component props,
|
||||
// for the child component to write into and the parent to read
|
||||
// 2) <ButtonB/>: passing a closure as one of the child component props, for
|
||||
// the child component to call
|
||||
// 3) <ButtonC/>: adding an `on:` event listener to a component
|
||||
// 4) <ButtonD/>: providing a context that is used in the component (rather than prop drilling)
|
||||
|
||||
#[derive(Copy, Clone)]
|
||||
struct SmallcapsContext(WriteSignal<bool>);
|
||||
|
||||
#[component]
|
||||
pub fn App(cx: Scope) -> impl IntoView {
|
||||
// just some signals to toggle three classes on our <p>
|
||||
let (red, set_red) = create_signal(cx, false);
|
||||
let (right, set_right) = create_signal(cx, false);
|
||||
let (italics, set_italics) = create_signal(cx, false);
|
||||
let (smallcaps, set_smallcaps) = create_signal(cx, false);
|
||||
|
||||
// the newtype pattern isn't *necessary* here but is a good practice
|
||||
// it avoids confusion with other possible future `WriteSignal<bool>` contexts
|
||||
// and makes it easier to refer to it in ButtonC
|
||||
provide_context(cx, SmallcapsContext(set_smallcaps));
|
||||
|
||||
view! {
|
||||
cx,
|
||||
<main>
|
||||
<p
|
||||
// class: attributes take F: Fn() => bool, and these signals all implement Fn()
|
||||
class:red=red
|
||||
class:right=right
|
||||
class:italics=italics
|
||||
class:smallcaps=smallcaps
|
||||
>
|
||||
"Lorem ipsum sit dolor amet."
|
||||
</p>
|
||||
|
||||
// Button A: pass the signal setter
|
||||
<ButtonA setter=set_red/>
|
||||
|
||||
// Button B: pass a closure
|
||||
<ButtonB on_click=move |_| set_right.update(|value| *value = !*value)/>
|
||||
|
||||
// Button B: use a regular event listener
|
||||
// setting an event listener on a component like this applies it
|
||||
// to each of the top-level elements the component returns
|
||||
<ButtonC on:click=move |_| set_italics.update(|value| *value = !*value)/>
|
||||
|
||||
// Button D gets its setter from context rather than props
|
||||
<ButtonD/>
|
||||
</main>
|
||||
}
|
||||
}
|
||||
|
||||
/// Button A receives a signal setter and updates the signal itself
|
||||
#[component]
|
||||
pub fn ButtonA(
|
||||
cx: Scope,
|
||||
/// Signal that will be toggled when the button is clicked.
|
||||
setter: WriteSignal<bool>,
|
||||
) -> impl IntoView {
|
||||
view! {
|
||||
cx,
|
||||
<button
|
||||
on:click=move |_| setter.update(|value| *value = !*value)
|
||||
>
|
||||
"Toggle Red"
|
||||
</button>
|
||||
}
|
||||
}
|
||||
|
||||
/// Button B receives a closure
|
||||
#[component]
|
||||
pub fn ButtonB<F>(
|
||||
cx: Scope,
|
||||
/// Callback that will be invoked when the button is clicked.
|
||||
on_click: F,
|
||||
) -> impl IntoView
|
||||
where
|
||||
F: Fn(MouseEvent) + 'static,
|
||||
{
|
||||
view! {
|
||||
cx,
|
||||
<button
|
||||
on:click=on_click
|
||||
>
|
||||
"Toggle Right"
|
||||
</button>
|
||||
}
|
||||
|
||||
// just a note: in an ordinary function ButtonB could take on_click: impl Fn(MouseEvent) + 'static
|
||||
// and save you from typing out the generic
|
||||
// the component macro actually expands to define a
|
||||
//
|
||||
// struct ButtonBProps<F> where F: Fn(MouseEvent) + 'static {
|
||||
// on_click: F
|
||||
// }
|
||||
//
|
||||
// this is what allows us to have named props in our component invocation,
|
||||
// instead of an ordered list of function arguments
|
||||
// if Rust ever had named function arguments we could drop this requirement
|
||||
}
|
||||
|
||||
/// Button C is a dummy: it renders a button but doesn't handle
|
||||
/// its click. Instead, the parent component adds an event listener.
|
||||
#[component]
|
||||
pub fn ButtonC(cx: Scope) -> impl IntoView {
|
||||
view! {
|
||||
cx,
|
||||
<button>
|
||||
"Toggle Italics"
|
||||
</button>
|
||||
}
|
||||
}
|
||||
|
||||
/// Button D is very similar to Button A, but instead of passing the setter as a prop
|
||||
/// we get it from the context
|
||||
#[component]
|
||||
pub fn ButtonD(cx: Scope) -> impl IntoView {
|
||||
let setter = use_context::<SmallcapsContext>(cx).unwrap().0;
|
||||
|
||||
view! {
|
||||
cx,
|
||||
<button
|
||||
on:click=move |_| setter.update(|value| *value = !*value)
|
||||
>
|
||||
"Toggle Small Caps"
|
||||
</button>
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
leptos::mount_to_body(|cx| view! { cx, <App/> })
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</details>
|
||||
</preview>
|
||||
|
||||
@@ -115,118 +115,14 @@ Calling it like this will create a list:
|
||||
|
||||
```rust
|
||||
view! { cx,
|
||||
<WrapsChildren>
|
||||
<WrappedChildren>
|
||||
"A"
|
||||
"B"
|
||||
"C"
|
||||
</WrapsChildren>
|
||||
</WrappedChildren>
|
||||
}
|
||||
```
|
||||
|
||||
[Click to open CodeSandbox.](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)
|
||||
|
||||
<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" style="max-height: 100vh"></iframe>
|
||||
|
||||
<details>
|
||||
<summary>CodeSandbox Source</summary>
|
||||
|
||||
```rust
|
||||
use leptos::*;
|
||||
|
||||
// Often, you want to pass some kind of child view to another
|
||||
// component. There are two basic patterns for doing this:
|
||||
// - "render props": creating a component prop that takes a function
|
||||
// that creates a view
|
||||
// - the `children` prop: a special property that contains content
|
||||
// passed as the children of a component in your view, not as a
|
||||
// property
|
||||
|
||||
#[component]
|
||||
pub fn App(cx: Scope) -> impl IntoView {
|
||||
let (items, set_items) = create_signal(cx, vec![0, 1, 2]);
|
||||
let render_prop = move || {
|
||||
// items.with(...) reacts to the value without cloning
|
||||
// by applying a function. Here, we pass the `len` method
|
||||
// on a `Vec<_>` directly
|
||||
let len = move || items.with(Vec::len);
|
||||
view! { cx,
|
||||
<p>"Length: " {len}</p>
|
||||
}
|
||||
};
|
||||
|
||||
view! { cx,
|
||||
// This component just displays the two kinds of children,
|
||||
// embedding them in some other markup
|
||||
<TakesChildren
|
||||
// for component props, you can shorthand
|
||||
// `render_prop=render_prop` => `render_prop`
|
||||
// (this doesn't work for HTML element attributes)
|
||||
render_prop
|
||||
>
|
||||
// these look just like the children of an HTML element
|
||||
<p>"Here's a child."</p>
|
||||
<p>"Here's another child."</p>
|
||||
</TakesChildren>
|
||||
<hr/>
|
||||
// This component actually iterates over and wraps the children
|
||||
<WrapsChildren>
|
||||
<p>"Here's a child."</p>
|
||||
<p>"Here's another child."</p>
|
||||
</WrapsChildren>
|
||||
}
|
||||
}
|
||||
|
||||
/// Displays a `render_prop` and some children within markup.
|
||||
#[component]
|
||||
pub fn TakesChildren<F, IV>(
|
||||
cx: Scope,
|
||||
/// Takes a function (type F) that returns anything that can be
|
||||
/// converted into a View (type IV)
|
||||
render_prop: F,
|
||||
/// `children` takes the `Children` type
|
||||
/// this is an alias for `Box<dyn FnOnce(Scope) -> Fragment>`
|
||||
/// ... aren't you glad we named it `Children` instead?
|
||||
children: Children,
|
||||
) -> impl IntoView
|
||||
where
|
||||
F: Fn() -> IV,
|
||||
IV: IntoView,
|
||||
{
|
||||
view! { cx,
|
||||
<h1><code>"<TakesChildren/>"</code></h1>
|
||||
<h2>"Render Prop"</h2>
|
||||
{render_prop()}
|
||||
<hr/>
|
||||
<h2>"Children"</h2>
|
||||
{children(cx)}
|
||||
}
|
||||
}
|
||||
|
||||
/// Wraps each child in an `<li>` and embeds them in a `<ul>`.
|
||||
#[component]
|
||||
pub fn WrapsChildren(cx: Scope, children: Children) -> impl IntoView {
|
||||
// children(cx) returns a `Fragment`, which has a
|
||||
// `nodes` field that contains a Vec<View>
|
||||
// this means we can iterate over the children
|
||||
// to create something new!
|
||||
let children = children(cx)
|
||||
.nodes
|
||||
.into_iter()
|
||||
.map(|child| view! { cx, <li>{child}</li> })
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
view! { cx,
|
||||
<h1><code>"<WrapsChildren/>"</code></h1>
|
||||
// wrap our wrapped children in a UL
|
||||
<ul>{children}</ul>
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
leptos::mount_to_body(|cx| view! { cx, <App/> })
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
</details>
|
||||
</preview>
|
||||
|
||||
@@ -5,12 +5,10 @@ CARGO_MAKE_EXTEND_WORKSPACE_MAKEFILE = true
|
||||
CARGO_MAKE_CARGO_BUILD_TEST_FLAGS = ""
|
||||
CARGO_MAKE_WORKSPACE_EMULATION = true
|
||||
CARGO_MAKE_CRATE_WORKSPACE_MEMBERS = [
|
||||
"animated_show",
|
||||
"counter",
|
||||
"counter_isomorphic",
|
||||
"counters",
|
||||
"counters_stable",
|
||||
"counter_url_query,
|
||||
"counter_without_macros",
|
||||
"error_boundary",
|
||||
"errors_axum",
|
||||
@@ -47,75 +45,3 @@ grep -v gtk |
|
||||
jq -R -s -c 'split("\n")[:-1]')
|
||||
echo "CARGO_MAKE_CRATE_WORKSPACE_MEMBERS = $examples"
|
||||
'''
|
||||
|
||||
[tasks.test-info]
|
||||
workspace = false
|
||||
description = "report ci test runners for each example - Option [all]"
|
||||
script = '''
|
||||
BOLD="\e[1m"
|
||||
GREEN="\e[0;32m"
|
||||
ITALIC="\e[3m"
|
||||
YELLOW="\e[0;33m"
|
||||
RESET="\e[0m"
|
||||
|
||||
echo
|
||||
echo "${YELLOW}CI test runners by example...${RESET}"
|
||||
echo
|
||||
|
||||
examples=$(ls |
|
||||
grep -v README.md |
|
||||
grep -v Makefile.toml |
|
||||
grep -v cargo-make |
|
||||
grep -v gtk |
|
||||
sort -u |
|
||||
awk '{print $0 ", "}')
|
||||
|
||||
example_root_dir=$(pwd)
|
||||
|
||||
for example_dir in $examples
|
||||
do
|
||||
clean_name=$(echo $example_dir | sed 's%,%%')
|
||||
cd $clean_name
|
||||
|
||||
c_tests=$(grep -rl --fixed-strings "#[test]" | wc -l)
|
||||
rs_tests=$(grep -rl --fixed-strings "#[rstest]" | wc -l)
|
||||
w_configs=$(grep -rl "\/wasm-test.toml\"" | wc -l)
|
||||
pw_configs=$(grep -rl "\/playwright-test.toml\"" | wc -l)
|
||||
cl_configs=$(grep -rl "\/cargo-leptos-test.toml\"" | wc -l)
|
||||
|
||||
test_runner=
|
||||
|
||||
if [ $c_tests -gt 0 ]; then
|
||||
test_runner="-C"
|
||||
fi
|
||||
|
||||
if [ $rs_tests -gt 0 ]; then
|
||||
test_runner=$test_runner"-R"
|
||||
fi
|
||||
|
||||
if [ $w_configs -gt 0 ]; then
|
||||
test_runner=$test_runner"-W"
|
||||
fi
|
||||
|
||||
if [ $pw_configs -gt 0 ]; then
|
||||
test_runner=$test_runner"-P"
|
||||
fi
|
||||
|
||||
if [ $cl_configs -gt 0 ]; then
|
||||
test_runner=$test_runner"-L"
|
||||
fi
|
||||
|
||||
if [ ! -z "$1" ]; then
|
||||
# Show all examples
|
||||
echo "$clean_name ${BOLD}${test_runner}${RESET}"
|
||||
elif [ ! -z $test_runner ]; then
|
||||
# Filter out examples that do not run tests in `ci`
|
||||
echo "$clean_name ${BOLD}${test_runner}${RESET}"
|
||||
fi
|
||||
|
||||
cd $example_root_dir
|
||||
done
|
||||
echo
|
||||
echo "${ITALIC}Test Runners: C = Cargo Test, L = Cargo Leptos Test, P = Playwright Test, R = RS Test, W = WASM Test${RESET}"
|
||||
echo
|
||||
'''
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
[package]
|
||||
name = "animated-show"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[profile.release]
|
||||
codegen-units = 1
|
||||
lto = true
|
||||
|
||||
[dependencies]
|
||||
leptos = { path = "../../leptos", features = ["csr"] }
|
||||
console_log = "1"
|
||||
log = "0.4"
|
||||
console_error_panic_hook = "0.1.7"
|
||||
@@ -1 +0,0 @@
|
||||
extend = [{ path = "../cargo-make/main.toml" }]
|
||||
@@ -1,9 +0,0 @@
|
||||
# `<AnimatedShow>` combined with CSS animations
|
||||
|
||||
This is a very simple example of the `<AnimatedShow>` component.
|
||||
|
||||
This component is an extension for the `<Show>` component and it will not take in a fallback, but it will unmount the
|
||||
component from the DOM after a given duration. This makes it possible to have really easy unmount animations with just
|
||||
CSS.
|
||||
|
||||
Just execute `trunk serve` to start the demo.
|
||||
@@ -1,42 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<link data-trunk rel="rust" data-wasm-opt="z"/>
|
||||
<link data-trunk rel="icon" type="image/ico" href="/public/favicon.ico"/>
|
||||
<style>
|
||||
.hover-me {
|
||||
width: 100px;
|
||||
margin: 1rem;
|
||||
padding: 1rem;
|
||||
text-align: center;
|
||||
cursor: pointer;
|
||||
border: 1px solid grey;
|
||||
}
|
||||
.here-i-am {
|
||||
width: 100px;
|
||||
margin: 1rem;
|
||||
padding: 1rem;
|
||||
text-align: center;
|
||||
color: white;
|
||||
font-weight: bold;
|
||||
background: black;
|
||||
}
|
||||
|
||||
@keyframes fade-in {
|
||||
from { opacity: 0; }
|
||||
to { opacity: 1; }
|
||||
}
|
||||
@keyframes fade-out {
|
||||
from { opacity: 1; }
|
||||
to { opacity: 0; }
|
||||
}
|
||||
.fade-in-1000 {
|
||||
animation: 1000ms fade-in forwards;
|
||||
}
|
||||
.fade-out-1000 {
|
||||
animation: 1000ms fade-out forwards;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body></body>
|
||||
</html>
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 15 KiB |
@@ -1,34 +0,0 @@
|
||||
use core::time::Duration;
|
||||
use leptos::*;
|
||||
|
||||
#[component]
|
||||
pub fn App(cx: Scope) -> impl IntoView {
|
||||
let show = create_rw_signal(cx, false);
|
||||
|
||||
// the CSS classes in this example are just written directly inside the `index.html`
|
||||
view! { cx,
|
||||
<div
|
||||
class="hover-me"
|
||||
on:mouseenter=move |_| show.set(true)
|
||||
on:mouseleave=move |_| show.set(false)
|
||||
>
|
||||
"Hover Me"
|
||||
</div>
|
||||
|
||||
<AnimatedShow
|
||||
when=show
|
||||
// optional CSS class which will be applied if `when == true`
|
||||
show_class="fade-in-1000"
|
||||
// optional CSS class which will be applied if `when == false` and before the
|
||||
// `hide_delay` starts -> makes CSS unmount animations really easy
|
||||
hide_class="fade-out-1000"
|
||||
// the given unmount delay which should match your unmount animation duration
|
||||
hide_delay=Duration::from_millis(1000)
|
||||
>
|
||||
// provide any `Children` inside here
|
||||
<div class="here-i-am">
|
||||
"Here I Am!"
|
||||
</div>
|
||||
</AnimatedShow>
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
use animated_show::App;
|
||||
use leptos::*;
|
||||
|
||||
pub fn main() {
|
||||
_ = console_log::init_with_level(log::Level::Debug);
|
||||
console_error_panic_hook::set_once();
|
||||
mount_to_body(|cx| {
|
||||
view! { cx,
|
||||
<App />
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
[package]
|
||||
name = "counter_url_query"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[profile.release]
|
||||
codegen-units = 1
|
||||
lto = true
|
||||
|
||||
[dependencies]
|
||||
leptos = { path = "../../leptos", features = ["csr", "nightly"] }
|
||||
leptos_router = { path = "../../router", features = ["csr"] }
|
||||
console_log = "1"
|
||||
log = "0.4"
|
||||
console_error_panic_hook = "0.1.7"
|
||||
|
||||
[dev-dependencies]
|
||||
wasm-bindgen = "0.2"
|
||||
wasm-bindgen-test = "0.3.0"
|
||||
web-sys = "0.3"
|
||||
@@ -1 +0,0 @@
|
||||
extend = [{ path = "../cargo-make/main.toml" }]
|
||||
@@ -1,7 +0,0 @@
|
||||
# Leptos Query Counter Example
|
||||
|
||||
This example creates a simple counter whose state is persisted and synced in the url with query params.
|
||||
|
||||
To run it, just issue the `trunk serve --open` command in the example root. This will build the app, run it, and open a new browser to serve it.
|
||||
|
||||
> If you don't have `trunk` installed, [click here for install instructions.](https://trunkrs.dev/)
|
||||
@@ -1,8 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<link data-trunk rel="rust" data-wasm-opt="z"/>
|
||||
<link data-trunk rel="icon" type="image/ico" href="/public/favicon.ico"/>
|
||||
</head>
|
||||
<body></body>
|
||||
</html>
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 15 KiB |
@@ -1,39 +0,0 @@
|
||||
use leptos::*;
|
||||
use leptos_router::*;
|
||||
|
||||
/// A simple counter component.
|
||||
///
|
||||
/// You can use doc comments like this to document your component.
|
||||
#[component]
|
||||
pub fn SimpleQueryCounter(cx: Scope) -> impl IntoView {
|
||||
let (count, set_count) = create_query_signal::<i32>(cx, "count");
|
||||
let clear = move |_| set_count(None);
|
||||
let decrement = move |_| set_count(Some(count().unwrap_or(0) - 1));
|
||||
let increment = move |_| set_count(Some(count().unwrap_or(0) + 1));
|
||||
|
||||
let (msg, set_msg) = create_query_signal::<String>(cx, "message");
|
||||
let update_msg = move |ev| {
|
||||
let new_msg = event_target_value(&ev);
|
||||
if new_msg.is_empty() {
|
||||
set_msg(None);
|
||||
} else {
|
||||
set_msg(Some(new_msg));
|
||||
}
|
||||
};
|
||||
|
||||
view! { cx,
|
||||
<div>
|
||||
<button on:click=clear>"Clear"</button>
|
||||
<button on:click=decrement>"-1"</button>
|
||||
<span>"Value: " {move || count().unwrap_or(0)} "!"</span>
|
||||
<button on:click=increment>"+1"</button>
|
||||
|
||||
<br />
|
||||
|
||||
<input
|
||||
prop:value=move || msg().unwrap_or_default()
|
||||
on:input=update_msg
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
use counter_url_query::SimpleQueryCounter;
|
||||
use leptos::*;
|
||||
use leptos_router::*;
|
||||
|
||||
pub fn main() {
|
||||
_ = console_log::init_with_level(log::Level::Debug);
|
||||
console_error_panic_hook::set_once();
|
||||
mount_to_body(|cx| {
|
||||
view! { cx,
|
||||
<Router>
|
||||
<Routes>
|
||||
<Route path="" view=SimpleQueryCounter />
|
||||
</Routes>
|
||||
</Router>
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -34,7 +34,7 @@ pub fn App(cx: Scope) -> impl IntoView {
|
||||
</header>
|
||||
<main>
|
||||
<Routes>
|
||||
<Route path="" view=ExampleErrors/>
|
||||
<Route path="" view=|cx| view! { cx, <ExampleErrors/> }/>
|
||||
</Routes>
|
||||
</main>
|
||||
</Router>
|
||||
|
||||
@@ -80,7 +80,7 @@ This crate can be run without `cargo-leptos`, using `wasm-pack` and `cargo`. To
|
||||
To run it as a server side app with hydration, first you should run
|
||||
|
||||
```bash
|
||||
wasm-pack build --target=web --debug --no-default-features --features=hydrate
|
||||
wasm-pack build --target=web --no-default-features --features=hydrate
|
||||
```
|
||||
|
||||
to generate the WebAssembly to hydrate the HTML delivered from the server.
|
||||
@@ -99,4 +99,4 @@ cargo run --no-default-features --features=ssr
|
||||
You'll need to install trunk to client side render this bundle.
|
||||
|
||||
1. `cargo install trunk`
|
||||
Then the site can be served with `trunk serve --open`
|
||||
Then the site can be served with `trunk serve --open`
|
||||
@@ -170,7 +170,7 @@ pub fn TodoApp(cx: Scope) -> impl IntoView {
|
||||
<hr/>
|
||||
<main>
|
||||
<Routes>
|
||||
<Route path="" view=Todos/> //Route
|
||||
<Route path="" view=|cx| view! { cx, <Todos/> }/> //Route
|
||||
<Route path="signup" view=move |cx| view! {
|
||||
cx,
|
||||
<Signup action=signup/>
|
||||
|
||||
@@ -90,8 +90,8 @@ By default, `cargo-leptos` uses `nightly` Rust, `cargo-generate`, and `sass`. If
|
||||
|
||||
## Alternatives to cargo-leptos
|
||||
|
||||
This crate can be run without `cargo-leptos`, using `wasm-pack` and `cargo`. To do so, you'll need to install some other tools. 0. `cargo install wasm-pack`
|
||||
|
||||
This crate can be run without `cargo-leptos`, using `wasm-pack` and `cargo`. To do so, you'll need to install some other tools.
|
||||
0. `cargo install wasm-pack`
|
||||
1. 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.
|
||||
|
||||
### Server Side Rendering With Hydration
|
||||
@@ -99,7 +99,7 @@ This crate can be run without `cargo-leptos`, using `wasm-pack` and `cargo`. To
|
||||
To run it as a server side app with hydration, first you should run
|
||||
|
||||
```bash
|
||||
wasm-pack build --target=web --debug --no-default-features --features=hydrate
|
||||
wasm-pack build --target=web --no-default-features --features=hydrate
|
||||
```
|
||||
|
||||
to generate the WebAssembly to hydrate the HTML delivered from the server.
|
||||
|
||||
@@ -104,7 +104,7 @@ pub fn TodoApp(cx: Scope) -> impl IntoView {
|
||||
</header>
|
||||
<main>
|
||||
<Routes>
|
||||
<Route path="" view=Todos/>
|
||||
<Route path="" view=|cx| view! { cx, <Todos/> }/>
|
||||
</Routes>
|
||||
</main>
|
||||
</Router>
|
||||
@@ -126,6 +126,10 @@ pub fn Todos(cx: Scope) -> impl IntoView {
|
||||
|
||||
view! {
|
||||
cx,
|
||||
<form method="POST" action="/weird">
|
||||
<input type="text" name="hi" value="John"/>
|
||||
<input type="submit"/>
|
||||
</form>
|
||||
<div>
|
||||
<MultiActionForm action=add_todo>
|
||||
<label>
|
||||
|
||||
@@ -104,7 +104,10 @@ pub fn TodoApp(cx: Scope) -> impl IntoView {
|
||||
</header>
|
||||
<main>
|
||||
<Routes>
|
||||
<Route path="" view=Todos/> //Route
|
||||
<Route path="" view=|cx| view! {
|
||||
cx,
|
||||
<Todos/>
|
||||
}/> //Route
|
||||
</Routes>
|
||||
</main>
|
||||
</Router>
|
||||
|
||||
@@ -605,6 +605,7 @@ where
|
||||
let res_options3 = default_res_options.clone();
|
||||
let local_pool = get_leptos_pool();
|
||||
let (tx, rx) = futures::channel::mpsc::channel(8);
|
||||
let (runtime_tx, runtime_rx) = futures::channel::oneshot::channel();
|
||||
|
||||
let current_span = tracing::Span::current();
|
||||
local_pool.spawn_pinned(move || async move {
|
||||
@@ -629,12 +630,17 @@ where
|
||||
replace_blocks
|
||||
);
|
||||
|
||||
forward_stream(&options, res_options2, bundle, runtime, scope, tx).await;
|
||||
runtime_tx.send(runtime).expect("should be able to send runtime");
|
||||
|
||||
runtime.dispose();
|
||||
forward_stream(&options, res_options2, bundle, runtime, scope, tx).await;
|
||||
}.instrument(current_span));
|
||||
|
||||
generate_response(res_options3, rx)
|
||||
async move {
|
||||
let runtime = runtime_rx
|
||||
.await
|
||||
.expect("runtime should be sent by renderer");
|
||||
generate_response(res_options3, rx, runtime).await
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -643,6 +649,7 @@ where
|
||||
async fn generate_response(
|
||||
res_options: ResponseOptions,
|
||||
rx: Receiver<String>,
|
||||
runtime: RuntimeId,
|
||||
) -> Response<StreamBody<PinnedHtmlStream>> {
|
||||
let mut stream = Box::pin(rx.map(|html| Ok(Bytes::from(html))));
|
||||
|
||||
@@ -655,7 +662,11 @@ async fn generate_response(
|
||||
|
||||
let complete_stream =
|
||||
futures::stream::iter([first_chunk.unwrap(), second_chunk.unwrap()])
|
||||
.chain(stream);
|
||||
.chain(stream)
|
||||
.chain(futures::stream::once(async move {
|
||||
runtime.dispose();
|
||||
Ok(Default::default())
|
||||
}));
|
||||
|
||||
let mut res = Response::new(StreamBody::new(
|
||||
Box::pin(complete_stream) as PinnedHtmlStream
|
||||
@@ -770,6 +781,8 @@ where
|
||||
let full_path = format!("http://leptos.dev{path}");
|
||||
|
||||
let (tx, rx) = futures::channel::mpsc::channel(8);
|
||||
let (runtime_tx, runtime_rx) =
|
||||
futures::channel::oneshot::channel();
|
||||
let local_pool = get_leptos_pool();
|
||||
let current_span = tracing::Span::current();
|
||||
local_pool.spawn_pinned(|| async move {
|
||||
@@ -789,12 +802,15 @@ where
|
||||
add_context,
|
||||
);
|
||||
|
||||
forward_stream(&options, res_options2, bundle, runtime, scope, tx).await;
|
||||
runtime_tx.send(runtime).expect("should be able to send runtime");
|
||||
|
||||
runtime.dispose();
|
||||
forward_stream(&options, res_options2, bundle, runtime, scope, tx).await;
|
||||
}.instrument(current_span));
|
||||
|
||||
generate_response(res_options3, rx).await
|
||||
let runtime = runtime_rx
|
||||
.await
|
||||
.expect("runtime should be sent by renderer");
|
||||
generate_response(res_options3, rx, runtime).await
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -52,7 +52,7 @@ pub fn html_parts(
|
||||
let pkg_path = &options.site_pkg_dir;
|
||||
let output_name = &options.output_name;
|
||||
|
||||
// Because wasm-pack adds _bg to the end of the WASM filename, and we want to maintain compatibility with it's default options
|
||||
// Because wasm-pack adds _bg to the end of the WASM filename, and we want to mantain compatibility with it's default options
|
||||
// we add _bg to the wasm files if cargo-leptos doesn't set the env var LEPTOS_OUTPUT_NAME at compile time
|
||||
// Otherwise we need to add _bg because wasm_pack always does.
|
||||
let mut wasm_output_name = output_name.clone();
|
||||
@@ -60,7 +60,7 @@ pub fn html_parts(
|
||||
wasm_output_name.push_str("_bg");
|
||||
}
|
||||
|
||||
let leptos_autoreload = autoreload("", options);
|
||||
let leptos_autoreload = autoreload("".into(), options);
|
||||
|
||||
let html_metadata =
|
||||
meta.and_then(|mc| mc.html.as_string()).unwrap_or_default();
|
||||
@@ -94,7 +94,7 @@ pub fn html_parts_separated(
|
||||
.map(|nonce| format!(" nonce=\"{nonce}\""))
|
||||
.unwrap_or_default();
|
||||
|
||||
// Because wasm-pack adds _bg to the end of the WASM filename, and we want to maintain compatibility with it's default options
|
||||
// Because wasm-pack adds _bg to the end of the WASM filename, and we want to mantain compatibility with it's default options
|
||||
// we add _bg to the wasm files if cargo-leptos doesn't set the env var LEPTOS_OUTPUT_NAME at compile time
|
||||
// Otherwise we need to add _bg because wasm_pack always does.
|
||||
let mut wasm_output_name = output_name.clone();
|
||||
|
||||
@@ -28,13 +28,13 @@ leptos = { path = "." }
|
||||
default = ["serde"]
|
||||
template_macro = ["leptos_dom/web", "web-sys", "wasm-bindgen"]
|
||||
csr = [
|
||||
"leptos_dom/csr",
|
||||
"leptos_dom/web",
|
||||
"leptos_macro/csr",
|
||||
"leptos_reactive/csr",
|
||||
"leptos_server/csr",
|
||||
]
|
||||
hydrate = [
|
||||
"leptos_dom/hydrate",
|
||||
"leptos_dom/web",
|
||||
"leptos_macro/hydrate",
|
||||
"leptos_reactive/hydrate",
|
||||
"leptos_server/hydrate",
|
||||
|
||||
@@ -1,111 +0,0 @@
|
||||
use crate::Show;
|
||||
use core::time::Duration;
|
||||
use leptos::component;
|
||||
use leptos_dom::{helpers::TimeoutHandle, Fragment, IntoView};
|
||||
use leptos_macro::view;
|
||||
use leptos_reactive::{
|
||||
create_effect, on_cleanup, signal_prelude::*, store_value, Scope,
|
||||
StoredValue,
|
||||
};
|
||||
|
||||
/// A component that will show its children when the `when` condition is `true`.
|
||||
/// Additionally, you need to specify a `hide_delay`. If the `when` condition changes to `false`,
|
||||
/// the unmounting of the children will be delayed by the specified Duration.
|
||||
/// If you provide the optional `show_class` and `hide_class`, you can create very easy mount /
|
||||
/// unmount animations.
|
||||
///
|
||||
/// ```rust
|
||||
/// # use core::time::Duration;
|
||||
/// # use leptos::*;
|
||||
/// # #[component]
|
||||
/// # pub fn App(cx: Scope) -> impl IntoView {
|
||||
/// let show = create_rw_signal(cx, false);
|
||||
///
|
||||
/// view! { cx,
|
||||
/// <div
|
||||
/// class="hover-me"
|
||||
/// on:mouseenter=move |_| show.set(true)
|
||||
/// on:mouseleave=move |_| show.set(false)
|
||||
/// >
|
||||
/// "Hover Me"
|
||||
/// </div>
|
||||
///
|
||||
/// <AnimatedShow
|
||||
/// when=show
|
||||
/// show_class="fade-in-1000"
|
||||
/// hide_class="fade-out-1000"
|
||||
/// hide_delay=Duration::from_millis(1000)
|
||||
/// >
|
||||
/// <div class="here-i-am">
|
||||
/// "Here I Am!"
|
||||
/// </div>
|
||||
/// </AnimatedShow>
|
||||
/// }
|
||||
/// # }
|
||||
/// ```
|
||||
#[cfg_attr(
|
||||
any(debug_assertions, feature = "ssr"),
|
||||
tracing::instrument(level = "info", skip_all)
|
||||
)]
|
||||
#[component]
|
||||
pub fn AnimatedShow(
|
||||
/// The scope the component is running in
|
||||
cx: Scope,
|
||||
/// The components Show wraps
|
||||
children: Box<dyn Fn(Scope) -> Fragment>,
|
||||
/// If the component should show or not
|
||||
#[prop(into)]
|
||||
when: MaybeSignal<bool>,
|
||||
/// Optional CSS class to apply if `when == true`
|
||||
#[prop(optional)]
|
||||
show_class: &'static str,
|
||||
/// Optional CSS class to apply if `when == false`
|
||||
#[prop(optional)]
|
||||
hide_class: &'static str,
|
||||
/// The timeout after which the component will be unmounted if `when == false`
|
||||
hide_delay: Duration,
|
||||
) -> impl IntoView {
|
||||
let handle: StoredValue<Option<TimeoutHandle>> = store_value(cx, None);
|
||||
let cls = create_rw_signal(
|
||||
cx,
|
||||
if when.get_untracked() {
|
||||
show_class
|
||||
} else {
|
||||
hide_class
|
||||
},
|
||||
);
|
||||
let show = create_rw_signal(cx, when.get_untracked());
|
||||
|
||||
create_effect(cx, move |_| {
|
||||
if when.get() {
|
||||
// clear any possibly active timer
|
||||
if let Some(h) = handle.get_value() {
|
||||
h.clear();
|
||||
}
|
||||
|
||||
cls.set(show_class);
|
||||
show.set(true);
|
||||
} else {
|
||||
cls.set(hide_class);
|
||||
|
||||
let h = leptos_dom::helpers::set_timeout_with_handle(
|
||||
move || show.set(false),
|
||||
hide_delay,
|
||||
)
|
||||
.expect("set timeout in AnimatedShow");
|
||||
handle.set_value(Some(h));
|
||||
}
|
||||
});
|
||||
|
||||
on_cleanup(cx, move || {
|
||||
if let Some(h) = handle.get_value() {
|
||||
h.clear();
|
||||
}
|
||||
});
|
||||
|
||||
view! { cx,
|
||||
<Show when=move || show.get() fallback=|_| ()>
|
||||
<div class=move || cls.get()>{children(cx)}</div>
|
||||
</Show>
|
||||
}
|
||||
}
|
||||
@@ -58,14 +58,13 @@ where
|
||||
F: Fn(Scope, RwSignal<Errors>) -> IV + 'static,
|
||||
IV: IntoView,
|
||||
{
|
||||
let before_children = HydrationCtx::next_component();
|
||||
let before_children = HydrationCtx::next_component("e");
|
||||
|
||||
let errors: RwSignal<Errors> = create_rw_signal(cx, Errors::default());
|
||||
|
||||
provide_context(cx, errors);
|
||||
|
||||
// Run children so that they render and execute resources
|
||||
_ = HydrationCtx::next_component();
|
||||
let children = children(cx);
|
||||
HydrationCtx::continue_from(before_children);
|
||||
|
||||
|
||||
@@ -189,14 +189,12 @@ pub use typed_builder;
|
||||
pub use {leptos_macro::template, wasm_bindgen, web_sys};
|
||||
mod error_boundary;
|
||||
pub use error_boundary::*;
|
||||
mod animated_show;
|
||||
mod for_loop;
|
||||
mod show;
|
||||
pub use animated_show::*;
|
||||
pub use for_loop::*;
|
||||
pub use show::*;
|
||||
pub use suspense_component::*;
|
||||
mod suspense_component;
|
||||
pub use suspense_component::*;
|
||||
mod text_prop;
|
||||
mod transition;
|
||||
pub use text_prop::TextProp;
|
||||
|
||||
@@ -69,11 +69,13 @@ where
|
||||
// provide this SuspenseContext to any resources below it
|
||||
provide_context(cx, context);
|
||||
|
||||
let current_id = HydrationCtx::next_component();
|
||||
let before = HydrationCtx::peek();
|
||||
let current_id = HydrationCtx::next_component("s");
|
||||
leptos::log!("<Suspense/> next_component {current_id}");
|
||||
|
||||
let child = DynChild::new({
|
||||
#[cfg(not(any(feature = "csr", feature = "hydrate")))]
|
||||
let current_id = current_id;
|
||||
let current_id = current_id.clone();
|
||||
|
||||
let children = Rc::new(orig_children(cx).into_view(cx));
|
||||
#[cfg(not(any(feature = "csr", feature = "hydrate")))]
|
||||
@@ -97,7 +99,7 @@ where
|
||||
{
|
||||
// no resources were read under this, so just return the child
|
||||
if context.pending_resources.get() == 0 {
|
||||
HydrationCtx::continue_from(current_id);
|
||||
HydrationCtx::continue_from(current_id.clone());
|
||||
DynChild::new({
|
||||
let children = Rc::clone(&children);
|
||||
move || (*children).clone()
|
||||
@@ -106,7 +108,7 @@ where
|
||||
}
|
||||
// show the fallback, but also prepare to stream HTML
|
||||
else {
|
||||
HydrationCtx::continue_from(current_id);
|
||||
HydrationCtx::continue_from(current_id.clone());
|
||||
|
||||
cx.register_suspense(
|
||||
context,
|
||||
@@ -114,8 +116,11 @@ where
|
||||
// out-of-order streaming
|
||||
{
|
||||
let orig_children = Rc::clone(&orig_children);
|
||||
let current_id = current_id.clone();
|
||||
move || {
|
||||
HydrationCtx::continue_from(current_id);
|
||||
HydrationCtx::continue_from(
|
||||
current_id.clone(),
|
||||
);
|
||||
DynChild::new({
|
||||
let orig_children =
|
||||
orig_children(cx).into_view(cx);
|
||||
@@ -129,8 +134,11 @@ where
|
||||
// in-order streaming
|
||||
{
|
||||
let orig_children = Rc::clone(&orig_children);
|
||||
let current_id = current_id.clone();
|
||||
move || {
|
||||
HydrationCtx::continue_from(current_id);
|
||||
HydrationCtx::continue_from(
|
||||
current_id.clone(),
|
||||
);
|
||||
DynChild::new({
|
||||
let orig_children =
|
||||
orig_children(cx).into_view(cx);
|
||||
@@ -155,8 +163,8 @@ where
|
||||
_ => unreachable!(),
|
||||
};
|
||||
|
||||
HydrationCtx::continue_from(current_id);
|
||||
HydrationCtx::next_component();
|
||||
HydrationCtx::continue_from(before.clone());
|
||||
_ = HydrationCtx::id();
|
||||
|
||||
leptos_dom::View::Suspense(current_id, core_component)
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use leptos_dom::{Fragment, HydrationCtx, IntoView, View};
|
||||
use leptos_dom::{Fragment, IntoView, View};
|
||||
use leptos_macro::component;
|
||||
use leptos_reactive::{
|
||||
create_isomorphic_effect, use_context, Scope, SignalGet, SignalSetter,
|
||||
@@ -99,7 +99,7 @@ where
|
||||
|
||||
let is_first_run =
|
||||
is_first_run(&first_run, &suspense_context);
|
||||
first_run.set(false);
|
||||
first_run.set(is_first_run);
|
||||
|
||||
if let Some(prev_children) = &*prev_child.borrow() {
|
||||
if is_first_run {
|
||||
@@ -127,10 +127,7 @@ where
|
||||
if is_first_run(&first_run, &suspense_context) {
|
||||
let has_local_only = suspense_context.has_local_only()
|
||||
|| cfg!(feature = "csr");
|
||||
if (!has_local_only || child_runs.get() > 0)
|
||||
&& (cfg!(feature = "csr")
|
||||
|| HydrationCtx::is_hydrating())
|
||||
{
|
||||
if !has_local_only || child_runs.get() > 0 {
|
||||
first_run.set(false);
|
||||
}
|
||||
}
|
||||
@@ -166,7 +163,7 @@ fn is_first_run(
|
||||
// SSR but with only local resources (so, has not streamed)
|
||||
(_, false, true) => true,
|
||||
// hydrate: it's the first run
|
||||
(first_run, true, _) => HydrationCtx::is_hydrating() || first_run,
|
||||
(_, true, _) => true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,12 +52,12 @@ pub fn App(cx: Scope) -> impl IntoView {
|
||||
<Outlet/>
|
||||
}
|
||||
>
|
||||
<Route path="" view=Nested
|
||||
<Route path="inside" view=NestedResourceInside
|
||||
<Route path="single" view=Single
|
||||
<Route path="parallel" view=Parallel
|
||||
<Route path="inside-component" view=InsideComponent
|
||||
<Route path="none" view=None
|
||||
<Route path="" view=|cx| view! { cx, <Nested/> }/>
|
||||
<Route path="inside" view=|cx| view! { cx, <NestedResourceInside/> }/>
|
||||
<Route path="single" view=|cx| view! { cx, <Single/> }/>
|
||||
<Route path="parallel" view=|cx| view! { cx, <Parallel/> }/>
|
||||
<Route path="inside-component" view=|cx| view! { cx, <InsideComponent/> }/>
|
||||
<Route path="none" view=|cx| view! { cx, <None/> }/>
|
||||
</Route>
|
||||
// in-order
|
||||
<Route
|
||||
@@ -69,12 +69,12 @@ pub fn App(cx: Scope) -> impl IntoView {
|
||||
<Outlet/>
|
||||
}
|
||||
>
|
||||
<Route path="" view=Nested
|
||||
<Route path="inside" view=NestedResourceInside
|
||||
<Route path="single" view=Single
|
||||
<Route path="parallel" view=Parallel
|
||||
<Route path="inside-component" view=InsideComponent
|
||||
<Route path="none" view=None
|
||||
<Route path="" view=|cx| view! { cx, <Nested/> }/>
|
||||
<Route path="inside" view=|cx| view! { cx, <NestedResourceInside/> }/>
|
||||
<Route path="single" view=|cx| view! { cx, <Single/> }/>
|
||||
<Route path="parallel" view=|cx| view! { cx, <Parallel/> }/>
|
||||
<Route path="inside-component" view=|cx| view! { cx, <InsideComponent/> }/>
|
||||
<Route path="none" view=|cx| view! { cx, <None/> }/>
|
||||
</Route>
|
||||
// async
|
||||
<Route
|
||||
@@ -86,12 +86,12 @@ pub fn App(cx: Scope) -> impl IntoView {
|
||||
<Outlet/>
|
||||
}
|
||||
>
|
||||
<Route path="" view=Nested
|
||||
<Route path="inside" view=NestedResourceInside
|
||||
<Route path="single" view=Single
|
||||
<Route path="parallel" view=Parallel
|
||||
<Route path="inside-component" view=InsideComponent
|
||||
<Route path="none" view=None
|
||||
<Route path="" view=|cx| view! { cx, <Nested/> }/>
|
||||
<Route path="inside" view=|cx| view! { cx, <NestedResourceInside/> }/>
|
||||
<Route path="single" view=|cx| view! { cx, <Single/> }/>
|
||||
<Route path="parallel" view=|cx| view! { cx, <Parallel/> }/>
|
||||
<Route path="inside-component" view=|cx| view! { cx, <InsideComponent/> }/>
|
||||
<Route path="none" view=|cx| view! { cx, <None/> }/>
|
||||
</Route>
|
||||
</Routes>
|
||||
</main>
|
||||
|
||||
@@ -179,9 +179,9 @@ impl TryFrom<String> for Env {
|
||||
/// Loads [LeptosOptions] from a Cargo.toml text content with layered overrides.
|
||||
/// If an env var is specified, like `LEPTOS_ENV`, it will override a setting in the file.
|
||||
pub fn get_config_from_str(text: &str) -> Result<ConfFile, LeptosConfigError> {
|
||||
let re: Regex = Regex::new(r"(?m)^\[package.metadata.leptos\]").unwrap();
|
||||
let re: Regex = Regex::new(r#"(?m)^\[package.metadata.leptos\]"#).unwrap();
|
||||
let re_workspace: Regex =
|
||||
Regex::new(r"(?m)^\[\[workspace.metadata.leptos\]\]").unwrap();
|
||||
Regex::new(r#"(?m)^\[\[workspace.metadata.leptos\]\]"#).unwrap();
|
||||
|
||||
let metadata_name;
|
||||
let start;
|
||||
|
||||
@@ -164,9 +164,7 @@ features = [
|
||||
|
||||
[features]
|
||||
default = []
|
||||
web = []
|
||||
csr = ["leptos_reactive/csr", "web"]
|
||||
hydrate = ["leptos_reactive/hydrate", "web"]
|
||||
web = ["leptos_reactive/csr"]
|
||||
ssr = ["leptos_reactive/ssr"]
|
||||
nightly = ["leptos_reactive/nightly"]
|
||||
nonce = ["dep:base64", "dep:getrandom", "dep:rand"]
|
||||
|
||||
@@ -196,7 +196,7 @@ impl TimeoutHandle {
|
||||
/// Executes the given function after the given duration of time has passed.
|
||||
/// [`setTimeout()`](https://developer.mozilla.org/en-US/docs/Web/API/setTimeout).
|
||||
#[cfg_attr(
|
||||
any(debug_assertions, feature = "ssr"),
|
||||
any(debug_assertions, features = "ssr"),
|
||||
instrument(level = "trace", skip_all, fields(duration = ?duration))
|
||||
)]
|
||||
pub fn set_timeout(cb: impl FnOnce() + 'static, duration: Duration) {
|
||||
@@ -206,7 +206,7 @@ pub fn set_timeout(cb: impl FnOnce() + 'static, duration: Duration) {
|
||||
/// Executes the given function after the given duration of time has passed, returning a cancelable handle.
|
||||
/// [`setTimeout()`](https://developer.mozilla.org/en-US/docs/Web/API/setTimeout).
|
||||
#[cfg_attr(
|
||||
any(debug_assertions, feature = "ssr"),
|
||||
any(debug_assertions, features = "ssr"),
|
||||
instrument(level = "trace", skip_all, fields(duration = ?duration))
|
||||
)]
|
||||
#[inline(always)]
|
||||
@@ -325,10 +325,11 @@ impl IntervalHandle {
|
||||
}
|
||||
}
|
||||
|
||||
/// Repeatedly calls the given function, with a delay of the given duration between calls.
|
||||
/// Repeatedly calls the given function, with a delay of the given duration between calls,
|
||||
/// returning a cancelable handle.
|
||||
/// See [`setInterval()`](https://developer.mozilla.org/en-US/docs/Web/API/setInterval).
|
||||
#[cfg_attr(
|
||||
any(debug_assertions, feature = "ssr"),
|
||||
any(debug_assertions, features = "ssr"),
|
||||
instrument(level = "trace", skip_all, fields(duration = ?duration))
|
||||
)]
|
||||
pub fn set_interval(cb: impl Fn() + 'static, duration: Duration) {
|
||||
@@ -339,7 +340,7 @@ pub fn set_interval(cb: impl Fn() + 'static, duration: Duration) {
|
||||
/// returning a cancelable handle.
|
||||
/// See [`setInterval()`](https://developer.mozilla.org/en-US/docs/Web/API/setInterval).
|
||||
#[cfg_attr(
|
||||
any(debug_assertions, feature = "ssr"),
|
||||
any(debug_assertions, features = "ssr"),
|
||||
instrument(level = "trace", skip_all, fields(duration = ?duration))
|
||||
)]
|
||||
#[inline(always)]
|
||||
|
||||
@@ -445,7 +445,7 @@ impl<El: ElementDescriptor + 'static> HtmlElement<El> {
|
||||
element: AnyElement {
|
||||
name: element.name(),
|
||||
is_void: element.is_void(),
|
||||
id: *element.hydration_id()
|
||||
id: element.hydration_id().clone()
|
||||
},
|
||||
#[cfg(debug_assertions)]
|
||||
view_marker
|
||||
@@ -1070,7 +1070,7 @@ impl<El: ElementDescriptor> IntoView for HtmlElement<El> {
|
||||
..
|
||||
} = self;
|
||||
|
||||
let id = *element.hydration_id();
|
||||
let id = element.hydration_id().clone();
|
||||
|
||||
let mut element = Element::new(element);
|
||||
let children = children;
|
||||
@@ -1114,7 +1114,7 @@ pub fn custom<El: ElementDescriptor>(cx: Scope, el: El) -> HtmlElement<Custom> {
|
||||
#[cfg(all(target_arch = "wasm32", feature = "web"))]
|
||||
element: el.as_ref().clone(),
|
||||
#[cfg(not(all(target_arch = "wasm32", feature = "web")))]
|
||||
id: *el.hydration_id(),
|
||||
id: el.hydration_id().clone(),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,16 +1,17 @@
|
||||
use cfg_if::cfg_if;
|
||||
use std::{cell::RefCell, fmt::Display};
|
||||
|
||||
#[cfg(all(target_arch = "wasm32", feature = "hydrate"))]
|
||||
mod hydration {
|
||||
cfg_if! {
|
||||
if #[cfg(all(target_arch = "wasm32", feature = "web"))] {
|
||||
use once_cell::unsync::Lazy as LazyCell;
|
||||
use std::{cell::RefCell, collections::HashMap};
|
||||
use std::collections::HashMap;
|
||||
use wasm_bindgen::JsCast;
|
||||
|
||||
// We can tell if we start in hydration mode by checking to see if the
|
||||
// id "_0-1" is present in the DOM. If it is, we know we are hydrating from
|
||||
// the server, if not, we are starting off in CSR
|
||||
thread_local! {
|
||||
pub static HYDRATION_COMMENTS: LazyCell<HashMap<String, web_sys::Comment>> = LazyCell::new(|| {
|
||||
static HYDRATION_COMMENTS: LazyCell<HashMap<String, web_sys::Comment>> = LazyCell::new(|| {
|
||||
let document = crate::document();
|
||||
let body = document.body().unwrap();
|
||||
let walker = document
|
||||
@@ -30,7 +31,7 @@ mod hydration {
|
||||
});
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
pub static VIEW_MARKERS: LazyCell<HashMap<String, web_sys::Comment>> = LazyCell::new(|| {
|
||||
pub(crate) static VIEW_MARKERS: LazyCell<HashMap<String, web_sys::Comment>> = LazyCell::new(|| {
|
||||
let document = crate::document();
|
||||
let body = document.body().unwrap();
|
||||
let walker = document
|
||||
@@ -47,33 +48,31 @@ mod hydration {
|
||||
map
|
||||
});
|
||||
|
||||
pub static IS_HYDRATING: RefCell<LazyCell<bool>> = RefCell::new(LazyCell::new(|| {
|
||||
static IS_HYDRATING: RefCell<LazyCell<bool>> = RefCell::new(LazyCell::new(|| {
|
||||
#[cfg(debug_assertions)]
|
||||
return crate::document().get_element_by_id("_0-1").is_some()
|
||||
|| crate::document().get_element_by_id("_0-1o").is_some()
|
||||
|| HYDRATION_COMMENTS.with(|comments| comments.get("_0-1o").is_some());
|
||||
return crate::document().get_element_by_id("_-1").is_some()
|
||||
|| crate::document().get_element_by_id("_-1o").is_some()
|
||||
|| HYDRATION_COMMENTS.with(|comments| comments.get("_-1o").is_some());
|
||||
|
||||
#[cfg(not(debug_assertions))]
|
||||
return crate::document().get_element_by_id("_0-1").is_some()
|
||||
|| HYDRATION_COMMENTS.with(|comments| comments.get("_0-1").is_some());
|
||||
return crate::document().get_element_by_id("_-1").is_some()
|
||||
|| HYDRATION_COMMENTS.with(|comments| comments.get("_-1").is_some());
|
||||
}));
|
||||
}
|
||||
|
||||
pub fn get_marker(id: &str) -> Option<web_sys::Comment> {
|
||||
HYDRATION_COMMENTS.with(|comments| comments.get(id).cloned())
|
||||
pub(crate) fn get_marker(id: &str) -> Option<web_sys::Comment> {
|
||||
HYDRATION_COMMENTS.with(|comments| comments.get(id).cloned())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(target_arch = "wasm32", feature = "hydrate"))]
|
||||
pub(crate) use hydration::*;
|
||||
|
||||
/// A stable identifier within the server-rendering or hydration process.
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Default)]
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, Default)]
|
||||
pub struct HydrationKey {
|
||||
/// ID of the current key.
|
||||
pub id: usize,
|
||||
/// ID of the current fragment.
|
||||
pub fragment: usize,
|
||||
pub fragment: String,
|
||||
}
|
||||
|
||||
impl Display for HydrationKey {
|
||||
@@ -90,7 +89,7 @@ pub struct HydrationCtx;
|
||||
impl HydrationCtx {
|
||||
/// Get the next `id` without incrementing it.
|
||||
pub fn peek() -> HydrationKey {
|
||||
ID.with(|id| *id.borrow())
|
||||
ID.with(|id| id.borrow().clone())
|
||||
}
|
||||
|
||||
/// Increments the current hydration `id` and returns it
|
||||
@@ -98,17 +97,17 @@ impl HydrationCtx {
|
||||
ID.with(|id| {
|
||||
let mut id = id.borrow_mut();
|
||||
id.id = id.id.wrapping_add(1);
|
||||
*id
|
||||
id.clone()
|
||||
})
|
||||
}
|
||||
|
||||
/// Resets the hydration `id` for the next component, and returns it
|
||||
pub fn next_component() -> HydrationKey {
|
||||
pub fn next_component(tag: &'static str) -> HydrationKey {
|
||||
ID.with(|id| {
|
||||
let mut id = id.borrow_mut();
|
||||
id.fragment = id.fragment.wrapping_add(1);
|
||||
id.fragment = format!("{}-{}{}", id.fragment, id.id, tag);
|
||||
id.id = 0;
|
||||
*id
|
||||
id.clone()
|
||||
})
|
||||
}
|
||||
|
||||
@@ -126,27 +125,16 @@ impl HydrationCtx {
|
||||
|
||||
#[cfg(all(target_arch = "wasm32", feature = "web"))]
|
||||
pub(crate) fn stop_hydrating() {
|
||||
#[cfg(feature = "hydrate")]
|
||||
{
|
||||
IS_HYDRATING.with(|is_hydrating| {
|
||||
std::mem::take(&mut *is_hydrating.borrow_mut());
|
||||
})
|
||||
}
|
||||
IS_HYDRATING.with(|is_hydrating| {
|
||||
std::mem::take(&mut *is_hydrating.borrow_mut());
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the UI is currently in the process of hydrating from the server-sent HTML.
|
||||
pub fn is_hydrating() -> bool {
|
||||
#[cfg(all(target_arch = "wasm32", feature = "hydrate"))]
|
||||
{
|
||||
IS_HYDRATING.with(|is_hydrating| **is_hydrating.borrow())
|
||||
}
|
||||
#[cfg(not(all(target_arch = "wasm32", feature = "hydrate")))]
|
||||
{
|
||||
false
|
||||
}
|
||||
#[cfg(all(target_arch = "wasm32", feature = "web"))]
|
||||
pub(crate) fn is_hydrating() -> bool {
|
||||
IS_HYDRATING.with(|is_hydrating| **is_hydrating.borrow())
|
||||
}
|
||||
|
||||
#[allow(dead_code)] // not used in CSR
|
||||
pub(crate) fn to_string(id: &HydrationKey, closing: bool) -> String {
|
||||
#[cfg(debug_assertions)]
|
||||
return format!("_{id}{}", if closing { 'c' } else { 'o' });
|
||||
|
||||
@@ -378,7 +378,7 @@ impl Element {
|
||||
is_void: el.is_void(),
|
||||
attrs: Default::default(),
|
||||
children: Default::default(),
|
||||
id: *el.hydration_id(),
|
||||
id: el.hydration_id().clone(),
|
||||
#[cfg(debug_assertions)]
|
||||
view_marker: None
|
||||
}
|
||||
@@ -416,18 +416,11 @@ impl Comment {
|
||||
|
||||
Self { content }
|
||||
} else {
|
||||
#[cfg(not(feature = "hydrate"))]
|
||||
{
|
||||
_ = id;
|
||||
_ = closing;
|
||||
}
|
||||
|
||||
let node = COMMENT.with(|comment| comment.clone_node().unwrap());
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
node.set_text_content(Some(&format!(" {content} ")));
|
||||
|
||||
#[cfg(feature = "hydrate")]
|
||||
if HydrationCtx::is_hydrating() {
|
||||
let id = HydrationCtx::to_string(id, closing);
|
||||
|
||||
|
||||
@@ -147,7 +147,7 @@ impl<T: ElementDescriptor + 'static> NodeRef<T> {
|
||||
|
||||
impl<T: ElementDescriptor> Clone for NodeRef<T> {
|
||||
fn clone(&self) -> Self {
|
||||
*self
|
||||
Self(self.0)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -453,7 +453,7 @@ impl View {
|
||||
View::CoreComponent(node) => {
|
||||
let (id, name, wrap, content) = match node {
|
||||
CoreComponent::Unit(u) => (
|
||||
u.id,
|
||||
u.id.clone(),
|
||||
"",
|
||||
false,
|
||||
Box::new(move || {
|
||||
|
||||
@@ -381,7 +381,7 @@ impl View {
|
||||
View::CoreComponent(node) => {
|
||||
let (id, name, wrap, content) = match node {
|
||||
CoreComponent::Unit(u) => (
|
||||
u.id,
|
||||
u.id.clone(),
|
||||
"",
|
||||
false,
|
||||
Box::new(move |chunks: &mut VecDeque<StreamChunk>| {
|
||||
|
||||
@@ -19,7 +19,7 @@ syn = { version = "2", features = [
|
||||
"printing",
|
||||
] }
|
||||
quote = "1"
|
||||
rstml = "0.11.0"
|
||||
rstml = "0.10.6"
|
||||
proc-macro2 = { version = "1", features = ["span-locations", "nightly"] }
|
||||
parking_lot = "0.12"
|
||||
walkdir = "2"
|
||||
|
||||
@@ -1,397 +1,386 @@
|
||||
console.log("[HOT RELOADING] Connected to server.");
|
||||
function patch(json) {
|
||||
try {
|
||||
const views = JSON.parse(json);
|
||||
for (const [id, patches] of views) {
|
||||
console.log("[HOT RELOAD]", id, patches);
|
||||
const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_COMMENT),
|
||||
open = `leptos-view|${id}|open`,
|
||||
close = `leptos-view|${id}|close`;
|
||||
let start, end;
|
||||
const instances = [];
|
||||
while (walker.nextNode()) {
|
||||
if (walker.currentNode.textContent == open) {
|
||||
start = walker.currentNode;
|
||||
} else if (walker.currentNode.textContent == close) {
|
||||
end = walker.currentNode;
|
||||
instances.push([start, end]);
|
||||
start = undefined;
|
||||
end = undefined;
|
||||
}
|
||||
}
|
||||
try {
|
||||
const views = JSON.parse(json);
|
||||
for (const [id, patches] of views) {
|
||||
console.log("[HOT RELOAD]", id, patches);
|
||||
const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_COMMENT),
|
||||
open = `leptos-view|${id}|open`,
|
||||
close = `leptos-view|${id}|close`;
|
||||
let start, end;
|
||||
const instances = [];
|
||||
while (walker.nextNode()) {
|
||||
if (walker.currentNode.textContent == open) {
|
||||
start = walker.currentNode;
|
||||
} else if (walker.currentNode.textContent == close) {
|
||||
end = walker.currentNode;
|
||||
instances.push([start, end]);
|
||||
start = undefined;
|
||||
end = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
for (const [start, end] of instances) {
|
||||
// build tree of current actual children
|
||||
const actualChildren = childrenFromRange(start.parentElement, start, end);
|
||||
const actions = [];
|
||||
for(const [start, end] of instances) {
|
||||
// build tree of current actual children
|
||||
const actualChildren = childrenFromRange(start.parentElement, start, end);
|
||||
const actions = [];
|
||||
|
||||
// build up the set of actions
|
||||
for (const patch of patches) {
|
||||
const child = childAtPath(
|
||||
actualChildren.length > 1 ? { children: actualChildren } : actualChildren[0],
|
||||
patch.path
|
||||
);
|
||||
const action = patch.action;
|
||||
if (action == "ClearChildren") {
|
||||
actions.push(() => {
|
||||
console.log("[HOT RELOAD] > ClearChildren", child.node);
|
||||
child.node.textContent = "";
|
||||
});
|
||||
} else if (action.ReplaceWith) {
|
||||
actions.push(() => {
|
||||
console.log("[HOT RELOAD] > ReplaceWith", child, action.ReplaceWith);
|
||||
const replacement = fromReplacementNode(action.ReplaceWith, actualChildren);
|
||||
if (child.node) {
|
||||
child.node.replaceWith(replacement);
|
||||
} else {
|
||||
const range = new Range();
|
||||
range.setStartAfter(child.start);
|
||||
range.setEndAfter(child.end);
|
||||
range.deleteContents();
|
||||
child.start.replaceWith(replacement);
|
||||
}
|
||||
});
|
||||
} else if (action.ChangeTagName) {
|
||||
const oldNode = child.node;
|
||||
actions.push(() => {
|
||||
console.log("[HOT RELOAD] > ChangeTagName", child.node, action.ChangeTagName);
|
||||
const newElement = document.createElement(action.ChangeTagName);
|
||||
for (const attr of oldNode.attributes) {
|
||||
newElement.setAttribute(attr.name, attr.value);
|
||||
}
|
||||
for (const childNode of child.node.childNodes) {
|
||||
newElement.appendChild(childNode);
|
||||
}
|
||||
|
||||
child.node.replaceWith(newElement);
|
||||
});
|
||||
} else if (action.RemoveAttribute) {
|
||||
actions.push(() => {
|
||||
console.log("[HOT RELOAD] > RemoveAttribute", child.node, action.RemoveAttribute);
|
||||
child.node.removeAttribute(action.RemoveAttribute);
|
||||
});
|
||||
} else if (action.SetAttribute) {
|
||||
const [name, value] = action.SetAttribute;
|
||||
actions.push(() => {
|
||||
console.log("[HOT RELOAD] > SetAttribute", child.node, action.SetAttribute);
|
||||
child.node.setAttribute(name, value);
|
||||
});
|
||||
} else if (action.SetText) {
|
||||
const node = child.node;
|
||||
actions.push(() => {
|
||||
console.log("[HOT RELOAD] > SetText", child.node, action.SetText);
|
||||
node.textContent = action.SetText;
|
||||
});
|
||||
} else if (action.AppendChildren) {
|
||||
actions.push(() => {
|
||||
console.log("[HOT RELOAD] > AppendChildren", child.node, action.AppendChildren);
|
||||
const newChildren = fromReplacementNode(action.AppendChildren, actualChildren);
|
||||
child.node.append(newChildren);
|
||||
});
|
||||
} else if (action.RemoveChild) {
|
||||
actions.push(() => {
|
||||
console.log("[HOT RELOAD] > RemoveChild", child.node, child.children, action.RemoveChild);
|
||||
const toRemove = child.children[action.RemoveChild.at];
|
||||
let toRemoveNode = toRemove.node;
|
||||
if (!toRemoveNode) {
|
||||
const range = new Range();
|
||||
range.setStartBefore(toRemove.start);
|
||||
range.setEndAfter(toRemove.end);
|
||||
toRemoveNode = range.deleteContents();
|
||||
} else {
|
||||
toRemoveNode.parentNode.removeChild(toRemoveNode);
|
||||
}
|
||||
});
|
||||
} else if (action.InsertChild) {
|
||||
const newChild = fromReplacementNode(action.InsertChild.child, actualChildren);
|
||||
let children = [];
|
||||
if (child.children) {
|
||||
children = child.children;
|
||||
} else if (child.start && child.end) {
|
||||
children = childrenFromRange(child.node || child.start.parentElement, start, end);
|
||||
} else {
|
||||
console.warn("InsertChildAfter could not build children.");
|
||||
}
|
||||
const before = children[action.InsertChild.before];
|
||||
actions.push(() => {
|
||||
console.log("[HOT RELOAD] > InsertChild", child, child.node, action.InsertChild, " before ", before);
|
||||
if (!before && child.node) {
|
||||
child.node.appendChild(newChild);
|
||||
} else {
|
||||
let node = child.node || child.end.parentElement;
|
||||
const reference = before ? before.node || before.start : child.end;
|
||||
node.insertBefore(newChild, reference);
|
||||
}
|
||||
});
|
||||
} else if (action.InsertChildAfter) {
|
||||
const newChild = fromReplacementNode(action.InsertChildAfter.child, actualChildren);
|
||||
let children = [];
|
||||
if (child.children) {
|
||||
children = child.children;
|
||||
} else if (child.start && child.end) {
|
||||
children = childrenFromRange(child.node || child.start.parentElement, start, end);
|
||||
} else {
|
||||
console.warn("InsertChildAfter could not build children.");
|
||||
}
|
||||
const after = children[action.InsertChildAfter.after];
|
||||
actions.push(() => {
|
||||
console.log(
|
||||
"[HOT RELOAD] > InsertChildAfter",
|
||||
child,
|
||||
child.node,
|
||||
action.InsertChildAfter,
|
||||
" after ",
|
||||
after
|
||||
);
|
||||
if (child.node && (!after || !(after.node || after.start).nextSibling)) {
|
||||
child.node.appendChild(newChild);
|
||||
} else {
|
||||
const node = child.node || child.end;
|
||||
const parent = node.nodeType === Node.COMMENT_NODE ? node.parentNode : node;
|
||||
if (!after) {
|
||||
parent.appendChild(newChild);
|
||||
} else {
|
||||
parent.insertBefore(newChild, (after.node || after.start).nextSibling);
|
||||
// build up the set of actions
|
||||
for (const patch of patches) {
|
||||
const child = childAtPath(
|
||||
actualChildren.length > 1 ? { children: actualChildren } : actualChildren[0],
|
||||
patch.path
|
||||
);
|
||||
const action = patch.action;
|
||||
if (action == "ClearChildren") {
|
||||
actions.push(() => {
|
||||
console.log("[HOT RELOAD] > ClearChildren", child.node);
|
||||
child.node.textContent = ""
|
||||
});
|
||||
} else if (action.ReplaceWith) {
|
||||
actions.push(() => {
|
||||
console.log("[HOT RELOAD] > ReplaceWith", child, action.ReplaceWith);
|
||||
const replacement = fromReplacementNode(action.ReplaceWith, actualChildren);
|
||||
if (child.node) {
|
||||
child.node.replaceWith(replacement)
|
||||
} else {
|
||||
const range = new Range();
|
||||
range.setStartAfter(child.start);
|
||||
range.setEndAfter(child.end);
|
||||
range.deleteContents();
|
||||
child.start.replaceWith(replacement);
|
||||
}
|
||||
});
|
||||
} else if (action.ChangeTagName) {
|
||||
const oldNode = child.node;
|
||||
actions.push(() => {
|
||||
console.log("[HOT RELOAD] > ChangeTagName", child.node, action.ChangeTagName);
|
||||
const newElement = document.createElement(action.ChangeTagName);
|
||||
for (const attr of oldNode.attributes) {
|
||||
newElement.setAttribute(attr.name, attr.value);
|
||||
}
|
||||
for (const childNode of child.node.childNodes) {
|
||||
newElement.appendChild(childNode);
|
||||
}
|
||||
|
||||
child.node.replaceWith(newElement)
|
||||
});
|
||||
} else if (action.RemoveAttribute) {
|
||||
actions.push(() => {
|
||||
console.log("[HOT RELOAD] > RemoveAttribute", child.node, action.RemoveAttribute);
|
||||
child.node.removeAttribute(action.RemoveAttribute);
|
||||
});
|
||||
} else if (action.SetAttribute) {
|
||||
const [name, value] = action.SetAttribute;
|
||||
actions.push(() => {
|
||||
console.log("[HOT RELOAD] > SetAttribute", child.node, action.SetAttribute);
|
||||
child.node.setAttribute(name, value);
|
||||
});
|
||||
} else if (action.SetText) {
|
||||
const node = child.node;
|
||||
actions.push(() => {
|
||||
console.log("[HOT RELOAD] > SetText", child.node, action.SetText);
|
||||
node.textContent = action.SetText
|
||||
});
|
||||
} else if (action.AppendChildren) {
|
||||
actions.push(() => {
|
||||
console.log("[HOT RELOAD] > AppendChildren", child.node, action.AppendChildren);
|
||||
const newChildren = fromReplacementNode(action.AppendChildren, actualChildren);
|
||||
child.node.append(newChildren);
|
||||
});
|
||||
} else if (action.RemoveChild) {
|
||||
actions.push(() => {
|
||||
console.log("[HOT RELOAD] > RemoveChild", child.node, child.children, action.RemoveChild);
|
||||
const toRemove = child.children[action.RemoveChild.at];
|
||||
let toRemoveNode = toRemove.node;
|
||||
if (!toRemoveNode) {
|
||||
const range = new Range();
|
||||
range.setStartBefore(toRemove.start);
|
||||
range.setEndAfter(toRemove.end);
|
||||
toRemoveNode = range.deleteContents();
|
||||
} else {
|
||||
toRemoveNode.parentNode.removeChild(toRemoveNode);
|
||||
}
|
||||
})
|
||||
} else if (action.InsertChild) {
|
||||
const newChild = fromReplacementNode(action.InsertChild.child, actualChildren);
|
||||
let children = [];
|
||||
if(child.children) {
|
||||
children = child.children;
|
||||
} else if (child.start && child.end) {
|
||||
children = childrenFromRange(child.node || child.start.parentElement, start, end);
|
||||
} else {
|
||||
console.warn("InsertChildAfter could not build children.");
|
||||
}
|
||||
const before = children[action.InsertChild.before];
|
||||
actions.push(() => {
|
||||
console.log("[HOT RELOAD] > InsertChild", child, child.node, action.InsertChild, " before ", before);
|
||||
if (!before && child.node) {
|
||||
child.node.appendChild(newChild);
|
||||
} else {
|
||||
let node = child.node || child.end.parentElement;
|
||||
const reference = before ? before.node || before.start : child.end;
|
||||
node.insertBefore(newChild, reference);
|
||||
}
|
||||
})
|
||||
} else if (action.InsertChildAfter) {
|
||||
const newChild = fromReplacementNode(action.InsertChildAfter.child, actualChildren);
|
||||
let children = [];
|
||||
if(child.children) {
|
||||
children = child.children;
|
||||
} else if (child.start && child.end) {
|
||||
children = childrenFromRange(child.node || child.start.parentElement, start, end);
|
||||
} else {
|
||||
console.warn("InsertChildAfter could not build children.");
|
||||
}
|
||||
const after = children[action.InsertChildAfter.after];
|
||||
actions.push(() => {
|
||||
console.log("[HOT RELOAD] > InsertChildAfter", child, child.node, action.InsertChildAfter, " after ", after);
|
||||
if (child.node && (!after || !(after.node || after.start).nextSibling)) {
|
||||
child.node.appendChild(newChild);
|
||||
} else {
|
||||
const node = child.node || child.end;
|
||||
const parent = node.nodeType === Node.COMMENT_NODE ? node.parentNode : node;
|
||||
if(!after) {
|
||||
parent.appendChild(newChild);
|
||||
} else {
|
||||
parent.insertBefore(newChild, (after.node || after.start).nextSibling);
|
||||
}
|
||||
}
|
||||
})
|
||||
} else {
|
||||
console.warn("[HOT RELOADING] Unmatched action", action);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
} else {
|
||||
console.warn("[HOT RELOADING] Unmatched action", action);
|
||||
}
|
||||
}
|
||||
|
||||
// actually run the actions
|
||||
// the reason we delay them is so that children aren't moved before other children are found, etc.
|
||||
for (const action of actions) {
|
||||
action();
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn("[HOT RELOADING] Error: ", e);
|
||||
}
|
||||
// actually run the actions
|
||||
// the reason we delay them is so that children aren't moved before other children are found, etc.
|
||||
for (const action of actions) {
|
||||
action();
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn("[HOT RELOADING] Error: ", e);
|
||||
}
|
||||
|
||||
function fromReplacementNode(node, actualChildren) {
|
||||
if (node.Html) {
|
||||
return fromHTML(node.Html);
|
||||
} else if (node.Fragment) {
|
||||
const frag = document.createDocumentFragment();
|
||||
for (const child of node.Fragment) {
|
||||
frag.appendChild(fromReplacementNode(child, actualChildren));
|
||||
}
|
||||
return frag;
|
||||
} else if (node.Element) {
|
||||
const element = document.createElement(node.Element.name);
|
||||
for (const [name, value] of node.Element.attrs) {
|
||||
element.setAttribute(name, value);
|
||||
}
|
||||
for (const child of node.Element.children) {
|
||||
element.appendChild(fromReplacementNode(child, actualChildren));
|
||||
}
|
||||
return element;
|
||||
} else {
|
||||
const child = childAtPath(
|
||||
actualChildren.length > 1 ? { children: actualChildren } : actualChildren[0],
|
||||
node.Path
|
||||
);
|
||||
if (child) {
|
||||
let childNode = child.node;
|
||||
if (!childNode) {
|
||||
const range = new Range();
|
||||
range.setStartBefore(child.start);
|
||||
range.setEndAfter(child.end);
|
||||
// okay this is somewhat silly
|
||||
// if we do cloneContents() here to return it,
|
||||
// we strip away the event listeners
|
||||
// if we're moving just one object, this is less than ideal
|
||||
// so I'm actually going to *extract* them, then clone and reinsert
|
||||
/* const toReinsert = range.cloneContents();
|
||||
function fromReplacementNode(node, actualChildren) {
|
||||
if (node.Html) {
|
||||
return fromHTML(node.Html);
|
||||
}
|
||||
else if (node.Fragment) {
|
||||
const frag = document.createDocumentFragment();
|
||||
for (const child of node.Fragment) {
|
||||
frag.appendChild(fromReplacementNode(child, actualChildren));
|
||||
}
|
||||
return frag;
|
||||
}
|
||||
else if (node.Element) {
|
||||
const element = document.createElement(node.Element.name);
|
||||
for (const [name, value] of node.Element.attrs) {
|
||||
element.setAttribute(name, value);
|
||||
}
|
||||
for (const child of node.Element.children) {
|
||||
element.appendChild(fromReplacementNode(child, actualChildren));
|
||||
}
|
||||
return element;
|
||||
}
|
||||
else {
|
||||
const child = childAtPath(
|
||||
actualChildren.length > 1 ? { children: actualChildren } : actualChildren[0],
|
||||
node.Path
|
||||
);
|
||||
if (child) {
|
||||
let childNode = child.node;
|
||||
if (!childNode) {
|
||||
const range = new Range();
|
||||
range.setStartBefore(child.start);
|
||||
range.setEndAfter(child.end);
|
||||
// okay this is somewhat silly
|
||||
// if we do cloneContents() here to return it,
|
||||
// we strip away the event listeners
|
||||
// if we're moving just one object, this is less than ideal
|
||||
// so I'm actually going to *extract* them, then clone and reinsert
|
||||
/* const toReinsert = range.cloneContents();
|
||||
if (child.end.nextSibling) {
|
||||
child.end.parentNode.insertBefore(toReinsert, child.end.nextSibling);
|
||||
} else {
|
||||
child.end.parentNode.appendChild(toReinsert);
|
||||
} */
|
||||
childNode = range.cloneContents();
|
||||
}
|
||||
return childNode;
|
||||
} else {
|
||||
console.warn("[HOT RELOADING] Could not find replacement node at ", node.Path);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
}
|
||||
childNode = range.cloneContents();
|
||||
}
|
||||
return childNode;
|
||||
} else {
|
||||
console.warn("[HOT RELOADING] Could not find replacement node at ", node.Path);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function buildActualChildren(element, range) {
|
||||
const walker = document.createTreeWalker(
|
||||
element,
|
||||
NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT | NodeFilter.SHOW_COMMENT,
|
||||
{
|
||||
acceptNode(node) {
|
||||
if (node.parentNode == element && (!range || range.isPointInRange(node, 0))) {
|
||||
return NodeFilter.FILTER_ACCEPT;
|
||||
} else {
|
||||
return NodeFilter.FILTER_REJECT;
|
||||
}
|
||||
},
|
||||
}
|
||||
);
|
||||
const actualChildren = [],
|
||||
elementCount = {};
|
||||
while (walker.nextNode()) {
|
||||
if (walker.currentNode.nodeType == Node.ELEMENT_NODE) {
|
||||
if (elementCount[walker.currentNode.nodeName]) {
|
||||
elementCount[walker.currentNode.nodeName] += 1;
|
||||
function buildActualChildren(element, range) {
|
||||
const walker = document.createTreeWalker(
|
||||
element,
|
||||
NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT | NodeFilter.SHOW_COMMENT,
|
||||
{
|
||||
acceptNode(node) {
|
||||
return node.parentNode == element && (!range || range.isPointInRange(node, 0));
|
||||
}
|
||||
}
|
||||
);
|
||||
const actualChildren = [],
|
||||
elementCount = {};
|
||||
while (walker.nextNode()) {
|
||||
if (walker.currentNode.nodeType == Node.ELEMENT_NODE) {
|
||||
if (elementCount[walker.currentNode.nodeName]) {
|
||||
elementCount[walker.currentNode.nodeName] += 1;
|
||||
} else {
|
||||
elementCount[walker.currentNode.nodeName] = 0;
|
||||
}
|
||||
elementCount[walker.currentNode.nodeName];
|
||||
|
||||
actualChildren.push({
|
||||
type: "element",
|
||||
name: walker.currentNode.nodeName,
|
||||
number: elementCount[walker.currentNode.nodeName],
|
||||
node: walker.currentNode,
|
||||
children: buildActualChildren(walker.currentNode)
|
||||
});
|
||||
} else if (walker.currentNode.nodeType == Node.TEXT_NODE) {
|
||||
actualChildren.push({
|
||||
type: "text",
|
||||
node: walker.currentNode
|
||||
});
|
||||
} else if (walker.currentNode.nodeType == Node.COMMENT_NODE) {
|
||||
if (walker.currentNode.textContent.trim().startsWith("leptos-view")) {
|
||||
if (walker.currentNode.textContent.trim().endsWith("-children|open")) {
|
||||
const startingName = walker.currentNode.textContent.trim();
|
||||
const componentName = startingName.replace("-children|open").replace("leptos-view|");
|
||||
const endingName = `leptos-view|${componentName}-children|close`;
|
||||
let start = walker.currentNode;
|
||||
let depth = 1;
|
||||
|
||||
while (walker.nextNode()) {
|
||||
if (walker.currentNode.textContent.trim() == endingName) {
|
||||
depth--;
|
||||
} else if (walker.currentNode.textContent.trim() == startingName) {
|
||||
depth++;
|
||||
}
|
||||
|
||||
if(depth == 0) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let end = walker.currentNode;
|
||||
actualChildren.push({
|
||||
type: "fragment",
|
||||
start: start.nextSibling,
|
||||
end: end.previousSibling,
|
||||
children: childrenFromRange(start.parentElement, start.nextSibling, end.previousSibling)
|
||||
});
|
||||
}
|
||||
} else if (walker.currentNode.textContent.trim() == "<() />") {
|
||||
actualChildren.push({
|
||||
type: "unit",
|
||||
node: walker.currentNode
|
||||
});
|
||||
} else if (walker.currentNode.textContent.trim() == "<DynChild>") {
|
||||
let start = walker.currentNode;
|
||||
let depth = 1;
|
||||
|
||||
while (walker.nextNode()) {
|
||||
if (walker.currentNode.textContent.trim() == "</DynChild>") {
|
||||
depth--;
|
||||
} else if (walker.currentNode.textContent.trim() == "<DynChild>") {
|
||||
depth++;
|
||||
}
|
||||
|
||||
if(depth == 0) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let end = walker.currentNode;
|
||||
actualChildren.push({
|
||||
type: "dyn-child",
|
||||
start, end
|
||||
});
|
||||
} else if (walker.currentNode.textContent.trim() == "<>") {
|
||||
let start = walker.currentNode;
|
||||
let depth = 1;
|
||||
|
||||
while (walker.nextNode()) {
|
||||
if (walker.currentNode.textContent.trim() == "</>") {
|
||||
depth--;
|
||||
} else if (walker.currentNode.textContent.trim() == "<>") {
|
||||
depth++;
|
||||
}
|
||||
|
||||
if(depth == 0) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let end = walker.currentNode;
|
||||
actualChildren.push({
|
||||
type: "fragment",
|
||||
children: childrenFromRange(start.parentElement, start, end),
|
||||
start, end
|
||||
});
|
||||
} else if (walker.currentNode.textContent.trim().startsWith("<")) {
|
||||
let componentName = walker.currentNode.textContent.trim();
|
||||
let endMarker = componentName.replace("<", "</");
|
||||
let depth = 1;
|
||||
let start = walker.currentNode;
|
||||
while (walker.nextNode()) {
|
||||
if (walker.currentNode.textContent.trim() == endMarker) {
|
||||
depth--;
|
||||
} else if (walker.currentNode.textContent.trim() == componentName) {
|
||||
depth++;
|
||||
}
|
||||
|
||||
if(depth == 0) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let end = walker.currentNode;
|
||||
actualChildren.push({
|
||||
type: "component",
|
||||
start, end
|
||||
});
|
||||
}
|
||||
} else {
|
||||
console.warn("[HOT RELOADING] Building children, encountered", walker.currentNode);
|
||||
}
|
||||
}
|
||||
return actualChildren;
|
||||
}
|
||||
|
||||
function childAtPath(element, path) {
|
||||
if (path.length == 0) {
|
||||
return element;
|
||||
} else if (element.children) {
|
||||
const next = element.children[path[0]],
|
||||
rest = path.slice(1);
|
||||
return childAtPath(next, rest);
|
||||
} else if (path == [0]) {
|
||||
return element;
|
||||
} else if (element.start && element.end) {
|
||||
const actualChildren = childrenFromRange(element.node || element.start.parentElement, element.start, element.end);
|
||||
return childAtPath({ children: actualChildren }, path);
|
||||
} else {
|
||||
elementCount[walker.currentNode.nodeName] = 0;
|
||||
}
|
||||
elementCount[walker.currentNode.nodeName];
|
||||
console.warn("[HOT RELOADING] Child at ", path, "not found in ", element);
|
||||
return element;
|
||||
}
|
||||
}
|
||||
|
||||
actualChildren.push({
|
||||
type: "element",
|
||||
name: walker.currentNode.nodeName,
|
||||
number: elementCount[walker.currentNode.nodeName],
|
||||
node: walker.currentNode,
|
||||
children: buildActualChildren(walker.currentNode),
|
||||
});
|
||||
} else if (walker.currentNode.nodeType == Node.TEXT_NODE) {
|
||||
actualChildren.push({
|
||||
type: "text",
|
||||
node: walker.currentNode,
|
||||
});
|
||||
} else if (walker.currentNode.nodeType == Node.COMMENT_NODE) {
|
||||
if (walker.currentNode.textContent.trim().startsWith("leptos-view")) {
|
||||
if (walker.currentNode.textContent.trim().endsWith("-children|open")) {
|
||||
const startingName = walker.currentNode.textContent.trim();
|
||||
const componentName = startingName.replace("-children|open").replace("leptos-view|");
|
||||
const endingName = `leptos-view|${componentName}-children|close`;
|
||||
let start = walker.currentNode;
|
||||
let depth = 1;
|
||||
|
||||
while (walker.nextNode()) {
|
||||
if (walker.currentNode.textContent.trim() == endingName) {
|
||||
depth--;
|
||||
} else if (walker.currentNode.textContent.trim() == startingName) {
|
||||
depth++;
|
||||
}
|
||||
|
||||
if (depth == 0) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let end = walker.currentNode;
|
||||
actualChildren.push({
|
||||
type: "fragment",
|
||||
start: start.nextSibling,
|
||||
end: end.previousSibling,
|
||||
children: childrenFromRange(start.parentElement, start.nextSibling, end.previousSibling),
|
||||
});
|
||||
}
|
||||
} else if (walker.currentNode.textContent.trim() == "<() />") {
|
||||
actualChildren.push({
|
||||
type: "unit",
|
||||
node: walker.currentNode,
|
||||
});
|
||||
} else if (walker.currentNode.textContent.trim() == "<DynChild>") {
|
||||
let start = walker.currentNode;
|
||||
let depth = 1;
|
||||
|
||||
while (walker.nextNode()) {
|
||||
if (walker.currentNode.textContent.trim() == "</DynChild>") {
|
||||
depth--;
|
||||
} else if (walker.currentNode.textContent.trim() == "<DynChild>") {
|
||||
depth++;
|
||||
}
|
||||
|
||||
if (depth == 0) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let end = walker.currentNode;
|
||||
actualChildren.push({
|
||||
type: "dyn-child",
|
||||
start,
|
||||
end,
|
||||
});
|
||||
} else if (walker.currentNode.textContent.trim() == "<>") {
|
||||
let start = walker.currentNode;
|
||||
let depth = 1;
|
||||
|
||||
while (walker.nextNode()) {
|
||||
if (walker.currentNode.textContent.trim() == "</>") {
|
||||
depth--;
|
||||
} else if (walker.currentNode.textContent.trim() == "<>") {
|
||||
depth++;
|
||||
}
|
||||
|
||||
if (depth == 0) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let end = walker.currentNode;
|
||||
actualChildren.push({
|
||||
type: "fragment",
|
||||
children: childrenFromRange(start.parentElement, start, end),
|
||||
start,
|
||||
end,
|
||||
});
|
||||
} else if (walker.currentNode.textContent.trim().startsWith("<")) {
|
||||
let componentName = walker.currentNode.textContent.trim();
|
||||
let endMarker = componentName.replace("<", "</");
|
||||
let depth = 1;
|
||||
let start = walker.currentNode;
|
||||
while (walker.nextNode()) {
|
||||
if (walker.currentNode.textContent.trim() == endMarker) {
|
||||
depth--;
|
||||
} else if (walker.currentNode.textContent.trim() == componentName) {
|
||||
depth++;
|
||||
}
|
||||
|
||||
if (depth == 0) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let end = walker.currentNode;
|
||||
actualChildren.push({
|
||||
type: "component",
|
||||
start,
|
||||
end,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
console.warn("[HOT RELOADING] Building children, encountered", walker.currentNode);
|
||||
}
|
||||
function childrenFromRange(parent, start, end) {
|
||||
const range = new Range();
|
||||
range.setStartAfter(start);
|
||||
range.setEndBefore(end);
|
||||
return buildActualChildren(parent, range);
|
||||
}
|
||||
return actualChildren;
|
||||
}
|
||||
|
||||
function childAtPath(element, path) {
|
||||
if (path.length == 0) {
|
||||
return element;
|
||||
} else if (element.children) {
|
||||
const next = element.children[path[0]],
|
||||
rest = path.slice(1);
|
||||
return childAtPath(next, rest);
|
||||
} else if (path == [0]) {
|
||||
return element;
|
||||
} else if (element.start && element.end) {
|
||||
const actualChildren = childrenFromRange(element.node || element.start.parentElement, element.start, element.end);
|
||||
return childAtPath({ children: actualChildren }, path);
|
||||
} else {
|
||||
console.warn("[HOT RELOADING] Child at ", path, "not found in ", element);
|
||||
return element;
|
||||
}
|
||||
}
|
||||
|
||||
function childrenFromRange(parent, start, end) {
|
||||
const range = new Range();
|
||||
range.setStartAfter(start);
|
||||
range.setEndBefore(end);
|
||||
return buildActualChildren(parent, range);
|
||||
}
|
||||
|
||||
function fromHTML(html) {
|
||||
const template = document.createElement("template");
|
||||
template.innerHTML = html;
|
||||
return template.content.cloneNode(true);
|
||||
}
|
||||
function fromHTML(html) {
|
||||
const template = document.createElement("template");
|
||||
template.innerHTML = html;
|
||||
return template.content.cloneNode(true);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ proc-macro-error = "1"
|
||||
proc-macro2 = "1"
|
||||
quote = "1"
|
||||
syn = { version = "2", features = ["full"] }
|
||||
rstml = "0.11.0"
|
||||
rstml = "0.10.6"
|
||||
leptos_hot_reload = { workspace = true }
|
||||
server_fn_macro = { workspace = true }
|
||||
convert_case = "0.6.0"
|
||||
|
||||
@@ -169,26 +169,14 @@ mod template;
|
||||
/// # });
|
||||
/// ```
|
||||
///
|
||||
/// Class names can include dashes, and since leptos v0.5.0 can include a dash-separated segment of only numbers.
|
||||
/// ```rust
|
||||
/// # use leptos::*;
|
||||
/// # run_scope(create_runtime(), |cx| {
|
||||
/// # if !cfg!(any(feature = "csr", feature = "hydrate")) {
|
||||
/// let (count, set_count) = create_signal(cx, 2);
|
||||
/// view! { cx, <div class:hidden-div-25={move || count.get() < 3}>"Now you see me, now you don’t."</div> }
|
||||
/// # ;
|
||||
/// # }
|
||||
/// # });
|
||||
/// ```
|
||||
///
|
||||
/// Class names cannot include special symbols.
|
||||
/// Class names can include dashes, but cannot (at the moment) include a dash-separated segment of only numbers.
|
||||
/// ```rust,compile_fail
|
||||
/// # use leptos::*;
|
||||
/// # run_scope(create_runtime(), |cx| {
|
||||
/// # if !cfg!(any(feature = "csr", feature = "hydrate")) {
|
||||
/// let (count, set_count) = create_signal(cx, 2);
|
||||
/// // class:hidden-[div]-25 is invalid attribute name
|
||||
/// view! { cx, <div class:hidden-[div]-25={move || count.get() < 3}>"Now you see me, now you don’t."</div> }
|
||||
/// // `hidden-div-25` is invalid at the moment
|
||||
/// view! { cx, <div class:hidden-div-25={move || count.get() < 3}>"Now you see me, now you don’t."</div> }
|
||||
/// # ;
|
||||
/// # }
|
||||
/// # });
|
||||
@@ -933,8 +921,8 @@ pub fn params_derive(
|
||||
}
|
||||
|
||||
pub(crate) fn attribute_value(attr: &KeyedAttribute) -> &syn::Expr {
|
||||
match attr.value() {
|
||||
Some(value) => value,
|
||||
match &attr.possible_value {
|
||||
Some(value) => &value.value,
|
||||
None => abort!(attr.key, "attribute should have value"),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -351,10 +351,7 @@ fn root_element_to_tokens_ssr(
|
||||
Ident::new("Custom", Span::call_site())
|
||||
} else {
|
||||
let camel_cased = camel_case_tag_name(
|
||||
tag_name
|
||||
.trim_start_matches("svg::")
|
||||
.trim_start_matches("math::")
|
||||
.trim_end_matches('_'),
|
||||
&tag_name.replace("svg::", "").replace("math::", ""),
|
||||
);
|
||||
Ident::new(&camel_cased, Span::call_site())
|
||||
};
|
||||
@@ -520,17 +517,6 @@ fn element_to_tokens_ssr(
|
||||
&value.replace('{', "\\{").replace('}', "\\}"),
|
||||
);
|
||||
}
|
||||
Node::RawText(r) => {
|
||||
let value = r.to_string_best();
|
||||
let value = if is_script_or_style {
|
||||
value.into()
|
||||
} else {
|
||||
html_escape::encode_safe(&value)
|
||||
};
|
||||
template.push_str(
|
||||
&value.replace('{', "\\{").replace('}', "\\}"),
|
||||
);
|
||||
}
|
||||
Node::Block(NodeBlock::ValidBlock(block)) => {
|
||||
if let Some(value) =
|
||||
block_to_primitive_expression(block)
|
||||
@@ -565,7 +551,7 @@ fn element_to_tokens_ssr(
|
||||
}
|
||||
|
||||
template.push_str("</");
|
||||
template.push_str(tag_name);
|
||||
template.push_str(&node.name().to_string());
|
||||
template.push('>');
|
||||
}
|
||||
}
|
||||
@@ -1239,7 +1225,7 @@ fn attribute_to_tokens(
|
||||
};
|
||||
let undelegated_ident = match &node.key {
|
||||
NodeName::Punctuated(parts) => parts.last().and_then(|last| {
|
||||
if last.to_string() == "undelegated" {
|
||||
if last == "undelegated" {
|
||||
Some(last)
|
||||
} else {
|
||||
None
|
||||
@@ -1260,8 +1246,9 @@ fn attribute_to_tokens(
|
||||
let event_type = if is_custom {
|
||||
event_type
|
||||
} else if let Some(ev_name) = event_name_ident {
|
||||
quote! {
|
||||
#ev_name
|
||||
let span = ev_name.span();
|
||||
quote_spanned! {
|
||||
span => #ev_name
|
||||
}
|
||||
} else {
|
||||
event_type
|
||||
@@ -1269,8 +1256,9 @@ fn attribute_to_tokens(
|
||||
|
||||
let event_type = if is_force_undelegated {
|
||||
let undelegated = if let Some(undelegated) = undelegated_ident {
|
||||
quote! {
|
||||
#undelegated
|
||||
let span = undelegated.span();
|
||||
quote_spanned! {
|
||||
span => #undelegated
|
||||
}
|
||||
} else {
|
||||
quote! { undelegated }
|
||||
@@ -1853,7 +1841,11 @@ fn is_self_closing(node: &NodeElement) -> bool {
|
||||
fn camel_case_tag_name(tag_name: &str) -> String {
|
||||
let mut chars = tag_name.chars();
|
||||
let first = chars.next();
|
||||
let underscore = if tag_name == "option" { "_" } else { "" };
|
||||
let underscore = if tag_name == "option" || tag_name == "use" {
|
||||
"_"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
first
|
||||
.map(|f| f.to_ascii_uppercase())
|
||||
.into_iter()
|
||||
|
||||
@@ -57,15 +57,15 @@ use std::{any::Any, cell::RefCell, fmt, marker::PhantomData, rc::Rc};
|
||||
/// });
|
||||
///
|
||||
/// // instead, we create a memo
|
||||
/// // ✅ creation: the computation does not run on creation, because memos are lazy
|
||||
/// // 🆗 run #1: the calculation runs once immediately
|
||||
/// let memoized = create_memo(cx, move |_| really_expensive_computation(value.get()));
|
||||
/// create_effect(cx, move |_| {
|
||||
/// // 🆗 run #1: reading the memo for the first time causes the computation to run for the first time
|
||||
/// // 🆗 reads the current value of the memo
|
||||
/// // can be `memoized()` on nightly
|
||||
/// log::debug!("memoized = {}", memoized.get());
|
||||
/// });
|
||||
/// create_effect(cx, move |_| {
|
||||
/// // ✅ reads the current value again **without re-running the calculation**
|
||||
/// // ✅ reads the current value **without re-running the calculation**
|
||||
/// let value = memoized.get();
|
||||
/// // do something else...
|
||||
/// });
|
||||
@@ -149,15 +149,15 @@ where
|
||||
/// });
|
||||
///
|
||||
/// // instead, we create a memo
|
||||
// // ✅ creation: the computation does not run on creation, because memos are lazy
|
||||
/// // 🆗 run #1: the calculation runs once immediately
|
||||
/// let memoized = create_memo(cx, move |_| really_expensive_computation(value.get()));
|
||||
/// create_effect(cx, move |_| {
|
||||
/// // 🆗 run #1: reading the memo for the first time causes the computation to run for the first time
|
||||
/// // can be `memoized()` on nightly
|
||||
/// // 🆗 reads the current value of the memo
|
||||
/// log::debug!("memoized = {}", memoized.get());
|
||||
/// });
|
||||
/// create_effect(cx, move |_| {
|
||||
/// // ✅ reads the current value again **without re-running the calculation**
|
||||
/// // ✅ reads the current value **without re-running the calculation**
|
||||
/// // can be `memoized()` on nightly
|
||||
/// let value = memoized.get();
|
||||
/// // do something else...
|
||||
/// });
|
||||
@@ -179,7 +179,13 @@ where
|
||||
T: 'static,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
*self
|
||||
Self {
|
||||
runtime: self.runtime,
|
||||
id: self.id,
|
||||
ty: PhantomData,
|
||||
#[cfg(any(debug_assertions, feature = "ssr"))]
|
||||
defined_at: self.defined_at,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -6,8 +6,8 @@ use crate::{
|
||||
serialization::Serializable,
|
||||
spawn::spawn_local,
|
||||
use_context, GlobalSuspenseContext, Memo, ReadSignal, Scope, ScopeProperty,
|
||||
SignalDispose, SignalGetUntracked, SignalSet, SignalUpdate, SignalWith,
|
||||
SuspenseContext, WriteSignal,
|
||||
SignalGetUntracked, SignalSet, SignalUpdate, SignalWith, SuspenseContext,
|
||||
WriteSignal,
|
||||
};
|
||||
use std::{
|
||||
any::Any,
|
||||
@@ -237,7 +237,7 @@ where
|
||||
id,
|
||||
source_ty: PhantomData,
|
||||
out_ty: PhantomData,
|
||||
#[cfg(any(debug_assertions, feature = "ssr"))]
|
||||
#[cfg(any(debug_assertions, features = "ssr"))]
|
||||
defined_at: std::panic::Location::caller(),
|
||||
}
|
||||
}
|
||||
@@ -373,7 +373,7 @@ where
|
||||
id,
|
||||
source_ty: PhantomData,
|
||||
out_ty: PhantomData,
|
||||
#[cfg(any(debug_assertions, feature = "ssr"))]
|
||||
#[cfg(any(debug_assertions, features = "ssr"))]
|
||||
defined_at: std::panic::Location::caller(),
|
||||
}
|
||||
}
|
||||
@@ -719,7 +719,7 @@ where
|
||||
pub(crate) id: ResourceId,
|
||||
pub(crate) source_ty: PhantomData<S>,
|
||||
pub(crate) out_ty: PhantomData<T>,
|
||||
#[cfg(any(debug_assertions, feature = "ssr"))]
|
||||
#[cfg(any(debug_assertions, features = "ssr"))]
|
||||
pub(crate) defined_at: &'static std::panic::Location<'static>,
|
||||
}
|
||||
|
||||
@@ -734,8 +734,19 @@ where
|
||||
S: 'static,
|
||||
T: 'static,
|
||||
{
|
||||
#[cfg_attr(
|
||||
any(debug_assertions, feature = "ssr"),
|
||||
instrument(level = "trace", skip_all,)
|
||||
)]
|
||||
fn clone(&self) -> Self {
|
||||
*self
|
||||
Self {
|
||||
runtime: self.runtime,
|
||||
id: self.id,
|
||||
source_ty: PhantomData,
|
||||
out_ty: PhantomData,
|
||||
#[cfg(any(debug_assertions, features = "ssr"))]
|
||||
defined_at: self.defined_at,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1082,25 +1093,3 @@ thread_local! {
|
||||
pub fn suppress_resource_load(suppress: bool) {
|
||||
SUPPRESS_RESOURCE_LOAD.with(|w| w.set(suppress));
|
||||
}
|
||||
|
||||
impl<S, T> SignalDispose for Resource<S, T>
|
||||
where
|
||||
S: 'static,
|
||||
T: 'static,
|
||||
{
|
||||
#[track_caller]
|
||||
fn dispose(self) {
|
||||
let res = with_runtime(self.runtime, |runtime| {
|
||||
let mut resources = runtime.resources.borrow_mut();
|
||||
resources.remove(self.id)
|
||||
});
|
||||
if res.ok().flatten().is_none() {
|
||||
crate::macros::debug_warn!(
|
||||
"At {}, you are calling Resource::dispose() on a resource \
|
||||
that no longer exists, probably because its Scope has \
|
||||
already been disposed.",
|
||||
std::panic::Location::caller()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -415,12 +415,11 @@ pub struct RuntimeId;
|
||||
impl RuntimeId {
|
||||
/// Removes the runtime, disposing all its child [`Scope`](crate::Scope)s.
|
||||
pub fn dispose(self) {
|
||||
#[cfg(not(any(feature = "csr", feature = "hydrate")))]
|
||||
{
|
||||
let runtime = RUNTIMES.with(move |runtimes| runtimes.borrow_mut().remove(self))
|
||||
.expect("Attempted to dispose of a reactive runtime that was not found. This suggests \
|
||||
a possible memory leak. Please open an issue with details at https://github.com/leptos-rs/leptos");
|
||||
drop(runtime);
|
||||
cfg_if! {
|
||||
if #[cfg(not(any(feature = "csr", feature = "hydrate")))] {
|
||||
let runtime = RUNTIMES.with(move |runtimes| runtimes.borrow_mut().remove(self));
|
||||
drop(runtime);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -476,7 +475,7 @@ impl RuntimeId {
|
||||
}
|
||||
|
||||
#[cfg_attr(
|
||||
any(debug_assertions, feature = "ssr"),
|
||||
any(debug_assertions, features = "ssr"),
|
||||
instrument(level = "trace", skip_all,)
|
||||
)]
|
||||
#[inline(always)]
|
||||
|
||||
@@ -37,7 +37,7 @@ pub fn create_scope(
|
||||
///
|
||||
/// You usually don't need to call this manually.
|
||||
#[cfg_attr(
|
||||
any(debug_assertions, feature = "ssr"),
|
||||
any(debug_assertions, features = "ssr"),
|
||||
instrument(level = "trace", skip_all,)
|
||||
)]
|
||||
pub fn raw_scope_and_disposer(runtime: RuntimeId) -> (Scope, ScopeDisposer) {
|
||||
@@ -52,7 +52,7 @@ pub fn raw_scope_and_disposer(runtime: RuntimeId) -> (Scope, ScopeDisposer) {
|
||||
///
|
||||
/// You usually don't need to call this manually.
|
||||
#[cfg_attr(
|
||||
any(debug_assertions, feature = "ssr"),
|
||||
any(debug_assertions, features = "ssr"),
|
||||
instrument(level = "trace", skip_all,)
|
||||
)]
|
||||
pub fn run_scope<T>(
|
||||
@@ -69,7 +69,7 @@ pub fn run_scope<T>(
|
||||
///
|
||||
/// You usually don't need to call this manually.
|
||||
#[cfg_attr(
|
||||
any(debug_assertions, feature = "ssr"),
|
||||
any(debug_assertions, features = "ssr"),
|
||||
instrument(level = "trace", skip_all,)
|
||||
)]
|
||||
pub fn run_scope_undisposed<T>(
|
||||
@@ -128,7 +128,7 @@ impl Scope {
|
||||
/// dispose of them when they are no longer needed (e.g., a list item has been destroyed or the user
|
||||
/// has navigated away from the route.)
|
||||
#[cfg_attr(
|
||||
any(debug_assertions, feature = "ssr"),
|
||||
any(debug_assertions, features = "ssr"),
|
||||
instrument(level = "trace", skip_all,)
|
||||
)]
|
||||
#[inline(always)]
|
||||
@@ -147,7 +147,7 @@ impl Scope {
|
||||
/// dispose of them when they are no longer needed (e.g., a list item has been destroyed or the user
|
||||
/// has navigated away from the route.)
|
||||
#[cfg_attr(
|
||||
any(debug_assertions, feature = "ssr"),
|
||||
any(debug_assertions, features = "ssr"),
|
||||
instrument(level = "trace", skip_all,)
|
||||
)]
|
||||
#[inline(always)]
|
||||
@@ -203,7 +203,7 @@ impl Scope {
|
||||
/// # });
|
||||
/// ```
|
||||
#[cfg_attr(
|
||||
any(debug_assertions, feature = "ssr"),
|
||||
any(debug_assertions, features = "ssr"),
|
||||
instrument(level = "trace", skip_all,)
|
||||
)]
|
||||
#[inline(always)]
|
||||
@@ -229,7 +229,7 @@ impl Scope {
|
||||
/// 2. run all cleanup functions defined for this scope by [`on_cleanup`](crate::on_cleanup).
|
||||
/// 3. dispose of all signals, effects, and resources owned by this `Scope`.
|
||||
#[cfg_attr(
|
||||
any(debug_assertions, feature = "ssr"),
|
||||
any(debug_assertions, features = "ssr"),
|
||||
instrument(level = "trace", skip_all,)
|
||||
)]
|
||||
pub fn dispose(self) {
|
||||
@@ -306,7 +306,7 @@ impl Scope {
|
||||
})
|
||||
}
|
||||
#[cfg_attr(
|
||||
any(debug_assertions, feature = "ssr"),
|
||||
any(debug_assertions, features = "ssr"),
|
||||
instrument(level = "trace", skip_all,)
|
||||
)]
|
||||
pub(crate) fn push_scope_property(&self, prop: ScopeProperty) {
|
||||
@@ -322,7 +322,7 @@ impl Scope {
|
||||
})
|
||||
}
|
||||
#[cfg_attr(
|
||||
any(debug_assertions, feature = "ssr"),
|
||||
any(debug_assertions, features = "ssr"),
|
||||
instrument(level = "trace", skip_all,)
|
||||
)]
|
||||
pub(crate) fn remove_scope_property(&self, prop: ScopeProperty) {
|
||||
@@ -343,7 +343,7 @@ impl Scope {
|
||||
})
|
||||
}
|
||||
#[cfg_attr(
|
||||
any(debug_assertions, feature = "ssr"),
|
||||
any(debug_assertions, features = "ssr"),
|
||||
instrument(level = "trace", skip_all,)
|
||||
)]
|
||||
/// Returns the the parent Scope, if any.
|
||||
@@ -361,7 +361,7 @@ impl Scope {
|
||||
}
|
||||
|
||||
#[cfg_attr(
|
||||
any(debug_assertions, feature = "ssr"),
|
||||
any(debug_assertions, features = "ssr"),
|
||||
instrument(level = "trace", skip_all,)
|
||||
)]
|
||||
fn push_cleanup(cx: Scope, cleanup_fn: Box<dyn FnOnce()>) {
|
||||
@@ -424,7 +424,7 @@ impl ScopeDisposer {
|
||||
impl Scope {
|
||||
/// Returns IDs for all [`Resource`](crate::Resource)s found on any scope.
|
||||
#[cfg_attr(
|
||||
any(debug_assertions, feature = "ssr"),
|
||||
any(debug_assertions, features = "ssr"),
|
||||
instrument(level = "trace", skip_all,)
|
||||
)]
|
||||
pub fn all_resources(&self) -> Vec<ResourceId> {
|
||||
@@ -435,7 +435,7 @@ impl Scope {
|
||||
/// Returns IDs for all [`Resource`](crate::Resource)s found on any scope that are
|
||||
/// pending from the server.
|
||||
#[cfg_attr(
|
||||
any(debug_assertions, feature = "ssr"),
|
||||
any(debug_assertions, features = "ssr"),
|
||||
instrument(level = "trace", skip_all,)
|
||||
)]
|
||||
pub fn pending_resources(&self) -> Vec<ResourceId> {
|
||||
@@ -445,7 +445,7 @@ impl Scope {
|
||||
|
||||
/// Returns IDs for all [`Resource`](crate::Resource)s found on any scope.
|
||||
#[cfg_attr(
|
||||
any(debug_assertions, feature = "ssr"),
|
||||
any(debug_assertions, features = "ssr"),
|
||||
instrument(level = "trace", skip_all,)
|
||||
)]
|
||||
pub fn serialization_resolvers(
|
||||
@@ -460,7 +460,7 @@ impl Scope {
|
||||
/// Registers the given [`SuspenseContext`](crate::SuspenseContext) with the current scope,
|
||||
/// calling the `resolver` when its resources are all resolved.
|
||||
#[cfg_attr(
|
||||
any(debug_assertions, feature = "ssr"),
|
||||
any(debug_assertions, features = "ssr"),
|
||||
instrument(level = "trace", skip_all,)
|
||||
)]
|
||||
pub fn register_suspense(
|
||||
@@ -517,7 +517,7 @@ impl Scope {
|
||||
/// The keys are hydration IDs. Values are tuples of two pinned
|
||||
/// `Future`s that return content for out-of-order and in-order streaming, respectively.
|
||||
#[cfg_attr(
|
||||
any(debug_assertions, feature = "ssr"),
|
||||
any(debug_assertions, features = "ssr"),
|
||||
instrument(level = "trace", skip_all,)
|
||||
)]
|
||||
pub fn pending_fragments(&self) -> HashMap<String, FragmentData> {
|
||||
@@ -530,7 +530,7 @@ impl Scope {
|
||||
|
||||
/// A future that will resolve when all blocking fragments are ready.
|
||||
#[cfg_attr(
|
||||
any(debug_assertions, feature = "ssr"),
|
||||
any(debug_assertions, features = "ssr"),
|
||||
instrument(level = "trace", skip_all,)
|
||||
)]
|
||||
pub fn blocking_fragments_ready(self) -> PinnedFuture<()> {
|
||||
@@ -557,7 +557,7 @@ impl Scope {
|
||||
/// Returns a tuple of two pinned `Future`s that return content for out-of-order
|
||||
/// and in-order streaming, respectively.
|
||||
#[cfg_attr(
|
||||
any(debug_assertions, feature = "ssr"),
|
||||
any(debug_assertions, features = "ssr"),
|
||||
instrument(level = "trace", skip_all,)
|
||||
)]
|
||||
pub fn take_pending_fragment(&self, id: &str) -> Option<FragmentData> {
|
||||
@@ -576,7 +576,7 @@ impl Scope {
|
||||
/// # Panics
|
||||
/// Panics if the runtime this scope belongs to has already been disposed.
|
||||
#[cfg_attr(
|
||||
any(debug_assertions, feature = "ssr"),
|
||||
any(debug_assertions, features = "ssr"),
|
||||
instrument(level = "trace", skip_all,)
|
||||
)]
|
||||
#[inline(always)]
|
||||
|
||||
@@ -95,7 +95,7 @@ cfg_if! {
|
||||
|
||||
fn de(json: &str) -> Result<Self, SerializationError> {
|
||||
let intermediate =
|
||||
serde_json::from_str(json).map_err(|e| SerializationError::Deserialize(Rc::new(e)))?;
|
||||
serde_json::from_str(&json).map_err(|e| SerializationError::Deserialize(Rc::new(e)))?;
|
||||
Self::deserialize(&intermediate).map_err(|e| SerializationError::Deserialize(Rc::new(e)))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2059,11 +2059,11 @@ impl NodeId {
|
||||
debug_warn!(
|
||||
"[Signal::update] You’re trying to update a \
|
||||
Signal<{}> (defined at {defined_at}) that has \
|
||||
already been disposed of. This is probably a \
|
||||
logic error in a component that creates and \
|
||||
disposes of scopes. If it does not cause any \
|
||||
issues, it is safe to ignore this warning, which \
|
||||
occurs only in debug mode.",
|
||||
already been disposed of. This is probably \
|
||||
either a logic error in a component that creates \
|
||||
and disposes of scopes. If it does cause cause \
|
||||
any issues, it is safe to ignore this warning, \
|
||||
which occurs only in debug mode.",
|
||||
std::any::type_name::<T>()
|
||||
);
|
||||
}
|
||||
@@ -2106,11 +2106,11 @@ impl NodeId {
|
||||
debug_warn!(
|
||||
"[Signal::update] You’re trying to update a \
|
||||
Signal<{}> (defined at {defined_at}) that has \
|
||||
already been disposed of. This is probably a \
|
||||
logic error in a component that creates and \
|
||||
disposes of scopes. If it does not cause any \
|
||||
issues, it is safe to ignore this warning, which \
|
||||
occurs only in debug mode.",
|
||||
already been disposed of. This is probably \
|
||||
either a logic error in a component that creates \
|
||||
and disposes of scopes. If it does cause cause \
|
||||
any issues, it is safe to ignore this warning, \
|
||||
which occurs only in debug mode.",
|
||||
std::any::type_name::<T>()
|
||||
);
|
||||
}
|
||||
|
||||
@@ -71,7 +71,11 @@ where
|
||||
|
||||
impl<T> Clone for Signal<T> {
|
||||
fn clone(&self) -> Self {
|
||||
*self
|
||||
Self {
|
||||
inner: self.inner,
|
||||
#[cfg(any(debug_assertions, feature = "ssr"))]
|
||||
defined_at: self.defined_at,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -432,7 +436,13 @@ where
|
||||
|
||||
impl<T> Clone for SignalTypes<T> {
|
||||
fn clone(&self) -> Self {
|
||||
*self
|
||||
match self {
|
||||
Self::ReadSignal(arg0) => Self::ReadSignal(*arg0),
|
||||
Self::Memo(arg0) => Self::Memo(*arg0),
|
||||
Self::DerivedSignal(arg0, arg1) => {
|
||||
Self::DerivedSignal(*arg0, *arg1)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -63,7 +63,11 @@ where
|
||||
|
||||
impl<T> Clone for SignalSetter<T> {
|
||||
fn clone(&self) -> Self {
|
||||
*self
|
||||
Self {
|
||||
inner: self.inner,
|
||||
#[cfg(any(debug_assertions, feature = "ssr"))]
|
||||
defined_at: self.defined_at,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -227,7 +231,11 @@ where
|
||||
|
||||
impl<T> Clone for SignalSetterTypes<T> {
|
||||
fn clone(&self) -> Self {
|
||||
*self
|
||||
match self {
|
||||
Self::Write(arg0) => Self::Write(*arg0),
|
||||
Self::Mapped(cx, f) => Self::Mapped(*cx, *f),
|
||||
Self::Default => Self::Default,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -33,7 +33,11 @@ where
|
||||
|
||||
impl<T> Clone for StoredValue<T> {
|
||||
fn clone(&self) -> Self {
|
||||
*self
|
||||
Self {
|
||||
runtime: self.runtime,
|
||||
id: self.id,
|
||||
ty: self.ty,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -190,10 +194,8 @@ impl<T> StoredValue<T> {
|
||||
/// stored value has not yet been disposed, [`None`] otherwise.
|
||||
pub fn try_update_value<O>(self, f: impl FnOnce(&mut T) -> O) -> Option<O> {
|
||||
with_runtime(self.runtime, |runtime| {
|
||||
let value = {
|
||||
let values = runtime.stored_values.borrow();
|
||||
values.get(self.id)?.clone()
|
||||
};
|
||||
let values = runtime.stored_values.borrow();
|
||||
let value = values.get(self.id)?;
|
||||
let mut value = value.borrow_mut();
|
||||
let value = value.downcast_mut::<T>()?;
|
||||
Some(f(value))
|
||||
@@ -226,20 +228,13 @@ impl<T> StoredValue<T> {
|
||||
/// stored value has not yet been disposed, [`Some(T)`] otherwise.
|
||||
pub fn try_set_value(&self, value: T) -> Option<T> {
|
||||
with_runtime(self.runtime, |runtime| {
|
||||
let n = {
|
||||
let values = runtime.stored_values.borrow();
|
||||
values.get(self.id).map(Rc::clone)
|
||||
};
|
||||
|
||||
let values = runtime.stored_values.borrow();
|
||||
let n = values.get(self.id);
|
||||
let mut n = n.map(|n| n.borrow_mut());
|
||||
let n = n.as_mut().and_then(|n| n.downcast_mut::<T>());
|
||||
if let Some(n) = n {
|
||||
let mut n = n.borrow_mut();
|
||||
let n = n.downcast_mut::<T>();
|
||||
if let Some(n) = n {
|
||||
*n = value;
|
||||
None
|
||||
} else {
|
||||
Some(value)
|
||||
}
|
||||
*n = value;
|
||||
None
|
||||
} else {
|
||||
Some(value)
|
||||
}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
use crate::{Scope, ScopeProperty};
|
||||
|
||||
/// A version of [`create_effect`](crate::create_effect) that listens to any dependency that is accessed inside `deps` and returns
|
||||
/// A version of [`create_effect`] that listens to any dependency that is accessed inside `deps` and returns
|
||||
/// a stop handler.
|
||||
/// The return value of `deps` is passed into `callback` as an argument together with the previous value.
|
||||
/// Additionally the last return value of `callback` is provided as a third argument as is done in [`create_effect`](crate::create_effect).
|
||||
/// Additionally the last return value of `callback` is provided as a third argument as is done in [`create_effect`].
|
||||
///
|
||||
/// ## Usage
|
||||
///
|
||||
|
||||
@@ -187,7 +187,7 @@ where
|
||||
O: 'static,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
*self
|
||||
Self(self.0)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -77,7 +77,7 @@ where
|
||||
O: 'static,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
*self
|
||||
Self(self.0)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -95,7 +95,7 @@ where
|
||||
{
|
||||
/// Calls the `async` function with a reference to the input type as its argument.
|
||||
#[cfg_attr(
|
||||
any(debug_assertions, feature = "ssr"),
|
||||
any(debug_assertions, features = "ssr"),
|
||||
tracing::instrument(level = "trace", skip_all,)
|
||||
)]
|
||||
pub fn dispatch(&self, input: I) {
|
||||
@@ -104,7 +104,7 @@ where
|
||||
|
||||
/// The set of all submissions to this multi-action.
|
||||
#[cfg_attr(
|
||||
any(debug_assertions, feature = "ssr"),
|
||||
any(debug_assertions, features = "ssr"),
|
||||
tracing::instrument(level = "trace", skip_all,)
|
||||
)]
|
||||
pub fn submissions(&self) -> ReadSignal<Vec<Submission<I, O>>> {
|
||||
@@ -119,7 +119,7 @@ where
|
||||
|
||||
/// How many times an action has successfully resolved.
|
||||
#[cfg_attr(
|
||||
any(debug_assertions, feature = "ssr"),
|
||||
any(debug_assertions, features = "ssr"),
|
||||
tracing::instrument(level = "trace", skip_all,)
|
||||
)]
|
||||
pub fn version(&self) -> RwSignal<usize> {
|
||||
@@ -129,7 +129,7 @@ where
|
||||
/// Associates the URL of the given server function with this action.
|
||||
/// This enables integration with the `MultiActionForm` component in `leptos_router`.
|
||||
#[cfg_attr(
|
||||
any(debug_assertions, feature = "ssr"),
|
||||
any(debug_assertions, features = "ssr"),
|
||||
tracing::instrument(level = "trace", skip_all,)
|
||||
)]
|
||||
pub fn using_server_fn<T: ServerFn>(self) -> Self {
|
||||
@@ -178,7 +178,12 @@ where
|
||||
|
||||
impl<I, O> Clone for Submission<I, O> {
|
||||
fn clone(&self) -> Self {
|
||||
*self
|
||||
Self {
|
||||
input: self.input,
|
||||
value: self.value,
|
||||
pending: self.pending,
|
||||
canceled: self.canceled,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -207,7 +212,7 @@ where
|
||||
{
|
||||
/// Calls the `async` function with a reference to the input type as its argument.
|
||||
#[cfg_attr(
|
||||
any(debug_assertions, feature = "ssr"),
|
||||
any(debug_assertions, features = "ssr"),
|
||||
tracing::instrument(level = "trace", skip_all,)
|
||||
)]
|
||||
pub fn dispatch(&self, input: I) {
|
||||
@@ -299,7 +304,7 @@ where
|
||||
/// # });
|
||||
/// ```
|
||||
#[cfg_attr(
|
||||
any(debug_assertions, feature = "ssr"),
|
||||
any(debug_assertions, features = "ssr"),
|
||||
tracing::instrument(level = "trace", skip_all,)
|
||||
)]
|
||||
pub fn create_multi_action<I, O, F, Fu>(
|
||||
@@ -346,7 +351,7 @@ where
|
||||
/// # });
|
||||
/// ```
|
||||
#[cfg_attr(
|
||||
any(debug_assertions, feature = "ssr"),
|
||||
any(debug_assertions, features = "ssr"),
|
||||
tracing::instrument(level = "trace", skip_all,)
|
||||
)]
|
||||
pub fn create_server_multi_action<S>(
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "leptos_meta"
|
||||
version = "0.4.5"
|
||||
version = "0.4.3"
|
||||
edition = "2021"
|
||||
authors = ["Greg Johnston"]
|
||||
license = "MIT"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "leptos_router"
|
||||
version = "0.4.5"
|
||||
version = "0.4.3"
|
||||
edition = "2021"
|
||||
authors = ["Greg Johnston"]
|
||||
license = "MIT"
|
||||
|
||||
@@ -342,7 +342,8 @@ fn current_window_origin() -> String {
|
||||
///
|
||||
/// ## Encoding
|
||||
/// **Note:** `<ActionForm/>` only works with server functions that use the
|
||||
/// default `Url` encoding. This is to ensure that `<ActionForm/>` works correctly
|
||||
/// default `Url` encoding or the `GetJSON` encoding, not with `CBOR` or other
|
||||
/// encoding schemes. This is to ensure that `<ActionForm/>` works correctly
|
||||
/// both before and after WASM has loaded.
|
||||
#[cfg_attr(
|
||||
any(debug_assertions, feature = "ssr"),
|
||||
@@ -492,19 +493,6 @@ where
|
||||
});
|
||||
});
|
||||
let class = class.map(|bx| bx.into_attribute_boxed(cx));
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
{
|
||||
if I::encoding() != server_fn::Encoding::Url {
|
||||
leptos::warn!(
|
||||
"<ActionForm/> only supports the `Url` encoding for server \
|
||||
functions, but {} uses {:?}.",
|
||||
std::any::type_name::<I>(),
|
||||
I::encoding()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
let mut props = FormProps::builder()
|
||||
.action(action_url)
|
||||
.version(version)
|
||||
|
||||
@@ -42,21 +42,19 @@ impl ParamsMap {
|
||||
self.0.remove(key)
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "csr", feature = "hydrate", feature = "ssr"))]
|
||||
/// Converts the map to a query string.
|
||||
pub fn to_query_string(&self) -> String {
|
||||
use crate::history::url::escape;
|
||||
let mut buf = String::new();
|
||||
if !self.0.is_empty() {
|
||||
buf.push('?');
|
||||
for (k, v) in &self.0 {
|
||||
buf.push_str(&escape(k));
|
||||
buf.push('=');
|
||||
buf.push_str(&escape(v));
|
||||
buf.push('&');
|
||||
}
|
||||
if buf.len() > 1 {
|
||||
buf.pop();
|
||||
}
|
||||
let mut buf = String::from("?");
|
||||
for (k, v) in &self.0 {
|
||||
buf.push_str(&escape(k));
|
||||
buf.push('=');
|
||||
buf.push_str(&escape(v));
|
||||
buf.push('&');
|
||||
}
|
||||
if buf.len() > 1 {
|
||||
buf.pop();
|
||||
}
|
||||
buf
|
||||
}
|
||||
|
||||
@@ -36,8 +36,9 @@ impl TryFrom<&str> for Url {
|
||||
type Error = String;
|
||||
|
||||
fn try_from(url: &str) -> Result<Self, Self::Error> {
|
||||
let fake_host = "http://leptos";
|
||||
let url = web_sys::Url::new_with_base(url, fake_host).map_js_error()?;
|
||||
let fake_host = String::from("http://leptos");
|
||||
let url =
|
||||
web_sys::Url::new_with_base(url, &fake_host).map_js_error()?;
|
||||
Ok(Self {
|
||||
origin: url.origin(),
|
||||
pathname: url.pathname(),
|
||||
|
||||
@@ -3,82 +3,7 @@ use crate::{
|
||||
RouteContext, RouterContext,
|
||||
};
|
||||
use leptos::{create_memo, signal_prelude::*, use_context, Memo, Scope};
|
||||
use std::{borrow::Cow, rc::Rc, str::FromStr};
|
||||
|
||||
/// Constructs a signal synchronized with a specific URL query parameter.
|
||||
///
|
||||
/// The function creates a bidirectional sync mechanism between the state encapsulated in a signal and a URL query parameter.
|
||||
/// This means that any change to the state will update the URL, and vice versa, making the function especially useful
|
||||
/// for maintaining state consistency across page reloads.
|
||||
///
|
||||
/// The `key` argument is the unique identifier for the query parameter to be synced with the state.
|
||||
/// It is important to note that only one state can be tied to a specific key at any given time.
|
||||
///
|
||||
/// The function operates with types that can be parsed from and formatted into strings, denoted by `T`.
|
||||
/// If the parsing fails for any reason, the function treats the value as `None`.
|
||||
/// The URL parameter can be cleared by setting the signal to `None`.
|
||||
///
|
||||
/// ```rust
|
||||
/// use leptos::*;
|
||||
/// use leptos_router::*;
|
||||
///
|
||||
/// #[component]
|
||||
/// pub fn SimpleQueryCounter(cx: Scope) -> impl IntoView {
|
||||
/// let (count, set_count) = create_query_signal::<i32>(cx, "count");
|
||||
/// let clear = move |_| set_count.set(None);
|
||||
/// let decrement =
|
||||
/// move |_| set_count.set(Some(count.get().unwrap_or(0) - 1));
|
||||
/// let increment =
|
||||
/// move |_| set_count.set(Some(count.get().unwrap_or(0) + 1));
|
||||
///
|
||||
/// view! { cx,
|
||||
/// <div>
|
||||
/// <button on:click=clear>"Clear"</button>
|
||||
/// <button on:click=decrement>"-1"</button>
|
||||
/// <span>"Value: " {move || count.get().unwrap_or(0)} "!"</span>
|
||||
/// <button on:click=increment>"+1"</button>
|
||||
/// </div>
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
pub fn create_query_signal<T>(
|
||||
cx: Scope,
|
||||
key: impl Into<Cow<'static, str>>,
|
||||
) -> (Memo<Option<T>>, SignalSetter<Option<T>>)
|
||||
where
|
||||
T: FromStr + ToString + PartialEq,
|
||||
{
|
||||
let key = key.into();
|
||||
let query_map = use_query_map(cx);
|
||||
let navigate = use_navigate(cx);
|
||||
let route = use_route(cx);
|
||||
|
||||
let get = create_memo(cx, {
|
||||
let key = key.clone();
|
||||
move |_| {
|
||||
query_map
|
||||
.with(|map| map.get(&key).and_then(|value| value.parse().ok()))
|
||||
}
|
||||
});
|
||||
|
||||
let set = SignalSetter::map(cx, move |value: Option<T>| {
|
||||
let mut new_query_map = query_map.get();
|
||||
match value {
|
||||
Some(value) => {
|
||||
new_query_map.insert(key.to_string(), value.to_string());
|
||||
}
|
||||
None => {
|
||||
new_query_map.remove(&key);
|
||||
}
|
||||
}
|
||||
let qs = new_query_map.to_query_string();
|
||||
let path = route.path();
|
||||
let new_url = format!("{path}{qs}");
|
||||
let _ = navigate(&new_url, NavigateOptions::default());
|
||||
});
|
||||
|
||||
(get, set)
|
||||
}
|
||||
use std::rc::Rc;
|
||||
|
||||
/// Returns the current [RouterContext], containing information about the router's state.
|
||||
pub fn use_router(cx: Scope) -> RouterContext {
|
||||
|
||||
@@ -56,23 +56,23 @@
|
||||
//! // our root route: the contact list is always shown
|
||||
//! <Route
|
||||
//! path=""
|
||||
//! view=ContactList
|
||||
//! view=move |cx| view! { cx, <ContactList/> }
|
||||
//! >
|
||||
//! // users like /gbj or /bob
|
||||
//! <Route
|
||||
//! path=":id"
|
||||
//! view=Contact
|
||||
//! view=move |cx| view! { cx, <Contact/> }
|
||||
//! />
|
||||
//! // a fallback if the /:id segment is missing from the URL
|
||||
//! <Route
|
||||
//! path=""
|
||||
//! view=move |_| view! { cx, <p class="contact">"Select a contact."</p> }
|
||||
//! view=move |_| view! { cx, <p class="contact">"Select a contact."</p> }
|
||||
//! />
|
||||
//! </Route>
|
||||
//! // LR will automatically use this for /about, not the /:id match above
|
||||
//! <Route
|
||||
//! path="about"
|
||||
//! view=About
|
||||
//! view=move |cx| view! { cx, <About/> }
|
||||
//! />
|
||||
//! </Routes>
|
||||
//! </main>
|
||||
|
||||
@@ -101,5 +101,5 @@ pub fn expand_optionals(pattern: &str) -> Vec<Cow<str>> {
|
||||
}
|
||||
}
|
||||
|
||||
const OPTIONAL: &str = r"(/?:[^/]+)\?";
|
||||
const OPTIONAL_2: &str = r"^(/:[^/]+)\?";
|
||||
const OPTIONAL: &str = r#"(/?:[^/]+)\?"#;
|
||||
const OPTIONAL_2: &str = r#"^(/:[^/]+)\?"#;
|
||||
|
||||
Reference in New Issue
Block a user