mirror of
https://github.com/leptos-rs/leptos.git
synced 2025-12-28 12:31:55 -05:00
Compare commits
1 Commits
new-exampl
...
1408
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8bcc277acb |
@@ -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).
|
||||
|
||||
@@ -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=Home
|
||||
<Route path="/users" view=Users
|
||||
<Route path="/users/:id" view=UserProfile
|
||||
<Route path="/*any" view=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=Home
|
||||
<Route path="/users" view=Users
|
||||
<Route path=":id" view=UserProfile
|
||||
</Route>
|
||||
<Route path="/*any" view=NotFound/>
|
||||
<Route path="/*any" view=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=Users
|
||||
<Route path="/users/:id" view=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=Users
|
||||
<Route path=":id" view=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=Users
|
||||
<Route path=":id" view=UserProfile
|
||||
<Route path="" view=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=ContactList
|
||||
<Route path=":id" view=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=ContactList
|
||||
<Route path=":id" view=ContactInfo
|
||||
<Route path="" view=EmailAndPhone
|
||||
<Route path="address" view=Address
|
||||
<Route path="messages" view=Messages
|
||||
</Route>
|
||||
<Route path="" view=|cx| view! { cx,
|
||||
<p>"Select a contact to view more info."</p>
|
||||
@@ -203,7 +203,7 @@ fn App(cx: Scope) -> impl IntoView {
|
||||
path="/contacts"
|
||||
view=ContactList
|
||||
// if no id specified, fall back
|
||||
<Route path=":id" view=ContactInfo>
|
||||
<Route path=":id" view=ContactInfo
|
||||
<Route path="" view=|cx| view! { cx,
|
||||
<div class="tab">
|
||||
"(Contact Info)"
|
||||
|
||||
@@ -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`.
|
||||
|
||||
@@ -117,9 +109,8 @@ fn App(cx: Scope) -> impl IntoView {
|
||||
<Route
|
||||
path="/contacts"
|
||||
view=ContactList
|
||||
>
|
||||
// if no id specified, fall back
|
||||
<Route path=":id" view=ContactInfo>
|
||||
<Route path=":id" view=ContactInfo
|
||||
<Route path="" view=|cx| view! { cx,
|
||||
<div class="tab">
|
||||
"(Contact Info)"
|
||||
|
||||
@@ -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.
|
||||
@@ -55,9 +53,8 @@ fn App(cx: Scope) -> impl IntoView {
|
||||
<Route
|
||||
path="/contacts"
|
||||
view=ContactList
|
||||
>
|
||||
// if no id specified, fall back
|
||||
<Route path=":id" view=ContactInfo>
|
||||
<Route path=":id" view=ContactInfo
|
||||
<Route path="" view=|cx| view! { cx,
|
||||
<div class="tab">
|
||||
"(Contact Info)"
|
||||
|
||||
@@ -80,7 +80,7 @@ fn App(cx: Scope) -> impl IntoView {
|
||||
<h1><code>"<Form/>"</code></h1>
|
||||
<main>
|
||||
<Routes>
|
||||
<Route path="" view=FormExample/>
|
||||
<Route path="" view=FormExample
|
||||
</Routes>
|
||||
</main>
|
||||
</Router>
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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”:
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -115,11 +115,11 @@ Calling it like this will create a list:
|
||||
|
||||
```rust
|
||||
view! { cx,
|
||||
<WrapsChildren>
|
||||
<WrappedChildren>
|
||||
"A"
|
||||
"B"
|
||||
"C"
|
||||
</WrapsChildren>
|
||||
</WrappedChildren>
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
@@ -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>
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -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>
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
#![allow(clippy::incorrect_clone_impl_on_copy_type)]
|
||||
#![deny(missing_docs)]
|
||||
#![forbid(unsafe_code)]
|
||||
#![cfg_attr(feature = "nightly", feature(fn_traits))]
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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"),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1239,7 +1239,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 +1260,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 +1270,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 }
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
#![allow(clippy::incorrect_clone_impl_on_copy_type)]
|
||||
#![deny(missing_docs)]
|
||||
#![cfg_attr(feature = "nightly", feature(fn_traits))]
|
||||
#![cfg_attr(feature = "nightly", feature(unboxed_closures))]
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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, feature = "ssr"))]
|
||||
defined_at: self.defined_at,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -187,7 +187,7 @@ where
|
||||
O: 'static,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
*self
|
||||
Self(self.0)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
#![allow(clippy::incorrect_clone_impl_on_copy_type)]
|
||||
#![deny(missing_docs)]
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
|
||||
@@ -77,7 +77,7 @@ where
|
||||
O: 'static,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
*self
|
||||
Self(self.0)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
Reference in New Issue
Block a user