mirror of
https://github.com/leptos-rs/leptos.git
synced 2026-01-10 15:39:45 -05:00
Compare commits
1 Commits
signal-api
...
4453
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b484b39779 |
2
.github/workflows/autofix.yml
vendored
2
.github/workflows/autofix.yml
vendored
@@ -18,7 +18,7 @@ jobs:
|
||||
autofix:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions-rust-lang/setup-rust-toolchain@v1
|
||||
with: {toolchain: "nightly-2025-07-16", components: "rustfmt, clippy", target: "wasm32-unknown-unknown", rustflags: ""}
|
||||
- name: Install Glib
|
||||
|
||||
2
.github/workflows/ci.yml
vendored
2
.github/workflows/ci.yml
vendored
@@ -63,6 +63,6 @@ jobs:
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y libglib2.0-dev
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
uses: actions/checkout@v5
|
||||
- name: Semver Checks
|
||||
uses: obi1kenobi/cargo-semver-checks-action@v2
|
||||
|
||||
2
.github/workflows/get-example-changed.yml
vendored
2
.github/workflows/get-example-changed.yml
vendored
@@ -19,7 +19,7 @@ jobs:
|
||||
matrix: ${{ steps.set-example-changed.outputs.matrix }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: Get example files that changed
|
||||
|
||||
2
.github/workflows/get-examples-matrix.yml
vendored
2
.github/workflows/get-examples-matrix.yml
vendored
@@ -17,7 +17,7 @@ jobs:
|
||||
EXCLUDED_EXAMPLES: cargo-make
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
uses: actions/checkout@v5
|
||||
- name: Install jq
|
||||
run: sudo apt-get install jq
|
||||
- name: Set Matrix
|
||||
|
||||
2
.github/workflows/get-leptos-changed.yml
vendored
2
.github/workflows/get-leptos-changed.yml
vendored
@@ -13,7 +13,7 @@ jobs:
|
||||
leptos_changed: ${{ steps.set-source-changed.outputs.leptos_changed }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: Get source files that changed
|
||||
|
||||
2
.github/workflows/get-leptos-matrix.yml
vendored
2
.github/workflows/get-leptos-matrix.yml
vendored
@@ -13,7 +13,7 @@ jobs:
|
||||
matrix: ${{ steps.set-matrix.outputs.matrix }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
uses: actions/checkout@v5
|
||||
- name: Install jq
|
||||
run: sudo apt-get install jq
|
||||
- name: Set Matrix
|
||||
|
||||
2
.github/workflows/publish-book.yml
vendored
2
.github/workflows/publish-book.yml
vendored
@@ -12,7 +12,7 @@ jobs:
|
||||
contents: write # To push a branch
|
||||
pull-requests: write # To create a PR from that branch
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/checkout@v5
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: Install mdbook
|
||||
|
||||
4
.github/workflows/run-cargo-make-task.yml
vendored
4
.github/workflows/run-cargo-make-task.yml
vendored
@@ -53,7 +53,7 @@ jobs:
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y libglib2.0-dev
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/checkout@v5
|
||||
- name: Setup Rust
|
||||
uses: dtolnay/rust-toolchain@master
|
||||
with:
|
||||
@@ -103,7 +103,7 @@ jobs:
|
||||
id: pnpm-cache
|
||||
run: |
|
||||
echo "STORE_PATH=$(pnpm store path)" >> $GITHUB_OUTPUT
|
||||
- uses: actions/cache@v5
|
||||
- uses: actions/cache@v4
|
||||
if: contains(inputs.directory, 'examples')
|
||||
name: Setup pnpm cache
|
||||
with:
|
||||
|
||||
1055
Cargo.lock
generated
1055
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
123
Cargo.toml
123
Cargo.toml
@@ -2,6 +2,7 @@
|
||||
resolver = "2"
|
||||
members = [
|
||||
# utilities
|
||||
"oco",
|
||||
"any_spawner",
|
||||
"const_str_slice_concat",
|
||||
"either_of",
|
||||
@@ -49,45 +50,44 @@ any_spawner = { path = "./any_spawner/", version = "0.3.0" }
|
||||
const_str_slice_concat = { path = "./const_str_slice_concat", version = "0.1" }
|
||||
either_of = { path = "./either_of/", version = "0.1.6" }
|
||||
hydration_context = { path = "./hydration_context", version = "0.3.0" }
|
||||
leptos = { path = "./leptos", version = "0.8.15" }
|
||||
leptos_config = { path = "./leptos_config", version = "0.8.8" }
|
||||
leptos = { path = "./leptos", version = "0.8.12" }
|
||||
leptos_config = { path = "./leptos_config", version = "0.8.7" }
|
||||
leptos_dom = { path = "./leptos_dom", version = "0.8.7" }
|
||||
leptos_hot_reload = { path = "./leptos_hot_reload", version = "0.8.5" }
|
||||
leptos_integration_utils = { path = "./integrations/utils", version = "0.8.7" }
|
||||
leptos_macro = { path = "./leptos_macro", version = "0.8.13" }
|
||||
leptos_router = { path = "./router", version = "0.8.11" }
|
||||
leptos_integration_utils = { path = "./integrations/utils", version = "0.8.6" }
|
||||
leptos_macro = { path = "./leptos_macro", version = "0.8.11" }
|
||||
leptos_router = { path = "./router", version = "0.8.9" }
|
||||
leptos_router_macro = { path = "./router_macro", version = "0.8.6" }
|
||||
leptos_server = { path = "./leptos_server", version = "0.8.6" }
|
||||
leptos_server = { path = "./leptos_server", version = "0.8.5" }
|
||||
leptos_meta = { path = "./meta", version = "0.8.5" }
|
||||
next_tuple = { path = "./next_tuple", version = "0.1.0" }
|
||||
oco_ref = { path = "./oco", version = "0.2.1" }
|
||||
or_poisoned = { path = "./or_poisoned", version = "0.1.0" }
|
||||
reactive_graph = { path = "./reactive_graph", version = "0.2.12" }
|
||||
reactive_stores = { path = "./reactive_stores", version = "0.3.1" }
|
||||
reactive_graph = { path = "./reactive_graph", version = "0.2.9" }
|
||||
reactive_stores = { path = "./reactive_stores", version = "0.3.0" }
|
||||
reactive_stores_macro = { path = "./reactive_stores_macro", version = "0.2.6" }
|
||||
server_fn = { path = "./server_fn", version = "0.8.9" }
|
||||
server_fn = { path = "./server_fn", version = "0.8.8" }
|
||||
server_fn_macro = { path = "./server_fn_macro", version = "0.8.8" }
|
||||
server_fn_macro_default = { path = "./server_fn/server_fn_macro_default", version = "0.8.5" }
|
||||
tachys = { path = "./tachys", version = "0.2.11" }
|
||||
tachys = { path = "./tachys", version = "0.2.10" }
|
||||
|
||||
# members deps
|
||||
async-once-cell = { default-features = false, version = "0.5.4" }
|
||||
async-once-cell = { default-features = false, version = "0.5.3" }
|
||||
itertools = { default-features = false, version = "0.14.0" }
|
||||
convert_case = { default-features = false, version = "0.10.0" }
|
||||
serde_json = { default-features = false, version = "1.0.148" }
|
||||
trybuild = { default-features = false, version = "1.0.114" }
|
||||
typed-builder = { default-features = false, version = "0.23.2" }
|
||||
typed-builder-macro = { default-features = false, version = "0.23.2" }
|
||||
convert_case = { default-features = false, version = "0.8.0" }
|
||||
serde_json = { default-features = false, version = "1.0.143" }
|
||||
trybuild = { default-features = false, version = "1.0.110" }
|
||||
typed-builder = { default-features = false, version = "0.21.2" }
|
||||
thiserror = { default-features = false, version = "2.0.17" }
|
||||
wasm-bindgen = { default-features = false, version = "0.2.106" }
|
||||
indexmap = { default-features = false, version = "2.12.1" }
|
||||
wasm-bindgen = { default-features = false, version = "0.2.100" }
|
||||
indexmap = { default-features = false, version = "2.11.0" }
|
||||
rstml = { default-features = false, version = "0.12.1" }
|
||||
rustc_version = { default-features = false, version = "0.4.1" }
|
||||
guardian = { default-features = false, version = "1.3.0" }
|
||||
rustc-hash = { default-features = false, version = "2.1.1" }
|
||||
actix-web = { default-features = false, version = "4.12.1" }
|
||||
tracing = { default-features = false, version = "0.1.44" }
|
||||
slotmap = { default-features = false, version = "1.1.1" }
|
||||
actix-web = { default-features = false, version = "4.11.0" }
|
||||
tracing = { default-features = false, version = "0.1.41" }
|
||||
slotmap = { default-features = false, version = "1.0.7" }
|
||||
futures = { default-features = false, version = "0.3.31" }
|
||||
dashmap = { default-features = false, version = "6.1.0" }
|
||||
pin-project-lite = { default-features = false, version = "0.2.16" }
|
||||
@@ -97,41 +97,42 @@ html-escape = { default-features = false, version = "0.2.13" }
|
||||
proc-macro-error2 = { default-features = false, version = "2.0.1" }
|
||||
const_format = { default-features = false, version = "0.2.35" }
|
||||
gloo-net = { default-features = false, version = "0.6.0" }
|
||||
url = { default-features = false, version = "2.5.7" }
|
||||
tokio = { default-features = false, version = "1.48.0" }
|
||||
url = { default-features = false, version = "2.5.4" }
|
||||
tokio = { default-features = false, version = "1.47.1" }
|
||||
base64 = { default-features = false, version = "0.22.1" }
|
||||
cfg-if = { default-features = false, version = "1.0.4" }
|
||||
wasm-bindgen-futures = { default-features = false, version = "0.4.56" }
|
||||
cfg-if = { default-features = false, version = "1.0.3" }
|
||||
wasm-bindgen-futures = { default-features = false, version = "0.4.50" }
|
||||
tower = { default-features = false, version = "0.5.2" }
|
||||
proc-macro2 = { default-features = false, version = "1.0.96" }
|
||||
proc-macro2 = { default-features = false, version = "1.0.101" }
|
||||
serde = { default-features = false, version = "1.0.219" }
|
||||
parking_lot = { default-features = false, version = "0.12.4" }
|
||||
axum = { default-features = false, version = "0.8.4" }
|
||||
serde_qs = { default-features = false, version = "1.0.0-rc.3" }
|
||||
syn = { default-features = false, version = "2.0.104" }
|
||||
parking_lot = { default-features = false, version = "0.12.5" }
|
||||
axum = { default-features = false, version = "0.8.6" }
|
||||
serde_qs = { default-features = false, version = "0.15.0" }
|
||||
syn = { default-features = false, version = "2.0.106" }
|
||||
xxhash-rust = { default-features = false, version = "0.8.15" }
|
||||
paste = { default-features = false, version = "1.0.15" }
|
||||
quote = { default-features = false, version = "1.0.42" }
|
||||
web-sys = { default-features = false, version = "0.3.83" }
|
||||
js-sys = { default-features = false, version = "0.3.83" }
|
||||
rand = { default-features = false, version = "0.9.2" }
|
||||
serde-lite = { default-features = false, version = "0.5.1" }
|
||||
quote = { default-features = false, version = "1.0.41" }
|
||||
web-sys = { default-features = false, version = "0.3.77" }
|
||||
js-sys = { default-features = false, version = "0.3.77" }
|
||||
rand = { default-features = false, version = "0.9.1" }
|
||||
serde-lite = { default-features = false, version = "0.5.0" }
|
||||
tokio-tungstenite = { default-features = false, version = "0.28.0" }
|
||||
serial_test = { default-features = false, version = "3.2.0" }
|
||||
erased = { default-features = false, version = "0.1.2" }
|
||||
glib = { default-features = false, version = "0.21.5" }
|
||||
glib = { default-features = false, version = "0.20.12" }
|
||||
async-trait = { default-features = false, version = "0.1.89" }
|
||||
typed-builder-macro = { default-features = false, version = "0.21.0" }
|
||||
linear-map = { default-features = false, version = "1.2.0" }
|
||||
anyhow = { default-features = false, version = "1.0.100" }
|
||||
walkdir = { default-features = false, version = "2.5.0" }
|
||||
actix-ws = { default-features = false, version = "0.3.0" }
|
||||
tower-http = { default-features = false, version = "0.6.8" }
|
||||
tower-http = { default-features = false, version = "0.6.4" }
|
||||
prettyplease = { default-features = false, version = "0.2.37" }
|
||||
inventory = { default-features = false, version = "0.3.21" }
|
||||
config = { default-features = false, version = "0.15.19" }
|
||||
camino = { default-features = false, version = "1.2.2" }
|
||||
config = { default-features = false, version = "0.15.14" }
|
||||
camino = { default-features = false, version = "1.2.1" }
|
||||
ciborium = { default-features = false, version = "0.2.2" }
|
||||
bitcode = { default-features = false, version = "0.6.9" }
|
||||
bitcode = { default-features = false, version = "0.6.6" }
|
||||
multer = { default-features = false, version = "3.1.0" }
|
||||
leptos-spin-macro = { default-features = false, version = "0.2.0" }
|
||||
sledgehammer_utils = { default-features = false, version = "0.3.1" }
|
||||
@@ -139,38 +140,38 @@ sledgehammer_bindgen = { default-features = false, version = "0.6.0" }
|
||||
wasm-streams = { default-features = false, version = "0.4.2" }
|
||||
rkyv = { default-features = false, version = "0.8.12" }
|
||||
temp-env = { default-features = false, version = "0.3.6" }
|
||||
uuid = { default-features = false, version = "1.19.0" }
|
||||
bytes = { default-features = false, version = "1.11.0" }
|
||||
http = { default-features = false, version = "1.4.0" }
|
||||
regex = { default-features = false, version = "1.12.2" }
|
||||
uuid = { default-features = false, version = "1.18.0" }
|
||||
bytes = { default-features = false, version = "1.10.1" }
|
||||
http = { default-features = false, version = "1.3.1" }
|
||||
regex = { default-features = false, version = "1.11.3" }
|
||||
drain_filter_polyfill = { default-features = false, version = "0.1.3" }
|
||||
tempfile = { default-features = false, version = "3.24.0" }
|
||||
tempfile = { default-features = false, version = "3.23.0" }
|
||||
futures-lite = { default-features = false, version = "2.6.1" }
|
||||
log = { default-features = false, version = "0.4.29" }
|
||||
log = { default-features = false, version = "0.4.27" }
|
||||
percent-encoding = { default-features = false, version = "2.3.2" }
|
||||
async-executor = { default-features = false, version = "1.13.3" }
|
||||
const-str = { default-features = false, version = "0.7.1" }
|
||||
async-executor = { default-features = false, version = "1.13.2" }
|
||||
const-str = { default-features = false, version = "0.6.4" }
|
||||
http-body-util = { default-features = false, version = "0.1.3" }
|
||||
hyper = { default-features = false, version = "1.8.1" }
|
||||
hyper = { default-features = false, version = "1.7.0" }
|
||||
postcard = { default-features = false, version = "1.1.3" }
|
||||
rmp-serde = { default-features = false, version = "1.3.1" }
|
||||
reqwest = { default-features = false, version = "0.12.28" }
|
||||
rmp-serde = { default-features = false, version = "1.3.0" }
|
||||
reqwest = { default-features = false, version = "0.12.23" }
|
||||
tower-layer = { default-features = false, version = "0.3.3" }
|
||||
attribute-derive = { default-features = false, version = "0.10.5" }
|
||||
insta = { default-features = false, version = "1.45.1" }
|
||||
codee = { default-features = false, version = "0.3.5" }
|
||||
insta = { default-features = false, version = "1.43.1" }
|
||||
codee = { default-features = false, version = "0.3.0" }
|
||||
actix-http = { default-features = false, version = "3.11.2" }
|
||||
wasm-bindgen-test = { default-features = false, version = "0.3.56" }
|
||||
wasm-bindgen-test = { default-features = false, version = "0.3.50" }
|
||||
rustversion = { default-features = false, version = "1.0.22" }
|
||||
getrandom = { default-features = false, version = "0.3.4" }
|
||||
actix-files = { default-features = false, version = "0.6.9" }
|
||||
async-lock = { default-features = false, version = "3.4.2" }
|
||||
getrandom = { default-features = false, version = "0.3.3" }
|
||||
actix-files = { default-features = false, version = "0.6.6" }
|
||||
async-lock = { default-features = false, version = "3.4.1" }
|
||||
base16 = { default-features = false, version = "0.2.1" }
|
||||
digest = { default-features = false, version = "0.10.7" }
|
||||
sha2 = { default-features = false, version = "0.10.9" }
|
||||
subsecond = { default-features = false, version = "0.7.2" }
|
||||
dioxus-cli-config = { default-features = false, version = "0.7.2" }
|
||||
dioxus-devtools = { default-features = false, version = "0.7.2" }
|
||||
sha2 = { default-features = false, version = "0.10.8" }
|
||||
subsecond = { default-features = false, version = "0.7.0-rc.0" }
|
||||
dioxus-cli-config = { default-features = false, version = "0.7.0-rc.0" }
|
||||
dioxus-devtools = { default-features = false, version = "0.7.0-rc.0" }
|
||||
wasm_split_helpers = { default-features = false, version = "0.2.0" }
|
||||
|
||||
[profile.release]
|
||||
|
||||
@@ -74,8 +74,8 @@ Leptos is a full-stack, isomorphic Rust web framework leveraging fine-grained re
|
||||
|
||||
## What does that mean?
|
||||
|
||||
- **Full-stack**: Leptos can be used to build apps that run in the browser (client-side rendering), on the server (server-side rendering), or by rendering HTML on the server and then adding interactivity in the browser (server-side rendering with hydration). This includes support for HTTP streaming of both data ([`Resource`s](https://docs.rs/leptos/latest/leptos/prelude/struct.Resource.html)) and HTML (out-of-order or in-order streaming of [`<Suspense/>`](https://docs.rs/leptos/latest/leptos/suspense/fn.Suspense.html) components.)
|
||||
- **Isomorphic**: Leptos provides primitives to write isomorphic [server functions](https://docs.rs/server_fn/latest/server_fn/), i.e., functions that can be called with the “same shape” on the client or server, but only run on the server. This means you can write your server-only logic (database requests, authentication etc.) alongside the client-side components that will consume it, and call server functions as if they were running in the browser, without needing to create and maintain a separate REST or other API.
|
||||
- **Full-stack**: Leptos can be used to build apps that run in the browser (client-side rendering), on the server (server-side rendering), or by rendering HTML on the server and then adding interactivity in the browser (server-side rendering with hydration). This includes support for HTTP streaming of both data ([`Resource`s](https://docs.rs/leptos/latest/leptos/struct.Resource.html)) and HTML (out-of-order or in-order streaming of [`<Suspense/>`](https://docs.rs/leptos/latest/leptos/fn.Suspense.html) components.)
|
||||
- **Isomorphic**: Leptos provides primitives to write isomorphic [server functions](https://docs.rs/leptos_server/0.2.5/leptos_server/index.html), i.e., functions that can be called with the “same shape” on the client or server, but only run on the server. This means you can write your server-only logic (database requests, authentication etc.) alongside the client-side components that will consume it, and call server functions as if they were running in the browser, without needing to create and maintain a separate REST or other API.
|
||||
- **Web**: Leptos is built on the Web platform and Web standards. The [router](https://docs.rs/leptos_router/latest/leptos_router/) is designed to use Web fundamentals (like links and forms) and build on top of them rather than trying to replace them.
|
||||
- **Framework**: Leptos provides most of what you need to build a modern web app: a reactive system, templating library, and a router that works on both the server and client side.
|
||||
- **Fine-grained reactivity**: The entire framework is built from reactive primitives. This allows for extremely performant code with minimal overhead: when a reactive signal’s value changes, it can update a single text node, toggle a single class, or remove an element from the DOM without any other code running. (So, no virtual DOM overhead!)
|
||||
|
||||
@@ -9,12 +9,12 @@ This document is intended as a running list of common issues, with example code
|
||||
**Issue**: Sometimes you want to update a reactive signal in a way that depends on another signal.
|
||||
|
||||
```rust
|
||||
let (a, set_a) = signal(0);
|
||||
let (b, set_b) = signal(false);
|
||||
let (a, set_a) = create_signal(0);
|
||||
let (b, set_b) = create_signal(false);
|
||||
|
||||
Effect::new(move |_| {
|
||||
if a.get() > 5 {
|
||||
set_b.set(true);
|
||||
create_effect(move |_| {
|
||||
if a() > 5 {
|
||||
set_b(true);
|
||||
}
|
||||
});
|
||||
```
|
||||
@@ -24,10 +24,56 @@ This creates an inefficient chain of updates, and can easily lead to infinite lo
|
||||
**Solution**: Follow the rule, _What can be derived, should be derived._ In this case, this has the benefit of massively reducing the code size, too!
|
||||
|
||||
```rust
|
||||
let (a, set_a) = signal(0);
|
||||
let b = move || a.get() > 5;
|
||||
let (a, set_a) = create_signal(0);
|
||||
let b = move || a () > 5;
|
||||
```
|
||||
|
||||
### Nested signal updates/reads triggering panic
|
||||
|
||||
Sometimes you have nested signals: for example, hash-map that can change over time, each of whose values can also change over time:
|
||||
|
||||
```rust
|
||||
#[component]
|
||||
pub fn App() -> impl IntoView {
|
||||
let resources = create_rw_signal(HashMap::new());
|
||||
|
||||
let update = move |id: usize| {
|
||||
resources.update(|resources| {
|
||||
resources
|
||||
.entry(id)
|
||||
.or_insert_with(|| create_rw_signal(0))
|
||||
.update(|amount| *amount += 1)
|
||||
})
|
||||
};
|
||||
|
||||
view! {
|
||||
<div>
|
||||
<pre>{move || format!("{:#?}", resources.get().into_iter().map(|(id, resource)| (id, resource.get())).collect::<Vec<_>>())}</pre>
|
||||
<button on:click=move |_| update(1)>"+"</button>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Clicking the button twice will cause a panic, because of the nested signal _read_. Calling the `update` function on `resources` immediately takes out a mutable borrow on `resources`, then updates the `resource` signal—which re-runs the effect that reads from the signals, which tries to immutably access `resources` and panics. It's the nested update here which causes a problem, because the inner update triggers and effect that tries to read both signals while the outer is still updating.
|
||||
|
||||
You can fix this fairly easily by using the [`batch()`](https://docs.rs/leptos/latest/leptos/fn.batch.html) method:
|
||||
|
||||
```rust
|
||||
let update = move |id: usize| {
|
||||
batch(move || {
|
||||
resources.update(|resources| {
|
||||
resources
|
||||
.entry(id)
|
||||
.or_insert_with(|| create_rw_signal(0))
|
||||
.update(|amount| *amount += 1)
|
||||
})
|
||||
});
|
||||
};
|
||||
```
|
||||
|
||||
This delays running any effects until after both updates are made, preventing the conflict entirely without requiring any other restructuring.
|
||||
|
||||
## Templates and the DOM
|
||||
|
||||
### `<input value=...>` doesn't update or stops updating
|
||||
@@ -37,8 +83,8 @@ Many DOM attributes can be updated either by setting an attribute on the DOM nod
|
||||
This means that in practice, attributes like `value` or `checked` on an `<input/>` element only update the _default_ value for the `<input/>`. If you want to reactively update the value, you should use `prop:value` instead to set the `value` property.
|
||||
|
||||
```rust
|
||||
let (a, set_a) = signal("Starting value".to_string());
|
||||
let on_input = move |ev| set_a.set(event_target_value(&ev));
|
||||
let (a, set_a) = create_signal("Starting value".to_string());
|
||||
let on_input = move |ev| set_a(event_target_value(&ev));
|
||||
|
||||
view! {
|
||||
|
||||
@@ -51,8 +97,8 @@ view! {
|
||||
```
|
||||
|
||||
```rust
|
||||
let (a, set_a) = signal("Starting value".to_string());
|
||||
let on_input = move |ev| set_a.set(event_target_value(&ev));
|
||||
let (a, set_a) = create_signal("Starting value".to_string());
|
||||
let on_input = move |ev| set_a(event_target_value(&ev));
|
||||
|
||||
view! {
|
||||
|
||||
|
||||
@@ -27,7 +27,7 @@ tokio = { version = "1.39", features = [
|
||||
], optional = true }
|
||||
tower = { version = "0.4.13", optional = true }
|
||||
tower-http = { version = "0.5.2", features = ["fs"], optional = true }
|
||||
wasm-bindgen = "0.2.105"
|
||||
wasm-bindgen = "0.2.92"
|
||||
web-sys = { version = "0.3.69", features = [
|
||||
"AddEventListenerOptions",
|
||||
"Document",
|
||||
|
||||
@@ -510,9 +510,11 @@ if (window.hljs) {
|
||||
});
|
||||
view! {
|
||||
<pre><code class="language-rust">{code.await}</code></pre>
|
||||
<ShowLet some=script let:script>
|
||||
<Script>{script}</Script>
|
||||
</ShowLet>
|
||||
{
|
||||
move || script.get().map(|script| {
|
||||
view! { <Script>{script}</Script> }
|
||||
})
|
||||
}
|
||||
}
|
||||
})
|
||||
};
|
||||
@@ -565,9 +567,11 @@ if (window.hljs) {
|
||||
});
|
||||
view! {
|
||||
<pre><code class="language-rust">{code.await}</code></pre>
|
||||
<ShowLet some=script let:script>
|
||||
<Script>{script}</Script>
|
||||
</ShowLet>
|
||||
{
|
||||
move || script.get().map(|script| {
|
||||
view! { <Script>{script}</Script> }
|
||||
})
|
||||
}
|
||||
}
|
||||
})
|
||||
};
|
||||
@@ -670,7 +674,7 @@ fn CodeDemoWasm(mode: WasmDemo) -> impl IntoView {
|
||||
leptos::logging::log!("wasm csr_listener listener added");
|
||||
|
||||
// Dispatch the event when this view is finally mounted onto the DOM.
|
||||
_ = request_animation_frame(move || {
|
||||
request_animation_frame(move || {
|
||||
let event = web_sys::Event::new("hljs_hook")
|
||||
.expect("error creating hljs_hook event");
|
||||
document.dispatch_event(&event)
|
||||
@@ -689,7 +693,7 @@ fn CodeDemoWasm(mode: WasmDemo) -> impl IntoView {
|
||||
<Suspense fallback=move || view! { <p>"Loading code example..."</p> }>{
|
||||
move || Suspend::new(async move {
|
||||
Effect::new(move |_| {
|
||||
_ = request_animation_frame(move || {
|
||||
request_animation_frame(move || {
|
||||
leptos::logging::log!("request_animation_frame invoking hljs::highlight_all");
|
||||
// under SSR this is an noop, but it wouldn't be called under there anyway because
|
||||
// it isn't the isomorphic version, i.e. Effect::new_isomorphic(...).
|
||||
@@ -815,7 +819,7 @@ fn WasmBindgenJSHookReadyEvent() -> impl IntoView {
|
||||
leptos::logging::log!("wasm csr_listener listener added");
|
||||
|
||||
// Dispatch the event when this view is finally mounted onto the DOM.
|
||||
_ = request_animation_frame(move || {
|
||||
request_animation_frame(move || {
|
||||
let event = web_sys::Event::new("hljs_hook")
|
||||
.expect("error creating hljs_hook event");
|
||||
document.dispatch_event(&event)
|
||||
@@ -866,7 +870,7 @@ fn WasmBindgenEffect() -> impl IntoView {
|
||||
let example = r#"<Suspense fallback=move || view! { <p>"Loading code example..."</p> }>{
|
||||
move || Suspend::new(async move {
|
||||
Effect::new(move |_| {
|
||||
_ = request_animation_frame(move || {
|
||||
request_animation_frame(move || {
|
||||
leptos::logging::log!("request_animation_frame invoking hljs::highlight_all");
|
||||
// under SSR this is an noop.
|
||||
crate::hljs::highlight_all();
|
||||
|
||||
@@ -25,7 +25,7 @@ log = "0.4.22"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
gloo-net = { version = "0.6.0", features = ["http"] }
|
||||
reqwest = { version = "0.12.5", features = ["json"] }
|
||||
wasm-bindgen = "0.2.105"
|
||||
wasm-bindgen = "0.2.93"
|
||||
web-sys = { version = "0.3.70", features = ["AbortController", "AbortSignal"] }
|
||||
send_wrapper = "0.6.0"
|
||||
|
||||
@@ -46,12 +46,12 @@ denylist = ["actix-files", "actix-web", "leptos_actix"]
|
||||
skip_feature_sets = [["csr", "ssr"], ["csr", "hydrate"], ["ssr", "hydrate"], []]
|
||||
|
||||
[package.metadata.leptos]
|
||||
# The name used by wasm-bindgen/cargo-leptos for the JS/WASM bundle. Defaults to the crate name
|
||||
# The name used by wasm-bindgen/cargo-leptos for the JS/WASM bundle. Defaults to the crate name
|
||||
output-name = "hackernews"
|
||||
# The site root folder is where cargo-leptos generate all output. WARNING: all content of this folder will be erased on a rebuild. Use it in your server setup.
|
||||
site-root = "target/site"
|
||||
# The site-root relative folder where all compiled output (JS, WASM and CSS) is written
|
||||
# Defaults to pkg
|
||||
# Defaults to pkg
|
||||
site-pkg-dir = "pkg"
|
||||
# [Optional] The source CSS file. If it ends with .sass or .scss then it will be compiled by dart-sass into CSS. The CSS is optimized by Lightning CSS before being written to <site-root>/<site-pkg>/app.css
|
||||
style-file = "./style.css"
|
||||
|
||||
@@ -145,11 +145,14 @@ fn Story(story: api::Story) -> impl IntoView {
|
||||
Either::Left(
|
||||
view! {
|
||||
<span>
|
||||
"by "
|
||||
<ShowLet some=story.user let:user>
|
||||
<A href=format!("/users/{user}")>{user.clone()}</A>
|
||||
</ShowLet>
|
||||
{format!(" {} | ", story.time_ago)}
|
||||
{"by "}
|
||||
{story
|
||||
.user
|
||||
.map(|user| {
|
||||
view! {
|
||||
<A href=format!("/users/{user}")>{user.clone()}</A>
|
||||
}
|
||||
})} {format!(" {} | ", story.time_ago)}
|
||||
<A href=format!(
|
||||
"/stories/{}",
|
||||
story.id,
|
||||
|
||||
@@ -30,13 +30,17 @@ pub fn Story() -> impl IntoView {
|
||||
<h1>{story.title}</h1>
|
||||
</a>
|
||||
<span class="host">"(" {story.domain} ")"</span>
|
||||
<ShowLet some=story.user let:user>
|
||||
<p class="meta">
|
||||
{story.points} " points | by "
|
||||
<A href=format!("/users/{user}")>{user.clone()}</A>
|
||||
{format!(" {}", story.time_ago)}
|
||||
</p>
|
||||
</ShowLet>
|
||||
{story
|
||||
.user
|
||||
.map(|user| {
|
||||
view! {
|
||||
<p class="meta">
|
||||
{story.points} " points | by "
|
||||
<A href=format!("/users/{user}")>{user.clone()}</A>
|
||||
{format!(" {}", story.time_ago)}
|
||||
</p>
|
||||
}
|
||||
})}
|
||||
</div>
|
||||
<div class="item-view-comments">
|
||||
<p class="item-view-comments-header">
|
||||
|
||||
@@ -26,7 +26,7 @@ tower-http = { version = "0.5.2", features = ["fs"], optional = true }
|
||||
tokio = { version = "1.39", features = ["full"], optional = true }
|
||||
http = { version = "1.1", optional = true }
|
||||
web-sys = { version = "0.3.70", features = ["AbortController", "AbortSignal"] }
|
||||
wasm-bindgen = "0.2.105"
|
||||
wasm-bindgen = "0.2.93"
|
||||
send_wrapper = { version = "0.6.0", features = ["futures"] }
|
||||
|
||||
[features]
|
||||
|
||||
@@ -133,9 +133,7 @@ fn Story(story: api::Story) -> impl IntoView {
|
||||
Either::Left(view! {
|
||||
<span>
|
||||
{"by "}
|
||||
<ShowLet some=story.user let:user>
|
||||
<A href=format!("/users/{user}")>{user.clone()}</A>
|
||||
</ShowLet>
|
||||
{story.user.map(|user| view ! { <A href=format!("/users/{user}")>{user.clone()}</A>})}
|
||||
{format!(" {} | ", story.time_ago)}
|
||||
<A href=format!("/stories/{}", story.id)>
|
||||
{if story.comments_count.unwrap_or_default() > 0 {
|
||||
|
||||
@@ -40,20 +40,18 @@ impl LazyRoute for StoryRoute {
|
||||
<Meta name="description" content=story.title.clone()/>
|
||||
<div class="item-view">
|
||||
<div class="item-view-header">
|
||||
<a href=story.url target="_blank">
|
||||
<h1>{story.title}</h1>
|
||||
</a>
|
||||
<span class="host">
|
||||
"("{story.domain}")"
|
||||
</span>
|
||||
<ShowLet some=story.user let:user>
|
||||
<p class="meta">
|
||||
{story.points}
|
||||
" points | by "
|
||||
<A href=format!("/users/{user}")>{user.clone()}</A>
|
||||
{format!(" {}", story.time_ago)}
|
||||
</p>
|
||||
</ShowLet>
|
||||
<a href=story.url target="_blank">
|
||||
<h1>{story.title}</h1>
|
||||
</a>
|
||||
<span class="host">
|
||||
"("{story.domain}")"
|
||||
</span>
|
||||
{story.user.map(|user| view! { <p class="meta">
|
||||
{story.points}
|
||||
" points | by "
|
||||
<A href=format!("/users/{user}")>{user.clone()}</A>
|
||||
{format!(" {}", story.time_ago)}
|
||||
</p>})}
|
||||
</div>
|
||||
<div class="item-view-comments">
|
||||
<p class="item-view-comments-header">
|
||||
|
||||
@@ -143,10 +143,8 @@ fn Story(story: api::Story) -> impl IntoView {
|
||||
{if story.story_type != "job" {
|
||||
Either::Left(view! {
|
||||
<span>
|
||||
"by "
|
||||
<ShowLet some=story.user let:user>
|
||||
<A href=format!("/users/{user}")>{user.clone()}</A>
|
||||
</ShowLet>
|
||||
{"by "}
|
||||
{story.user.map(|user| view ! { <A href=format!("/users/{user}")>{user.clone()}</A>})}
|
||||
{format!(" {} | ", story.time_ago)}
|
||||
<A href=format!("/stories/{}", story.id)>
|
||||
{if story.comments_count.unwrap_or_default() > 0 {
|
||||
|
||||
@@ -32,20 +32,18 @@ pub fn Story() -> impl IntoView {
|
||||
<Meta name="description" content=story.title.clone()/>
|
||||
<div class="item-view">
|
||||
<div class="item-view-header">
|
||||
<a href=story.url target="_blank">
|
||||
<h1>{story.title}</h1>
|
||||
</a>
|
||||
<span class="host">
|
||||
"("{story.domain}")"
|
||||
</span>
|
||||
<ShowLet some=story.user let:user>
|
||||
<p class="meta">
|
||||
{story.points}
|
||||
" points | by "
|
||||
<A href=format!("/users/{user}")>{user.clone()}</A>
|
||||
{format!(" {}", story.time_ago)}
|
||||
</p>
|
||||
</ShowLet>
|
||||
<a href=story.url target="_blank">
|
||||
<h1>{story.title}</h1>
|
||||
</a>
|
||||
<span class="host">
|
||||
"("{story.domain}")"
|
||||
</span>
|
||||
{story.user.map(|user| view! { <p class="meta">
|
||||
{story.points}
|
||||
" points | by "
|
||||
<A href=format!("/users/{user}")>{user.clone()}</A>
|
||||
{format!(" {}", story.time_ago)}
|
||||
</p>})}
|
||||
</div>
|
||||
<div class="item-view-comments">
|
||||
<p class="item-view-comments-header">
|
||||
|
||||
@@ -139,11 +139,14 @@ fn Story(story: api::Story) -> impl IntoView {
|
||||
Either::Left(
|
||||
view! {
|
||||
<span>
|
||||
"by "
|
||||
<ShowLet some=story.user let:user>
|
||||
<A href=format!("/users/{user}")>{user.clone()}</A>
|
||||
</ShowLet>
|
||||
{format!(" {} | ", story.time_ago)}
|
||||
{"by "}
|
||||
{story
|
||||
.user
|
||||
.map(|user| {
|
||||
view! {
|
||||
<A href=format!("/users/{user}")>{user.clone()}</A>
|
||||
}
|
||||
})} {format!(" {} | ", story.time_ago)}
|
||||
<A href=format!(
|
||||
"/stories/{}",
|
||||
story.id,
|
||||
|
||||
@@ -35,13 +35,17 @@ pub fn Story() -> impl IntoView {
|
||||
<h1>{story.title}</h1>
|
||||
</a>
|
||||
<span class="host">"("{story.domain}")"</span>
|
||||
<ShowLet some=story.user let:user>
|
||||
<p class="meta">
|
||||
{story.points} " points | by "
|
||||
<A href=format!("/users/{user}")>{user.clone()}</A>
|
||||
{format!(" {}", story.time_ago)}
|
||||
</p>
|
||||
</ShowLet>
|
||||
{story
|
||||
.user
|
||||
.map(|user| {
|
||||
view! {
|
||||
<p class="meta">
|
||||
{story.points} " points | by "
|
||||
<A href=format!("/users/{user}")>{user.clone()}</A>
|
||||
{format!(" {}", story.time_ago)}
|
||||
</p>
|
||||
}
|
||||
})}
|
||||
</div>
|
||||
<div class="item-view-comments">
|
||||
<p class="item-view-comments-header">
|
||||
|
||||
@@ -9,3 +9,6 @@ routing when you use islands.
|
||||
This uses *only* server rendering, with no actual islands, but still maintains client-side state across page navigations.
|
||||
It does this by building on the fact that we now have a statically-typed view tree to do pretty smart updates with
|
||||
new HTML from the client, with extremely minimal diffing.
|
||||
|
||||
The demo itself works, but the feature that supports it is incomplete. A couple people have accidentally
|
||||
used it and broken their applications in ways they don't understand, so I've renamed the feature to `dont-use-islands-router`.
|
||||
|
||||
@@ -10,7 +10,7 @@ crate-type = ["cdylib", "rlib"]
|
||||
axum = { version = "0.8.1", optional = true }
|
||||
console_error_panic_hook = "0.1.7"
|
||||
console_log = "1.0"
|
||||
leptos = { path = "../../leptos", features = ["tracing", "lazy"] }
|
||||
leptos = { path = "../../leptos", features = ["tracing"] }
|
||||
leptos_meta = { path = "../../meta" }
|
||||
leptos_axum = { path = "../../integrations/axum", optional = true }
|
||||
leptos_router = { path = "../../router" }
|
||||
|
||||
@@ -5,4 +5,4 @@ test cases that typically happens at integration.
|
||||
|
||||
## Quick Start
|
||||
|
||||
Run `cargo leptos watch --split` to run this example.
|
||||
Run `cargo leptos watch` to run this example.
|
||||
|
||||
@@ -17,7 +17,7 @@ leptos_router = { path = "../../router" }
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
thiserror = "2.0.12"
|
||||
tokio = { version = "1.39", features = [ "rt-multi-thread", "macros", "time" ], optional = true }
|
||||
wasm-bindgen = "0.2.106"
|
||||
wasm-bindgen = "0.2.92"
|
||||
|
||||
[features]
|
||||
hydrate = [
|
||||
|
||||
@@ -1,38 +0,0 @@
|
||||
@check_issue_4492
|
||||
Feature: Regression test for issue #4492
|
||||
|
||||
Scenario: Scenario A should show Loading once on first load.
|
||||
Given I see the app
|
||||
And I can access regression test 4492
|
||||
When I click the button a-toggle
|
||||
Then I see a-result has the text Loading...
|
||||
When I wait 100ms
|
||||
Then I see a-result has the text 0
|
||||
When I click the button a-button
|
||||
Then I see a-result has the text 0
|
||||
When I wait 100ms
|
||||
Then I see a-result has the text 1
|
||||
|
||||
Scenario: Scenario B should never show Loading
|
||||
Given I see the app
|
||||
And I can access regression test 4492
|
||||
When I click the button b-toggle
|
||||
Then I see b-result has the text 0
|
||||
When I click the button b-button
|
||||
Then I see b-result has the text 0
|
||||
When I wait 100ms
|
||||
Then I see b-result has the text 1
|
||||
When I click the button b-button
|
||||
Then I see b-result has the text 1
|
||||
When I wait 100ms
|
||||
Then I see b-result has the text 2
|
||||
|
||||
Scenario: Scenario C should never show Loading
|
||||
Given I see the app
|
||||
And I can access regression test 4492
|
||||
When I click the button c-toggle
|
||||
Then I see c-result has the text 0
|
||||
When I click the button c-button
|
||||
Then I see c-result has the text 42
|
||||
When I wait 100ms
|
||||
Then I see c-result has the text 1
|
||||
@@ -15,9 +15,3 @@ pub async fn click_link(client: &Client, text: &str) -> Result<()> {
|
||||
link.click().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn click_button(client: &Client, id: &str) -> Result<()> {
|
||||
let btn = find::element_by_id(&client, &id).await?;
|
||||
btn.click().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
10
examples/regression/e2e/tests/fixtures/check.rs
vendored
10
examples/regression/e2e/tests/fixtures/check.rs
vendored
@@ -7,15 +7,7 @@ pub async fn result_text_is(
|
||||
client: &Client,
|
||||
expected_text: &str,
|
||||
) -> Result<()> {
|
||||
element_text_is(client, "result", expected_text).await
|
||||
}
|
||||
|
||||
pub async fn element_text_is(
|
||||
client: &Client,
|
||||
id: &str,
|
||||
expected_text: &str,
|
||||
) -> Result<()> {
|
||||
let actual = find::text_at_id(client, id).await?;
|
||||
let actual = find::text_at_id(client, "result").await?;
|
||||
assert_eq!(&actual, expected_text);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -20,14 +20,6 @@ async fn i_select_the_link(world: &mut AppWorld, text: String) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[when(regex = "^I click the button (.*)$")]
|
||||
async fn i_click_the_button(world: &mut AppWorld, id: String) -> Result<()> {
|
||||
let client = &world.client;
|
||||
action::click_button(client, &id).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[given(expr = "I select the following links")]
|
||||
#[when(expr = "I select the following links")]
|
||||
async fn i_select_the_following_links(
|
||||
@@ -62,10 +54,3 @@ async fn i_go_back(world: &mut AppWorld) -> Result<()> {
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[when(regex = r"^I wait (\d+)ms$")]
|
||||
async fn i_wait_ms(_world: &mut AppWorld, ms: u64) -> Result<()> {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(ms)).await;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -19,17 +19,6 @@ async fn i_see_the_result_is_the_string(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[then(regex = r"^I see ([\w-]+) has the text (.*)$")]
|
||||
async fn i_see_element_has_text(
|
||||
world: &mut AppWorld,
|
||||
id: String,
|
||||
text: String,
|
||||
) -> Result<()> {
|
||||
let client = &world.client;
|
||||
check::element_text_is(client, &id, &text).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[then(regex = r"^I see the navbar$")]
|
||||
async fn i_see_the_navbar(world: &mut AppWorld) -> Result<()> {
|
||||
let client = &world.client;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use crate::{
|
||||
issue_4005::Routes4005, issue_4088::Routes4088, issue_4217::Routes4217,
|
||||
issue_4285::Routes4285, issue_4296::Routes4296, issue_4324::Routes4324,
|
||||
issue_4492::Routes4492, pr_4015::Routes4015, pr_4091::Routes4091,
|
||||
pr_4015::Routes4015, pr_4091::Routes4091,
|
||||
};
|
||||
use leptos::prelude::*;
|
||||
use leptos_meta::{MetaTags, *};
|
||||
@@ -48,7 +48,6 @@ pub fn App() -> impl IntoView {
|
||||
<Routes4285/>
|
||||
<Routes4296/>
|
||||
<Routes4324/>
|
||||
<Routes4492/>
|
||||
</Routes>
|
||||
</main>
|
||||
</Router>
|
||||
@@ -76,7 +75,6 @@ fn HomePage() -> impl IntoView {
|
||||
<li><a href="/4285/">"4285"</a></li>
|
||||
<li><a href="/4296/">"4296"</a></li>
|
||||
<li><a href="/4324/">"4324"</a></li>
|
||||
<li><a href="/4492/">"4492"</a></li>
|
||||
</ul>
|
||||
</nav>
|
||||
}
|
||||
|
||||
@@ -1,114 +0,0 @@
|
||||
use leptos::prelude::*;
|
||||
#[allow(unused_imports)]
|
||||
use leptos_router::{
|
||||
components::Route, path, MatchNestedRoutes, NavigateOptions,
|
||||
};
|
||||
|
||||
#[component]
|
||||
pub fn Routes4492() -> impl MatchNestedRoutes + Clone {
|
||||
view! {
|
||||
<Route path=path!("4492") view=Issue4492/>
|
||||
}
|
||||
.into_inner()
|
||||
}
|
||||
|
||||
#[component]
|
||||
fn Issue4492() -> impl IntoView {
|
||||
let show_a = RwSignal::new(false);
|
||||
let show_b = RwSignal::new(false);
|
||||
let show_c = RwSignal::new(false);
|
||||
|
||||
view! {
|
||||
<button id="a-toggle" on:click=move |_| show_a.set(!show_a.get())>"Toggle A"</button>
|
||||
<button id="b-toggle" on:click=move |_| show_b.set(!show_b.get())>"Toggle B"</button>
|
||||
<button id="c-toggle" on:click=move |_| show_c.set(!show_c.get())>"Toggle C"</button>
|
||||
|
||||
<Show when=move || show_a.get()>
|
||||
<ScenarioA/>
|
||||
</Show>
|
||||
<Show when=move || show_b.get()>
|
||||
<ScenarioB/>
|
||||
</Show>
|
||||
<Show when=move || show_c.get()>
|
||||
<ScenarioC/>
|
||||
</Show>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
fn ScenarioA() -> impl IntoView {
|
||||
// scenario A: one truly-async resource is read on click
|
||||
let counter = RwSignal::new(0);
|
||||
let resource = Resource::new(
|
||||
move || counter.get(),
|
||||
|count| async move {
|
||||
sleep(50).await.unwrap();
|
||||
count
|
||||
},
|
||||
);
|
||||
view! {
|
||||
<Transition fallback=|| view! { <p id="a-result">"Loading..."</p> }>
|
||||
<p id="a-result">{resource}</p>
|
||||
</Transition>
|
||||
<button id="a-button" on:click=move |_| *counter.write() += 1>"+1"</button>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
fn ScenarioB() -> impl IntoView {
|
||||
// scenario B: resource immediately available first time, then after 250ms
|
||||
let counter = RwSignal::new(0);
|
||||
let resource = Resource::new(
|
||||
move || counter.get(),
|
||||
|count| async move {
|
||||
if count == 0 {
|
||||
count
|
||||
} else {
|
||||
sleep(50).await.unwrap();
|
||||
count
|
||||
}
|
||||
},
|
||||
);
|
||||
view! {
|
||||
<Transition fallback=|| view! { <p id="b-result">"Loading..."</p> }>
|
||||
<p id="b-result">{resource}</p>
|
||||
</Transition>
|
||||
<button id="b-button" on:click=move |_| *counter.write() += 1>"+1"</button>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
fn ScenarioC() -> impl IntoView {
|
||||
// scenario C: not even a resource on the first run, just a value
|
||||
// see https://github.com/leptos-rs/leptos/issues/3868
|
||||
let counter = RwSignal::new(0);
|
||||
let s_res = StoredValue::new(None::<ArcLocalResource<i32>>);
|
||||
let resource = move || {
|
||||
let count = counter.get();
|
||||
if count == 0 {
|
||||
count
|
||||
} else {
|
||||
let r = s_res.get_value().unwrap_or_else(|| {
|
||||
let res = ArcLocalResource::new(move || async move {
|
||||
sleep(50).await.unwrap();
|
||||
count
|
||||
});
|
||||
s_res.set_value(Some(res.clone()));
|
||||
res
|
||||
});
|
||||
r.get().unwrap_or(42)
|
||||
}
|
||||
};
|
||||
view! {
|
||||
<Transition fallback=|| view! { <p id="c-result">"Loading..."</p> }>
|
||||
<p id="c-result">{resource}</p>
|
||||
</Transition>
|
||||
<button id="c-button" on:click=move |_| *counter.write() += 1>"+1"</button>
|
||||
}
|
||||
}
|
||||
|
||||
#[server]
|
||||
async fn sleep(ms: u64) -> Result<(), ServerFnError> {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(ms)).await;
|
||||
Ok(())
|
||||
}
|
||||
@@ -5,7 +5,6 @@ mod issue_4217;
|
||||
mod issue_4285;
|
||||
mod issue_4296;
|
||||
mod issue_4324;
|
||||
mod issue_4492;
|
||||
mod pr_4015;
|
||||
mod pr_4091;
|
||||
|
||||
|
||||
@@ -97,7 +97,7 @@ fn delay(
|
||||
duration: Duration,
|
||||
) -> impl Future<Output = Result<(), Canceled>> + Send {
|
||||
let (tx, rx) = oneshot::channel();
|
||||
_ = set_timeout(
|
||||
set_timeout(
|
||||
move || {
|
||||
_ = tx.send(());
|
||||
},
|
||||
|
||||
@@ -564,12 +564,17 @@ pub fn FileUploadWithProgress() -> impl IntoView {
|
||||
<input type="submit" />
|
||||
</form>
|
||||
{move || filename.get().map(|filename| view! { <p>Uploading {filename}</p> })}
|
||||
<ShowLet some=max let:max>
|
||||
<progress
|
||||
max=max
|
||||
value=move || current.get().unwrap_or_default()
|
||||
></progress>
|
||||
</ShowLet>
|
||||
{move || {
|
||||
max.get()
|
||||
.map(|max| {
|
||||
view! {
|
||||
<progress
|
||||
max=max
|
||||
value=move || current.get().unwrap_or_default()
|
||||
></progress>
|
||||
}
|
||||
})
|
||||
}}
|
||||
}
|
||||
}
|
||||
#[component]
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
#[cfg(feature = "ssr")]
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
use axum::{
|
||||
http::{HeaderName, HeaderValue},
|
||||
Router,
|
||||
};
|
||||
use axum::Router;
|
||||
use leptos::{logging::log, prelude::*};
|
||||
use leptos_axum::{generate_route_list, LeptosRoutes};
|
||||
use ssr_modes_axum::app::*;
|
||||
@@ -20,24 +17,7 @@ async fn main() {
|
||||
let leptos_options = leptos_options.clone();
|
||||
move || shell(leptos_options.clone())
|
||||
})
|
||||
.fallback(leptos_axum::file_and_error_handler_with_context(
|
||||
move || {
|
||||
// if you want to add custom headers to the static file handler response,
|
||||
// you can do that by providing `ResponseOptions` via context
|
||||
let opts = use_context::<leptos_axum::ResponseOptions>()
|
||||
.unwrap_or_default();
|
||||
opts.insert_header(
|
||||
HeaderName::from_static("cross-origin-opener-policy"),
|
||||
HeaderValue::from_static("same-origin"),
|
||||
);
|
||||
opts.insert_header(
|
||||
HeaderName::from_static("cross-origin-embedder-policy"),
|
||||
HeaderValue::from_static("require-corp"),
|
||||
);
|
||||
provide_context(opts);
|
||||
},
|
||||
shell,
|
||||
))
|
||||
.fallback(leptos_axum::file_and_error_handler(shell))
|
||||
.with_state(leptos_options);
|
||||
|
||||
// run our app with hyper
|
||||
|
||||
@@ -663,24 +663,26 @@ impl From<Vec<FieldNavItem>> for FieldNavCtx {
|
||||
#[component]
|
||||
pub fn FieldNavPortlet() -> impl IntoView {
|
||||
let ctx = expect_context::<ReadSignal<Option<FieldNavCtx>>>();
|
||||
|
||||
view! {
|
||||
<ShowLet some=ctx let:ctx>
|
||||
<div id="FieldNavPortlet">
|
||||
<span>"FieldNavPortlet:"</span>
|
||||
<nav>
|
||||
{ctx
|
||||
.0
|
||||
.map(|ctx| {
|
||||
ctx.into_iter()
|
||||
.map(|FieldNavItem { href, text }| {
|
||||
view! { <A href=href>{text}</A> }
|
||||
})
|
||||
.collect_view()
|
||||
})}
|
||||
</nav>
|
||||
</div>
|
||||
</ShowLet>
|
||||
move || {
|
||||
let ctx = ctx.get();
|
||||
ctx.map(|ctx| {
|
||||
view! {
|
||||
<div id="FieldNavPortlet">
|
||||
<span>"FieldNavPortlet:"</span>
|
||||
<nav>
|
||||
{ctx
|
||||
.0
|
||||
.map(|ctx| {
|
||||
ctx.into_iter()
|
||||
.map(|FieldNavItem { href, text }| {
|
||||
view! { <A href=href>{text}</A> }
|
||||
})
|
||||
.collect_view()
|
||||
})}
|
||||
</nav>
|
||||
</div>
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -50,7 +50,7 @@ where
|
||||
};
|
||||
|
||||
// here, we return the handle
|
||||
set_interval(
|
||||
set_interval_with_handle(
|
||||
f.clone(),
|
||||
// this is the only reactive access, so this effect will only
|
||||
// re-run when the interval changes
|
||||
|
||||
@@ -4,7 +4,7 @@ authors = ["Greg Johnston"]
|
||||
license = "MIT"
|
||||
repository = "https://github.com/leptos-rs/leptos"
|
||||
description = "Axum integrations for the Leptos web framework."
|
||||
version = "0.8.7"
|
||||
version = "0.8.6"
|
||||
rust-version.workspace = true
|
||||
edition.workspace = true
|
||||
|
||||
|
||||
@@ -684,7 +684,7 @@ where
|
||||
additional_context.clone(),
|
||||
app_fn.clone(),
|
||||
);
|
||||
let asyn = render_app_async_with_context(
|
||||
let asyn = render_app_async_stream_with_context(
|
||||
additional_context.clone(),
|
||||
app_fn.clone(),
|
||||
);
|
||||
@@ -1019,6 +1019,73 @@ where
|
||||
render_app_async_with_context(|| {}, app_fn)
|
||||
}
|
||||
|
||||
/// Returns an Axum [Handler](axum::handler::Handler) that listens for a `GET` request and tries
|
||||
/// to route it using [leptos_router], asynchronously rendering an HTML page after all
|
||||
/// `async` resources have loaded.
|
||||
///
|
||||
/// This version allows us to pass Axum State/Extension/Extractor or other info from Axum or network
|
||||
/// layers above Leptos itself. To use it, you'll need to write your own handler function that provides
|
||||
/// the data to leptos in a closure. An example is below
|
||||
/// ```
|
||||
/// use axum::{
|
||||
/// body::Body,
|
||||
/// extract::Path,
|
||||
/// http::Request,
|
||||
/// response::{IntoResponse, Response},
|
||||
/// };
|
||||
/// use leptos::context::provide_context;
|
||||
///
|
||||
/// async fn custom_handler(
|
||||
/// Path(id): Path<String>,
|
||||
/// req: Request<Body>,
|
||||
/// ) -> Response {
|
||||
/// let handler = leptos_axum::render_app_async_with_context(
|
||||
/// move || {
|
||||
/// provide_context(id.clone());
|
||||
/// },
|
||||
/// || { /* your application here */ },
|
||||
/// );
|
||||
/// handler(req).await.into_response()
|
||||
/// }
|
||||
/// ```
|
||||
/// Otherwise, this function is identical to [render_app_to_stream].
|
||||
///
|
||||
/// ## Provided Context Types
|
||||
/// This function always provides context values including the following types:
|
||||
/// - [`Parts`]
|
||||
/// - [`ResponseOptions`]
|
||||
/// - [`ServerMetaContext`]
|
||||
#[cfg_attr(
|
||||
feature = "tracing",
|
||||
tracing::instrument(level = "trace", fields(error), skip_all)
|
||||
)]
|
||||
pub fn render_app_async_stream_with_context<IV>(
|
||||
additional_context: impl Fn() + 'static + Clone + Send + Sync,
|
||||
app_fn: impl Fn() -> IV + Clone + Send + Sync + 'static,
|
||||
) -> impl Fn(
|
||||
Request<Body>,
|
||||
) -> Pin<Box<dyn Future<Output = Response<Body>> + Send + 'static>>
|
||||
+ Clone
|
||||
+ Send
|
||||
+ 'static
|
||||
where
|
||||
IV: IntoView + 'static,
|
||||
{
|
||||
handle_response(additional_context, app_fn, |app, chunks, _supports_ooo| {
|
||||
Box::pin(async move {
|
||||
let app = if cfg!(feature = "islands-router") {
|
||||
app.to_html_stream_in_order_branching()
|
||||
} else {
|
||||
app.to_html_stream_in_order()
|
||||
};
|
||||
let app = app.collect::<String>().await;
|
||||
let chunks = chunks();
|
||||
Box::pin(once(async move { app }).chain(chunks))
|
||||
as PinnedStream<String>
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns an Axum [Handler](axum::handler::Handler) that listens for a `GET` request and tries
|
||||
/// to route it using [leptos_router], asynchronously rendering an HTML page after all
|
||||
/// `async` resources have loaded.
|
||||
@@ -1983,20 +2050,7 @@ where
|
||||
let res = res.await.unwrap();
|
||||
|
||||
if res.status() == StatusCode::OK {
|
||||
let owner = Owner::new();
|
||||
owner.with(|| {
|
||||
additional_context();
|
||||
let res = res.into_response();
|
||||
if let Some(response_options) =
|
||||
use_context::<ResponseOptions>()
|
||||
{
|
||||
let mut res = AxumResponse(res);
|
||||
res.extend_response(&response_options);
|
||||
res.0
|
||||
} else {
|
||||
res
|
||||
}
|
||||
})
|
||||
res.into_response()
|
||||
} else {
|
||||
let mut res = handle_response_inner(
|
||||
move || {
|
||||
@@ -2005,7 +2059,19 @@ where
|
||||
},
|
||||
move || shell(options),
|
||||
req,
|
||||
async_stream_builder,
|
||||
|app, chunks, _supports_ooo| {
|
||||
Box::pin(async move {
|
||||
let app = if cfg!(feature = "islands-router") {
|
||||
app.to_html_stream_in_order_branching()
|
||||
} else {
|
||||
app.to_html_stream_in_order()
|
||||
};
|
||||
let app = app.collect::<String>().await;
|
||||
let chunks = chunks();
|
||||
Box::pin(once(async move { app }).chain(chunks))
|
||||
as PinnedStream<String>
|
||||
})
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ authors = ["Greg Johnston"]
|
||||
license = "MIT"
|
||||
repository = "https://github.com/leptos-rs/leptos"
|
||||
description = "Utilities to help build server integrations for the Leptos web framework."
|
||||
version = "0.8.7"
|
||||
version = "0.8.6"
|
||||
rust-version.workspace = true
|
||||
edition.workspace = true
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "leptos"
|
||||
version = "0.8.15"
|
||||
version = "0.8.12"
|
||||
authors = ["Greg Johnston"]
|
||||
license = "MIT"
|
||||
repository = "https://github.com/leptos-rs/leptos"
|
||||
@@ -122,7 +122,6 @@ subsecond = [
|
||||
"web-sys/WebSocket",
|
||||
"web-sys/Window",
|
||||
]
|
||||
lazy = ["tachys/lazy"]
|
||||
|
||||
[dev-dependencies]
|
||||
tokio = { features = [
|
||||
|
||||
@@ -83,7 +83,7 @@ pub fn AnimatedShow(
|
||||
} else {
|
||||
cls.set(hide_class);
|
||||
|
||||
let h = leptos_dom::helpers::set_timeout(
|
||||
let h = leptos_dom::helpers::set_timeout_with_handle(
|
||||
move || show.set(false),
|
||||
hide_delay,
|
||||
)
|
||||
|
||||
@@ -2,19 +2,48 @@
|
||||
//! for component properties, because they can be used to define optional callback functions,
|
||||
//! which generic props don’t support.
|
||||
//!
|
||||
//! The callback types implement [`Copy`], so they can easily be moved into and out of other closures, just like signals.
|
||||
//! # Usage
|
||||
//! Callbacks can be created manually from any function or closure, but the easiest way
|
||||
//! to create them is to use `#[prop(into)]]` when defining a component.
|
||||
//! ```
|
||||
//! use leptos::prelude::*;
|
||||
//!
|
||||
//! #[component]
|
||||
//! fn MyComponent(
|
||||
//! #[prop(into)] render_number: Callback<(i32,), String>,
|
||||
//! ) -> impl IntoView {
|
||||
//! view! {
|
||||
//! <div>
|
||||
//! {render_number.run((1,))}
|
||||
//! // callbacks can be called multiple times
|
||||
//! {render_number.run((42,))}
|
||||
//! </div>
|
||||
//! }
|
||||
//! }
|
||||
//! // you can pass a closure directly as `render_number`
|
||||
//! fn test() -> impl IntoView {
|
||||
//! view! {
|
||||
//! <MyComponent render_number=|x: i32| x.to_string()/>
|
||||
//! }
|
||||
//! }
|
||||
//! ```
|
||||
//!
|
||||
//! *Notes*:
|
||||
//! - The `render_number` prop can receive any type that implements `Fn(i32) -> String`.
|
||||
//! - Callbacks are most useful when you want optional generic props.
|
||||
//! - All callbacks implement the [`Callable`](leptos::callback::Callable) trait, and can be invoked with `my_callback.run(input)`.
|
||||
//! - The callback types implement [`Copy`], so they can easily be moved into and out of other closures, just like signals.
|
||||
//!
|
||||
//! # Types
|
||||
//! This modules implements 2 callback types:
|
||||
//! - [`Callback`](reactive_graph::callback::Callback)
|
||||
//! - [`UnsyncCallback`](reactive_graph::callback::UnsyncCallback)
|
||||
//! - [`Callback`](leptos::callback::Callback)
|
||||
//! - [`UnsyncCallback`](leptos::callback::UnsyncCallback)
|
||||
//!
|
||||
//! Use `SyncCallback` if the function is not `Sync` and `Send`.
|
||||
|
||||
use crate::{
|
||||
use reactive_graph::{
|
||||
owner::{LocalStorage, StoredValue},
|
||||
traits::{Dispose, WithValue},
|
||||
IntoReactiveValue,
|
||||
};
|
||||
use std::{fmt, rc::Rc, sync::Arc};
|
||||
|
||||
@@ -31,16 +60,7 @@ pub trait Callable<In: 'static, Out: 'static = ()> {
|
||||
fn run(&self, input: In) -> Out;
|
||||
}
|
||||
|
||||
/// A callback type that is not required to be [`Send`] or [`Sync`].
|
||||
///
|
||||
/// # Example
|
||||
/// ```
|
||||
/// # use reactive_graph::prelude::*; use reactive_graph::callback::*; let owner = reactive_graph::owner::Owner::new(); owner.set();
|
||||
/// let _: UnsyncCallback<()> = UnsyncCallback::new(|_| {});
|
||||
/// let _: UnsyncCallback<(i32, i32)> = (|_x: i32, _y: i32| {}).into();
|
||||
/// let cb: UnsyncCallback<i32, String> = UnsyncCallback::new(|x: i32| x.to_string());
|
||||
/// assert_eq!(cb.run(42), "42".to_string());
|
||||
/// ```
|
||||
/// A callback type that is not required to be `Send + Sync`.
|
||||
pub struct UnsyncCallback<In: 'static, Out: 'static = ()>(
|
||||
StoredValue<Rc<dyn Fn(In) -> Out>, LocalStorage>,
|
||||
);
|
||||
@@ -128,15 +148,28 @@ impl_unsync_callable_from_fn!(
|
||||
P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12
|
||||
);
|
||||
|
||||
/// A callback type that is [`Send`] + [`Sync`].
|
||||
/// Callbacks define a standard way to store functions and closures.
|
||||
///
|
||||
/// # Example
|
||||
/// ```
|
||||
/// # use reactive_graph::prelude::*; use reactive_graph::callback::*; let owner = reactive_graph::owner::Owner::new(); owner.set();
|
||||
/// let _: Callback<()> = Callback::new(|_| {});
|
||||
/// let _: Callback<(i32, i32)> = (|_x: i32, _y: i32| {}).into();
|
||||
/// let cb: Callback<i32, String> = Callback::new(|x: i32| x.to_string());
|
||||
/// assert_eq!(cb.run(42), "42".to_string());
|
||||
/// # use leptos::prelude::*;
|
||||
/// # use leptos::callback::{Callable, Callback};
|
||||
/// #[component]
|
||||
/// fn MyComponent(
|
||||
/// #[prop(into)] render_number: Callback<(i32,), String>,
|
||||
/// ) -> impl IntoView {
|
||||
/// view! {
|
||||
/// <div>
|
||||
/// {render_number.run((42,))}
|
||||
/// </div>
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// fn test() -> impl IntoView {
|
||||
/// view! {
|
||||
/// <MyComponent render_number=move |x: i32| x.to_string()/>
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
pub struct Callback<In, Out = ()>(
|
||||
StoredValue<Arc<dyn Fn(In) -> Out + Send + Sync>>,
|
||||
@@ -208,7 +241,6 @@ impl_callable_from_fn!(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12);
|
||||
|
||||
impl<In: 'static, Out: 'static> Callback<In, Out> {
|
||||
/// Creates a new callback from the given function.
|
||||
#[track_caller]
|
||||
pub fn new<F>(fun: F) -> Self
|
||||
where
|
||||
F: Fn(In) -> Out + Send + Sync + 'static,
|
||||
@@ -230,94 +262,22 @@ impl<In: 'static, Out: 'static> Callback<In, Out> {
|
||||
}
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub struct __IntoReactiveValueMarkerCallbackSingleParam;
|
||||
|
||||
#[doc(hidden)]
|
||||
pub struct __IntoReactiveValueMarkerCallbackStrOutputToString;
|
||||
|
||||
impl<I, O, F>
|
||||
IntoReactiveValue<
|
||||
Callback<I, O>,
|
||||
__IntoReactiveValueMarkerCallbackSingleParam,
|
||||
> for F
|
||||
where
|
||||
F: Fn(I) -> O + Send + Sync + 'static,
|
||||
{
|
||||
#[track_caller]
|
||||
fn into_reactive_value(self) -> Callback<I, O> {
|
||||
Callback::new(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl<I, O, F>
|
||||
IntoReactiveValue<
|
||||
UnsyncCallback<I, O>,
|
||||
__IntoReactiveValueMarkerCallbackSingleParam,
|
||||
> for F
|
||||
where
|
||||
F: Fn(I) -> O + 'static,
|
||||
{
|
||||
#[track_caller]
|
||||
fn into_reactive_value(self) -> UnsyncCallback<I, O> {
|
||||
UnsyncCallback::new(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl<I, F>
|
||||
IntoReactiveValue<
|
||||
Callback<I, String>,
|
||||
__IntoReactiveValueMarkerCallbackStrOutputToString,
|
||||
> for F
|
||||
where
|
||||
F: Fn(I) -> &'static str + Send + Sync + 'static,
|
||||
{
|
||||
#[track_caller]
|
||||
fn into_reactive_value(self) -> Callback<I, String> {
|
||||
Callback::new(move |i| self(i).to_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl<I, F>
|
||||
IntoReactiveValue<
|
||||
UnsyncCallback<I, String>,
|
||||
__IntoReactiveValueMarkerCallbackStrOutputToString,
|
||||
> for F
|
||||
where
|
||||
F: Fn(I) -> &'static str + 'static,
|
||||
{
|
||||
#[track_caller]
|
||||
fn into_reactive_value(self) -> UnsyncCallback<I, String> {
|
||||
UnsyncCallback::new(move |i| self(i).to_string())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::Callable;
|
||||
use crate::{
|
||||
callback::{Callback, UnsyncCallback},
|
||||
owner::Owner,
|
||||
traits::Dispose,
|
||||
IntoReactiveValue,
|
||||
};
|
||||
use crate::callback::{Callback, UnsyncCallback};
|
||||
use reactive_graph::traits::Dispose;
|
||||
|
||||
struct NoClone {}
|
||||
|
||||
#[test]
|
||||
fn clone_callback() {
|
||||
let owner = Owner::new();
|
||||
owner.set();
|
||||
|
||||
let callback = Callback::new(move |_no_clone: NoClone| NoClone {});
|
||||
let _cloned = callback;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clone_unsync_callback() {
|
||||
let owner = Owner::new();
|
||||
owner.set();
|
||||
|
||||
let callback =
|
||||
UnsyncCallback::new(move |_no_clone: NoClone| NoClone {});
|
||||
let _cloned = callback;
|
||||
@@ -325,39 +285,20 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn runback_from() {
|
||||
let owner = Owner::new();
|
||||
owner.set();
|
||||
|
||||
let _callback: Callback<(), String> = (|| "test").into();
|
||||
let _callback: Callback<(i32, String), String> =
|
||||
(|num, s| format!("{num} {s}")).into();
|
||||
// Single params should work without needing the (foo,) tuple using IntoReactiveValue:
|
||||
let _callback: Callback<usize, &'static str> =
|
||||
(|_usize| "test").into_reactive_value();
|
||||
let _callback: Callback<usize, String> =
|
||||
(|_usize| "test").into_reactive_value();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sync_callback_from() {
|
||||
let owner = Owner::new();
|
||||
owner.set();
|
||||
|
||||
let _callback: UnsyncCallback<(), String> = (|| "test").into();
|
||||
let _callback: UnsyncCallback<(i32, String), String> =
|
||||
(|num, s| format!("{num} {s}")).into();
|
||||
// Single params should work without needing the (foo,) tuple using IntoReactiveValue:
|
||||
let _callback: UnsyncCallback<usize, &'static str> =
|
||||
(|_usize| "test").into_reactive_value();
|
||||
let _callback: UnsyncCallback<usize, String> =
|
||||
(|_usize| "test").into_reactive_value();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sync_callback_try_run() {
|
||||
let owner = Owner::new();
|
||||
owner.set();
|
||||
|
||||
let callback = Callback::new(move |arg| arg);
|
||||
assert_eq!(callback.try_run((0,)), Some((0,)));
|
||||
callback.dispose();
|
||||
@@ -366,9 +307,6 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn unsync_callback_try_run() {
|
||||
let owner = Owner::new();
|
||||
owner.set();
|
||||
|
||||
let callback = UnsyncCallback::new(move |arg| arg);
|
||||
assert_eq!(callback.try_run((0,)), Some((0,)));
|
||||
callback.dispose();
|
||||
@@ -377,9 +315,6 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn callback_matches_same() {
|
||||
let owner = Owner::new();
|
||||
owner.set();
|
||||
|
||||
let callback1 = Callback::new(|x: i32| x * 2);
|
||||
let callback2 = callback1;
|
||||
assert!(callback1.matches(&callback2));
|
||||
@@ -387,9 +322,6 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn callback_matches_different() {
|
||||
let owner = Owner::new();
|
||||
owner.set();
|
||||
|
||||
let callback1 = Callback::new(|x: i32| x * 2);
|
||||
let callback2 = Callback::new(|x: i32| x + 1);
|
||||
assert!(!callback1.matches(&callback2));
|
||||
@@ -397,9 +329,6 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn unsync_callback_matches_same() {
|
||||
let owner = Owner::new();
|
||||
owner.set();
|
||||
|
||||
let callback1 = UnsyncCallback::new(|x: i32| x * 2);
|
||||
let callback2 = callback1;
|
||||
assert!(callback1.matches(&callback2));
|
||||
@@ -407,9 +336,6 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn unsync_callback_matches_different() {
|
||||
let owner = Owner::new();
|
||||
owner.set();
|
||||
|
||||
let callback1 = UnsyncCallback::new(|x: i32| x * 2);
|
||||
let callback2 = UnsyncCallback::new(|x: i32| x + 1);
|
||||
assert!(!callback1.matches(&callback2));
|
||||
@@ -287,9 +287,7 @@ where
|
||||
web_sys::UrlSearchParams::new_with_str_sequence_sequence(form_data)
|
||||
.unwrap_throw();
|
||||
let data = data.to_string().as_string().unwrap_or_default();
|
||||
serde_qs::Config::new()
|
||||
.use_form_encoding(true)
|
||||
.deserialize_str::<Self>(&data)
|
||||
serde_qs::Config::new(5, false).deserialize_str::<Self>(&data)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,42 +1,25 @@
|
||||
if (window.location.protocol === "https:") {
|
||||
protocol = "wss://";
|
||||
if (window.location.protocol === 'https:') {
|
||||
protocol = 'wss://';
|
||||
}
|
||||
|
||||
let host = window.location.hostname;
|
||||
|
||||
function connect() {
|
||||
let ws = new WebSocket(`${protocol}${host}:${reload_port}/live_reload`);
|
||||
|
||||
ws.onmessage = (ev) => {
|
||||
let msg = JSON.parse(ev.data);
|
||||
if (msg.all) window.location.reload();
|
||||
if (msg.css) {
|
||||
let found = false;
|
||||
document.querySelectorAll("link").forEach((link) => {
|
||||
if (link.getAttribute("href").includes(msg.css)) {
|
||||
let newHref = "/" + msg.css + "?version=" + Date.now();
|
||||
link.setAttribute("href", newHref);
|
||||
found = true;
|
||||
}
|
||||
});
|
||||
if (!found)
|
||||
console.warn(
|
||||
`CSS hot-reload: Could not find a <link href=/\"${msg.css}\"> element`,
|
||||
);
|
||||
}
|
||||
if (msg.view) {
|
||||
patch(msg.view);
|
||||
}
|
||||
let ws = new WebSocket(`${protocol}${host}:${reload_port}/live_reload`);
|
||||
ws.onmessage = (ev) => {
|
||||
let msg = JSON.parse(ev.data);
|
||||
if (msg.all) window.location.reload();
|
||||
if (msg.css) {
|
||||
let found = false;
|
||||
document.querySelectorAll("link").forEach((link) => {
|
||||
if (link.getAttribute('href').includes(msg.css)) {
|
||||
let newHref = '/' + msg.css + '?version=' + Date.now();
|
||||
link.setAttribute('href', newHref);
|
||||
found = true;
|
||||
}
|
||||
});
|
||||
if (!found) console.warn(`CSS hot-reload: Could not find a <link href=/\"${msg.css}\"> element`);
|
||||
};
|
||||
|
||||
ws.onclose = () => {
|
||||
console.warn("Live-reload disconnected. Reconnecting...");
|
||||
setTimeout(connect, 1000);
|
||||
};
|
||||
|
||||
ws.onerror = () => {
|
||||
ws.close();
|
||||
};
|
||||
}
|
||||
|
||||
connect();
|
||||
if(msg.view) {
|
||||
patch(msg.view);
|
||||
}
|
||||
};
|
||||
ws.onclose = () => console.warn('Live-reload stopped. Manual reload necessary.');
|
||||
|
||||
@@ -203,7 +203,7 @@ pub mod prelude {
|
||||
pub mod form;
|
||||
|
||||
/// A standard way to wrap functions and closures to pass them to components.
|
||||
pub use reactive_graph::callback;
|
||||
pub mod callback;
|
||||
|
||||
/// Types that can be passed as the `children` prop of a component.
|
||||
pub mod children;
|
||||
|
||||
@@ -160,16 +160,3 @@ where
|
||||
OptionGetter(Arc::new(move || cloned.get()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Marker type for creating an `OptionGetter` from a static value.
|
||||
/// Used so that the compiler doesn't complain about double implementations of the trait `IntoOptionGetter`.
|
||||
pub struct StaticMarker;
|
||||
|
||||
impl<T> IntoOptionGetter<T, StaticMarker> for Option<T>
|
||||
where
|
||||
T: Clone + Send + Sync + 'static,
|
||||
{
|
||||
fn into_option_getter(self) -> OptionGetter<T> {
|
||||
OptionGetter(Arc::new(move || self.clone()))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,7 +6,6 @@ use crate::{
|
||||
use futures::{channel::oneshot, select, FutureExt};
|
||||
use hydration_context::SerializedDataId;
|
||||
use leptos_macro::component;
|
||||
use or_poisoned::OrPoisoned;
|
||||
use reactive_graph::{
|
||||
computed::{
|
||||
suspense::{LocalResourceNotifier, SuspenseContext},
|
||||
@@ -15,13 +14,10 @@ use reactive_graph::{
|
||||
effect::RenderEffect,
|
||||
owner::{provide_context, use_context, Owner},
|
||||
signal::ArcRwSignal,
|
||||
traits::{
|
||||
Dispose, Get, Read, ReadUntracked, Track, With, WithUntracked,
|
||||
WriteValue,
|
||||
},
|
||||
traits::{Dispose, Get, Read, Track, With, WriteValue},
|
||||
};
|
||||
use slotmap::{DefaultKey, SlotMap};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::sync::Arc;
|
||||
use tachys::{
|
||||
either::Either,
|
||||
html::attribute::{any_attribute::AnyAttribute, Attribute},
|
||||
@@ -122,19 +118,14 @@ where
|
||||
provide_context(SuspenseContext {
|
||||
tasks: tasks.clone(),
|
||||
});
|
||||
let none_pending = ArcMemo::new({
|
||||
let tasks = tasks.clone();
|
||||
move |prev: Option<&bool>| {
|
||||
tasks.track();
|
||||
if prev.is_none() && starts_local {
|
||||
false
|
||||
} else {
|
||||
tasks.with(SlotMap::is_empty)
|
||||
}
|
||||
let none_pending = ArcMemo::new(move |prev: Option<&bool>| {
|
||||
tasks.track();
|
||||
if prev.is_none() && starts_local {
|
||||
false
|
||||
} else {
|
||||
tasks.with(SlotMap::is_empty)
|
||||
}
|
||||
});
|
||||
let has_tasks =
|
||||
Arc::new(move || !tasks.with_untracked(SlotMap::is_empty));
|
||||
|
||||
OwnedView::new(SuspenseBoundary::<false, _, _> {
|
||||
id,
|
||||
@@ -142,7 +133,6 @@ where
|
||||
fallback,
|
||||
children,
|
||||
error_boundary_parent,
|
||||
has_tasks,
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -165,7 +155,6 @@ pub(crate) struct SuspenseBoundary<const TRANSITION: bool, Fal, Chil> {
|
||||
pub fallback: Fal,
|
||||
pub children: Chil,
|
||||
pub error_boundary_parent: Option<ErrorBoundarySuspendedChildren>,
|
||||
pub has_tasks: Arc<dyn Fn() -> bool + Send + Sync>,
|
||||
}
|
||||
|
||||
impl<const TRANSITION: bool, Fal, Chil> Render
|
||||
@@ -202,26 +191,12 @@ where
|
||||
outer_owner.clone(),
|
||||
);
|
||||
|
||||
let state = if let Some(mut state) = prev {
|
||||
if let Some(mut state) = prev {
|
||||
this.rebuild(&mut state);
|
||||
state
|
||||
} else {
|
||||
this.build()
|
||||
};
|
||||
|
||||
if nth_run == 1 && !(self.has_tasks)() {
|
||||
// if this is the first run, and there are no pending resources at this point,
|
||||
// it means that there were no actually-async resources read while rendering the children
|
||||
// this means that we're effectively on the settled second run: none_pending
|
||||
// won't change false => true and cause this to rerender (and therefore increment nth_run)
|
||||
//
|
||||
// we increment it manually here so that future resource changes won't cause the transition fallback
|
||||
// to be displayed for the first time
|
||||
// see https://github.com/leptos-rs/leptos/issues/3868, https://github.com/leptos-rs/leptos/issues/4492
|
||||
nth_run += 1;
|
||||
}
|
||||
|
||||
state
|
||||
})
|
||||
}
|
||||
|
||||
@@ -259,7 +234,6 @@ where
|
||||
fallback,
|
||||
children,
|
||||
error_boundary_parent,
|
||||
has_tasks,
|
||||
} = self;
|
||||
SuspenseBoundary {
|
||||
id,
|
||||
@@ -267,7 +241,6 @@ where
|
||||
fallback,
|
||||
children: children.add_any_attr(attr),
|
||||
error_boundary_parent,
|
||||
has_tasks,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -347,66 +320,23 @@ where
|
||||
|
||||
// walk over the tree of children once to make sure that all resource loads are registered
|
||||
self.children.dry_resolve();
|
||||
let children = Arc::new(Mutex::new(Some(self.children)));
|
||||
|
||||
// check the set of tasks to see if it is empty, now or later
|
||||
let eff = reactive_graph::effect::Effect::new_isomorphic({
|
||||
let children = Arc::clone(&children);
|
||||
move |double_checking: Option<bool>| {
|
||||
// on the first run, always track the tasks
|
||||
if double_checking.is_none() {
|
||||
tasks.track();
|
||||
}
|
||||
|
||||
if let Some(curr_tasks) = tasks.try_read_untracked() {
|
||||
if curr_tasks.is_empty() {
|
||||
if double_checking == Some(true) {
|
||||
// we have finished loading, and checking the children again told us there are
|
||||
// no more pending tasks. so we can render both the children and the error boundary
|
||||
|
||||
if let Some(tx) = tasks_tx.take() {
|
||||
// If the receiver has dropped, it means the ScopedFuture has already
|
||||
// dropped, so it doesn't matter if we manage to send this.
|
||||
_ = tx.send(());
|
||||
}
|
||||
if let Some(tx) = notify_error_boundary.take() {
|
||||
_ = tx.send(());
|
||||
}
|
||||
} else {
|
||||
// release the read guard on tasks, as we'll be updating it again
|
||||
drop(curr_tasks);
|
||||
// check the children for additional pending tasks
|
||||
// the will catch additional resource reads nested inside a conditional depending on initial resource reads
|
||||
if let Some(children) =
|
||||
children.lock().or_poisoned().as_mut()
|
||||
{
|
||||
children.dry_resolve();
|
||||
}
|
||||
|
||||
if tasks
|
||||
.try_read()
|
||||
.map(|n| n.is_empty())
|
||||
.unwrap_or(false)
|
||||
{
|
||||
// there are no additional pending tasks, and we can simply return
|
||||
if let Some(tx) = tasks_tx.take() {
|
||||
// If the receiver has dropped, it means the ScopedFuture has already
|
||||
// dropped, so it doesn't matter if we manage to send this.
|
||||
_ = tx.send(());
|
||||
}
|
||||
if let Some(tx) = notify_error_boundary.take() {
|
||||
_ = tx.send(());
|
||||
}
|
||||
}
|
||||
|
||||
// tell ourselves that we're just double-checking
|
||||
return true;
|
||||
move |_| {
|
||||
tasks.track();
|
||||
if let Some(tasks) = tasks.try_read() {
|
||||
if tasks.is_empty() {
|
||||
if let Some(tx) = tasks_tx.take() {
|
||||
// If the receiver has dropped, it means the ScopedFuture has already
|
||||
// dropped, so it doesn't matter if we manage to send this.
|
||||
_ = tx.send(());
|
||||
}
|
||||
if let Some(tx) = notify_error_boundary.take() {
|
||||
_ = tx.send(());
|
||||
}
|
||||
} else {
|
||||
tasks.track();
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
});
|
||||
|
||||
@@ -432,17 +362,12 @@ where
|
||||
None
|
||||
}
|
||||
_ = tasks_rx => {
|
||||
let children = {
|
||||
let mut children_lock = children.lock().or_poisoned();
|
||||
children_lock.take().expect("children should not be removed until we render here")
|
||||
};
|
||||
|
||||
// if we ran this earlier, reactive reads would always be registered as None
|
||||
// this is fine in the case where we want to use Suspend and .await on some future
|
||||
// but in situations like a <For each=|| some_resource.snapshot()/> we actually
|
||||
// want to be able to 1) synchronously read a resource's value, but still 2) wait
|
||||
// for it to load before we render everything
|
||||
let mut children = Box::pin(children.resolve().fuse());
|
||||
let mut children = Box::pin(self.children.resolve().fuse());
|
||||
|
||||
// we continue racing the children against the "do we have any local
|
||||
// resources?" Future
|
||||
|
||||
@@ -10,11 +10,10 @@ use reactive_graph::{
|
||||
effect::Effect,
|
||||
owner::{provide_context, use_context, Owner},
|
||||
signal::ArcRwSignal,
|
||||
traits::{Get, Set, Track, With, WithUntracked},
|
||||
traits::{Get, Set, Track, With},
|
||||
wrappers::write::SignalSetter,
|
||||
};
|
||||
use slotmap::{DefaultKey, SlotMap};
|
||||
use std::sync::Arc;
|
||||
use tachys::reactive_graph::OwnedView;
|
||||
|
||||
/// If any [`Resource`](crate::prelude::Resource) is read in the `children` of this
|
||||
@@ -105,19 +104,14 @@ where
|
||||
provide_context(SuspenseContext {
|
||||
tasks: tasks.clone(),
|
||||
});
|
||||
let none_pending = ArcMemo::new({
|
||||
let tasks = tasks.clone();
|
||||
move |prev: Option<&bool>| {
|
||||
tasks.track();
|
||||
if prev.is_none() && starts_local {
|
||||
false
|
||||
} else {
|
||||
tasks.with(SlotMap::is_empty)
|
||||
}
|
||||
let none_pending = ArcMemo::new(move |prev: Option<&bool>| {
|
||||
tasks.track();
|
||||
if prev.is_none() && starts_local {
|
||||
false
|
||||
} else {
|
||||
tasks.with(SlotMap::is_empty)
|
||||
}
|
||||
});
|
||||
let has_tasks =
|
||||
Arc::new(move || !tasks.with_untracked(SlotMap::is_empty));
|
||||
if let Some(set_pending) = set_pending {
|
||||
Effect::new_isomorphic({
|
||||
let none_pending = none_pending.clone();
|
||||
@@ -133,7 +127,6 @@ where
|
||||
fallback,
|
||||
children,
|
||||
error_boundary_parent,
|
||||
has_tasks,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -103,76 +103,6 @@ fn test_classes() {
|
||||
assert_eq!(rendered.to_html(), "<div class=\"my big red car\"></div>");
|
||||
}
|
||||
|
||||
#[cfg(feature = "ssr")]
|
||||
#[test]
|
||||
fn test_class_with_class_directive_merge() {
|
||||
use leptos::prelude::*;
|
||||
|
||||
// class= followed by class: should merge
|
||||
let rendered: View<HtmlElement<_, _, _>> = view! {
|
||||
<div class="foo" class:bar=true></div>
|
||||
};
|
||||
|
||||
assert_eq!(rendered.to_html(), "<div class=\"foo bar\"></div>");
|
||||
}
|
||||
|
||||
#[cfg(feature = "ssr")]
|
||||
#[test]
|
||||
fn test_solo_class_directive() {
|
||||
use leptos::prelude::*;
|
||||
|
||||
// Solo class: directive should work without class attribute
|
||||
let rendered: View<HtmlElement<_, _, _>> = view! {
|
||||
<div class:foo=true></div>
|
||||
};
|
||||
|
||||
assert_eq!(rendered.to_html(), "<div class=\"foo\"></div>");
|
||||
}
|
||||
|
||||
#[cfg(feature = "ssr")]
|
||||
#[test]
|
||||
fn test_class_directive_with_static_class() {
|
||||
use leptos::prelude::*;
|
||||
|
||||
// class:foo comes after class= due to macro sorting
|
||||
// The class= clears buffer, then class:foo appends
|
||||
let rendered: View<HtmlElement<_, _, _>> = view! {
|
||||
<div class:foo=true class="bar"></div>
|
||||
};
|
||||
|
||||
// After macro sorting: class="bar" class:foo=true
|
||||
// Expected: "bar foo"
|
||||
assert_eq!(rendered.to_html(), "<div class=\"bar foo\"></div>");
|
||||
}
|
||||
|
||||
#[cfg(feature = "ssr")]
|
||||
#[test]
|
||||
fn test_global_class_applied() {
|
||||
use leptos::prelude::*;
|
||||
|
||||
// Test that a global class is properly applied
|
||||
let rendered: View<HtmlElement<_, _, _>> = view! { class="global",
|
||||
<div></div>
|
||||
};
|
||||
|
||||
assert_eq!(rendered.to_html(), "<div class=\"global\"></div>");
|
||||
}
|
||||
|
||||
#[cfg(feature = "ssr")]
|
||||
#[test]
|
||||
fn test_multiple_class_attributes_overwrite() {
|
||||
use leptos::prelude::*;
|
||||
|
||||
// When multiple class attributes are applied, the last one should win (browser behavior)
|
||||
// This simulates what happens when attributes are combined programmatically
|
||||
let el = leptos::html::div().class("first").class("second");
|
||||
|
||||
let html = el.to_html();
|
||||
|
||||
// The second class attribute should overwrite the first
|
||||
assert_eq!(html, "<div class=\"second\"></div>");
|
||||
}
|
||||
|
||||
#[cfg(feature = "ssr")]
|
||||
#[test]
|
||||
fn ssr_with_styles() {
|
||||
|
||||
@@ -5,7 +5,7 @@ license = "MIT"
|
||||
repository = "https://github.com/leptos-rs/leptos"
|
||||
description = "Configuration for the Leptos web framework."
|
||||
readme = "../README.md"
|
||||
version = "0.8.8"
|
||||
version = "0.8.7"
|
||||
rust-version.workspace = true
|
||||
edition.workspace = true
|
||||
|
||||
|
||||
@@ -73,14 +73,14 @@ where
|
||||
let to = to.into_iter().collect::<Vec<_>>();
|
||||
|
||||
let (list, set_list) = create_signal(from.clone());
|
||||
_ = request_animation_frame({
|
||||
request_animation_frame({
|
||||
let to = to.clone();
|
||||
let then = then.clone();
|
||||
move || {
|
||||
set_list(to);
|
||||
|
||||
if let Some(then) = then {
|
||||
_ = request_animation_frame({
|
||||
request_animation_frame({
|
||||
move || {
|
||||
set_list(then);
|
||||
}
|
||||
|
||||
@@ -116,7 +116,7 @@ pub fn event_target_checked(ev: &web_sys::Event) -> bool {
|
||||
.checked()
|
||||
}
|
||||
|
||||
/// Handle that is generated by [request_animation_frame] and can
|
||||
/// Handle that is generated by [request_animation_frame_with_handle] and can
|
||||
/// be used to cancel the animation frame request.
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct AnimationFrameRequestHandle(i32);
|
||||
@@ -129,6 +129,18 @@ impl AnimationFrameRequestHandle {
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs the given function between the next repaint using
|
||||
/// [`Window.requestAnimationFrame`](https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame).
|
||||
///
|
||||
/// ### Note about Context
|
||||
///
|
||||
/// The callback is called outside of the reactive ownership tree. This means that it does not have access to context via [`use_context`](reactive_graph::owner::use_context). If you want to use context inside the callback, you should either call `use_context` in the body of the component, and move the value into the callback, or access the current owner inside the component body using [`Owner::current`](reactive_graph::owner::Owner::current) and reestablish it in the callback with [`Owner::with`](reactive_graph::owner::Owner::with).
|
||||
#[cfg_attr(feature = "tracing", instrument(level = "trace", skip_all))]
|
||||
#[inline(always)]
|
||||
pub fn request_animation_frame(cb: impl FnOnce() + 'static) {
|
||||
_ = request_animation_frame_with_handle(cb);
|
||||
}
|
||||
|
||||
// Closure::once_into_js only frees the callback when it's actually
|
||||
// called, so this instead uses into_js_value, which can be freed by
|
||||
// the host JS engine's GC if it supports weak references (which all
|
||||
@@ -157,7 +169,7 @@ fn closure_once(cb: impl FnOnce() + 'static) -> JsValue {
|
||||
/// The callback is called outside of the reactive ownership tree. This means that it does not have access to context via [`use_context`](reactive_graph::owner::use_context). If you want to use context inside the callback, you should either call `use_context` in the body of the component, and move the value into the callback, or access the current owner inside the component body using [`Owner::current`](reactive_graph::owner::Owner::current) and reestablish it in the callback with [`Owner::with`](reactive_graph::owner::Owner::with).
|
||||
#[cfg_attr(feature = "tracing", instrument(level = "trace", skip_all))]
|
||||
#[inline(always)]
|
||||
pub fn request_animation_frame(
|
||||
pub fn request_animation_frame_with_handle(
|
||||
cb: impl FnOnce() + 'static,
|
||||
) -> Result<AnimationFrameRequestHandle, JsValue> {
|
||||
#[cfg(feature = "tracing")]
|
||||
@@ -178,7 +190,7 @@ pub fn request_animation_frame(
|
||||
raf(closure_once(cb))
|
||||
}
|
||||
|
||||
/// Handle that is generated by [request_idle_callback] and can be
|
||||
/// Handle that is generated by [request_idle_callback_with_handle] and can be
|
||||
/// used to cancel the idle callback.
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct IdleCallbackHandle(u32);
|
||||
@@ -191,6 +203,18 @@ impl IdleCallbackHandle {
|
||||
}
|
||||
}
|
||||
|
||||
/// Queues the given function during an idle period using
|
||||
/// [`Window.requestIdleCallback`](https://developer.mozilla.org/en-US/docs/Web/API/window/requestIdleCallback).
|
||||
///
|
||||
/// ### Note about Context
|
||||
///
|
||||
/// The callback is called outside of the reactive ownership tree. This means that it does not have access to context via [`use_context`](reactive_graph::owner::use_context). If you want to use context inside the callback, you should either call `use_context` in the body of the component, and move the value into the callback, or access the current owner inside the component body using [`Owner::current`](reactive_graph::owner::Owner::current) and reestablish it in the callback with [`Owner::with`](reactive_graph::owner::Owner::with).
|
||||
#[cfg_attr(feature = "tracing", instrument(level = "trace", skip_all))]
|
||||
#[inline(always)]
|
||||
pub fn request_idle_callback(cb: impl Fn() + 'static) {
|
||||
_ = request_idle_callback_with_handle(cb);
|
||||
}
|
||||
|
||||
/// Queues the given function during an idle period using
|
||||
/// [`Window.requestIdleCallback`](https://developer.mozilla.org/en-US/docs/Web/API/window/requestIdleCallback),
|
||||
/// returning a cancelable handle.
|
||||
@@ -200,7 +224,7 @@ impl IdleCallbackHandle {
|
||||
/// The callback is called outside of the reactive ownership tree. This means that it does not have access to context via [`use_context`](reactive_graph::owner::use_context). If you want to use context inside the callback, you should either call `use_context` in the body of the component, and move the value into the callback, or access the current owner inside the component body using [`Owner::current`](reactive_graph::owner::Owner::current) and reestablish it in the callback with [`Owner::with`](reactive_graph::owner::Owner::with).
|
||||
#[cfg_attr(feature = "tracing", instrument(level = "trace", skip_all))]
|
||||
#[inline(always)]
|
||||
pub fn request_idle_callback(
|
||||
pub fn request_idle_callback_with_handle(
|
||||
cb: impl Fn() + 'static,
|
||||
) -> Result<IdleCallbackHandle, JsValue> {
|
||||
#[cfg(feature = "tracing")]
|
||||
@@ -237,7 +261,7 @@ pub fn queue_microtask(task: impl FnOnce() + 'static) {
|
||||
tachys::renderer::dom::queue_microtask(task);
|
||||
}
|
||||
|
||||
/// Handle that is generated by [set_timeout] and can be used to clear the timeout.
|
||||
/// Handle that is generated by [set_timeout_with_handle] and can be used to clear the timeout.
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct TimeoutHandle(i32);
|
||||
|
||||
@@ -249,6 +273,20 @@ 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).
|
||||
///
|
||||
/// ### Note about Context
|
||||
///
|
||||
/// The callback is called outside of the reactive ownership tree. This means that it does not have access to context via [`use_context`](reactive_graph::owner::use_context). If you want to use context inside the callback, you should either call `use_context` in the body of the component, and move the value into the callback, or access the current owner inside the component body using [`Owner::current`](reactive_graph::owner::Owner::current) and reestablish it in the callback with [`Owner::with`](reactive_graph::owner::Owner::with).
|
||||
#[cfg_attr(
|
||||
feature = "tracing",
|
||||
instrument(level = "trace", skip_all, fields(duration = ?duration))
|
||||
)]
|
||||
pub fn set_timeout(cb: impl FnOnce() + 'static, duration: Duration) {
|
||||
_ = set_timeout_with_handle(cb, 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).
|
||||
///
|
||||
@@ -260,7 +298,7 @@ impl TimeoutHandle {
|
||||
instrument(level = "trace", skip_all, fields(duration = ?duration))
|
||||
)]
|
||||
#[inline(always)]
|
||||
pub fn set_timeout(
|
||||
pub fn set_timeout_with_handle(
|
||||
cb: impl FnOnce() + 'static,
|
||||
duration: Duration,
|
||||
) -> Result<TimeoutHandle, JsValue> {
|
||||
@@ -353,7 +391,7 @@ pub fn debounce<T: 'static>(
|
||||
if let Some(timer) = timer.write().unwrap().take() {
|
||||
timer.clear();
|
||||
}
|
||||
let handle = set_timeout(
|
||||
let handle = set_timeout_with_handle(
|
||||
{
|
||||
let cb = Arc::clone(&cb);
|
||||
move || {
|
||||
@@ -380,6 +418,20 @@ impl IntervalHandle {
|
||||
}
|
||||
}
|
||||
|
||||
/// Repeatedly calls the given function, with a delay of the given duration between calls.
|
||||
/// See [`setInterval()`](https://developer.mozilla.org/en-US/docs/Web/API/setInterval).
|
||||
///
|
||||
/// ### Note about Context
|
||||
///
|
||||
/// The callback is called outside of the reactive ownership tree. This means that it does not have access to context via [`use_context`](reactive_graph::owner::use_context). If you want to use context inside the callback, you should either call `use_context` in the body of the component, and move the value into the callback, or access the current owner inside the component body using [`Owner::current`](reactive_graph::owner::Owner::current) and reestablish it in the callback with [`Owner::with`](reactive_graph::owner::Owner::with).
|
||||
#[cfg_attr(
|
||||
feature = "tracing",
|
||||
instrument(level = "trace", skip_all, fields(duration = ?duration))
|
||||
)]
|
||||
pub fn set_interval(cb: impl Fn() + 'static, duration: Duration) {
|
||||
_ = set_interval_with_handle(cb, duration);
|
||||
}
|
||||
|
||||
/// 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).
|
||||
@@ -392,7 +444,7 @@ impl IntervalHandle {
|
||||
instrument(level = "trace", skip_all, fields(duration = ?duration))
|
||||
)]
|
||||
#[inline(always)]
|
||||
pub fn set_interval(
|
||||
pub fn set_interval_with_handle(
|
||||
cb: impl Fn() + 'static,
|
||||
duration: Duration,
|
||||
) -> Result<IntervalHandle, JsValue> {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "leptos_macro"
|
||||
version = "0.8.14"
|
||||
version = "0.8.11"
|
||||
authors = ["Greg Johnston"]
|
||||
license = "MIT"
|
||||
repository = "https://github.com/leptos-rs/leptos"
|
||||
|
||||
@@ -1016,27 +1016,25 @@ struct PropOpt {
|
||||
name: Option<String>,
|
||||
}
|
||||
|
||||
struct TypedBuilderOpts<'a> {
|
||||
struct TypedBuilderOpts {
|
||||
default: bool,
|
||||
default_with_value: Option<syn::Expr>,
|
||||
strip_option: bool,
|
||||
into: bool,
|
||||
ty: &'a Type,
|
||||
}
|
||||
|
||||
impl<'a> TypedBuilderOpts<'a> {
|
||||
fn from_opts(opts: &PropOpt, ty: &'a Type) -> Self {
|
||||
impl TypedBuilderOpts {
|
||||
fn from_opts(opts: &PropOpt, is_ty_option: bool) -> Self {
|
||||
Self {
|
||||
default: opts.optional || opts.optional_no_strip || opts.attrs,
|
||||
default_with_value: opts.default.clone(),
|
||||
strip_option: opts.strip_option || opts.optional && is_option(ty),
|
||||
strip_option: opts.strip_option || opts.optional && is_ty_option,
|
||||
into: opts.into,
|
||||
ty,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TypedBuilderOpts<'_> {
|
||||
impl TypedBuilderOpts {
|
||||
fn to_serde_tokens(&self) -> TokenStream {
|
||||
let default = if let Some(v) = &self.default_with_value {
|
||||
let v = v.to_token_stream().to_string();
|
||||
@@ -1055,7 +1053,7 @@ impl TypedBuilderOpts<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
impl ToTokens for TypedBuilderOpts<'_> {
|
||||
impl ToTokens for TypedBuilderOpts {
|
||||
fn to_tokens(&self, tokens: &mut TokenStream) {
|
||||
let default = if let Some(v) = &self.default_with_value {
|
||||
let v = v.to_token_stream().to_string();
|
||||
@@ -1066,29 +1064,14 @@ impl ToTokens for TypedBuilderOpts<'_> {
|
||||
quote! {}
|
||||
};
|
||||
|
||||
// If self.strip_option && self.into, then the strip_option will be represented as part of the transform closure.
|
||||
let strip_option = if self.strip_option && !self.into {
|
||||
let strip_option = if self.strip_option {
|
||||
quote! { strip_option, }
|
||||
} else {
|
||||
quote! {}
|
||||
};
|
||||
|
||||
let into = if self.into {
|
||||
if !self.strip_option {
|
||||
let ty = &self.ty;
|
||||
quote! {
|
||||
fn transform<__IntoReactiveValueMarker>(value: impl ::leptos::prelude::IntoReactiveValue<#ty, __IntoReactiveValueMarker>) -> #ty {
|
||||
value.into_reactive_value()
|
||||
},
|
||||
}
|
||||
} else {
|
||||
let ty = unwrap_option(self.ty);
|
||||
quote! {
|
||||
fn transform<__IntoReactiveValueMarker>(value: impl ::leptos::prelude::IntoReactiveValue<#ty, __IntoReactiveValueMarker>) -> Option<#ty> {
|
||||
Some(value.into_reactive_value())
|
||||
},
|
||||
}
|
||||
}
|
||||
quote! { into, }
|
||||
} else {
|
||||
quote! {}
|
||||
};
|
||||
@@ -1124,7 +1107,8 @@ fn prop_builder_fields(
|
||||
ty,
|
||||
} = prop;
|
||||
|
||||
let builder_attrs = TypedBuilderOpts::from_opts(prop_opts, ty);
|
||||
let builder_attrs =
|
||||
TypedBuilderOpts::from_opts(prop_opts, is_option(ty));
|
||||
|
||||
let builder_docs = prop_to_doc(prop, PropDocStyle::Inline);
|
||||
|
||||
@@ -1169,7 +1153,8 @@ fn prop_serializer_fields(vis: &Visibility, props: &[Prop]) -> TokenStream {
|
||||
ty,
|
||||
} = prop;
|
||||
|
||||
let builder_attrs = TypedBuilderOpts::from_opts(prop_opts, ty);
|
||||
let builder_attrs =
|
||||
TypedBuilderOpts::from_opts(prop_opts, is_option(ty));
|
||||
let serde_attrs = builder_attrs.to_serde_tokens();
|
||||
|
||||
let PatIdent { ident, by_ref, .. } = &name;
|
||||
|
||||
@@ -199,7 +199,7 @@ mod slot;
|
||||
/// ```
|
||||
///
|
||||
/// 9. You can use the `node_ref` or `_ref` attribute to store a reference to its DOM element in a
|
||||
/// [NodeRef](https://docs.rs/leptos/latest/leptos/prelude/struct.NodeRef.html) to use later.
|
||||
/// [NodeRef](https://docs.rs/leptos/latest/leptos/struct.NodeRef.html) to use later.
|
||||
/// ```rust
|
||||
/// # use leptos::prelude::*;
|
||||
///
|
||||
@@ -505,9 +505,9 @@ pub fn include_view(tokens: TokenStream) -> TokenStream {
|
||||
///
|
||||
/// * `#[prop(into)]`: This will call `.into()` on any value passed into the component prop. (For example,
|
||||
/// you could apply `#[prop(into)]` to a prop that takes
|
||||
/// [Signal](https://docs.rs/leptos/latest/leptos/prelude/struct.Signal.html), which would
|
||||
/// allow users to pass a [ReadSignal](https://docs.rs/leptos/latest/leptos/prelude/struct.ReadSignal.html) or
|
||||
/// [RwSignal](https://docs.rs/leptos/latest/leptos/prelude/struct.RwSignal.html)
|
||||
/// [Signal](https://docs.rs/leptos/latest/leptos/struct.Signal.html), which would
|
||||
/// allow users to pass a [ReadSignal](https://docs.rs/leptos/latest/leptos/struct.ReadSignal.html) or
|
||||
/// [RwSignal](https://docs.rs/leptos/latest/leptos/struct.RwSignal.html)
|
||||
/// and automatically convert it.)
|
||||
/// * `#[prop(optional)]`: If the user does not specify this property when they use the component,
|
||||
/// it will be set to its default value. If the property type is `Option<T>`, values should be passed
|
||||
|
||||
@@ -25,7 +25,7 @@ pub fn params_impl(ast: &syn::DeriveInput) -> proc_macro::TokenStream {
|
||||
let span = field.span();
|
||||
|
||||
quote_spanned! {
|
||||
span=> #ident: ::leptos_router::params::macro_helpers::Wrapper::<#ty>::__into_param(
|
||||
span=> #ident: <#ty as ::leptos_router::params::IntoParam>::into_param(
|
||||
map.get_str(#field_name_string),
|
||||
#field_name_string
|
||||
)?
|
||||
@@ -39,8 +39,6 @@ pub fn params_impl(ast: &syn::DeriveInput) -> proc_macro::TokenStream {
|
||||
let gen = quote! {
|
||||
impl Params for #name {
|
||||
fn from_map(map: &::leptos_router::params::ParamsMap) -> ::core::result::Result<Self, ::leptos_router::params::ParamsError> {
|
||||
use ::leptos_router::params::macro_helpers::Fallback as _;
|
||||
|
||||
Ok(Self {
|
||||
#(#fields,)*
|
||||
})
|
||||
|
||||
@@ -159,27 +159,25 @@ struct PropOpt {
|
||||
pub attrs: bool,
|
||||
}
|
||||
|
||||
struct TypedBuilderOpts<'a> {
|
||||
struct TypedBuilderOpts {
|
||||
default: bool,
|
||||
default_with_value: Option<syn::Expr>,
|
||||
strip_option: bool,
|
||||
into: bool,
|
||||
ty: &'a Type,
|
||||
}
|
||||
|
||||
impl<'a> TypedBuilderOpts<'a> {
|
||||
pub fn from_opts(opts: &PropOpt, ty: &'a Type) -> Self {
|
||||
impl TypedBuilderOpts {
|
||||
pub fn from_opts(opts: &PropOpt, is_ty_option: bool) -> Self {
|
||||
Self {
|
||||
default: opts.optional || opts.optional_no_strip || opts.attrs,
|
||||
default_with_value: opts.default.clone(),
|
||||
strip_option: opts.strip_option || opts.optional && is_option(ty),
|
||||
strip_option: opts.strip_option || opts.optional && is_ty_option,
|
||||
into: opts.into,
|
||||
ty,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ToTokens for TypedBuilderOpts<'_> {
|
||||
impl ToTokens for TypedBuilderOpts {
|
||||
fn to_tokens(&self, tokens: &mut TokenStream) {
|
||||
let default = if let Some(v) = &self.default_with_value {
|
||||
let v = v.to_token_stream().to_string();
|
||||
@@ -190,29 +188,14 @@ impl ToTokens for TypedBuilderOpts<'_> {
|
||||
quote! {}
|
||||
};
|
||||
|
||||
// If self.strip_option && self.into, then the strip_option will be represented as part of the transform closure.
|
||||
let strip_option = if self.strip_option && !self.into {
|
||||
let strip_option = if self.strip_option {
|
||||
quote! { strip_option, }
|
||||
} else {
|
||||
quote! {}
|
||||
};
|
||||
|
||||
let into = if self.into {
|
||||
if !self.strip_option {
|
||||
let ty = &self.ty;
|
||||
quote! {
|
||||
fn transform<__IntoReactiveValueMarker>(value: impl ::leptos::prelude::IntoReactiveValue<#ty, __IntoReactiveValueMarker>) -> #ty {
|
||||
value.into_reactive_value()
|
||||
},
|
||||
}
|
||||
} else {
|
||||
let ty = unwrap_option(self.ty);
|
||||
quote! {
|
||||
fn transform<__IntoReactiveValueMarker>(value: impl ::leptos::prelude::IntoReactiveValue<#ty, __IntoReactiveValueMarker>) -> Option<#ty> {
|
||||
Some(value.into_reactive_value())
|
||||
},
|
||||
}
|
||||
}
|
||||
quote! { into, }
|
||||
} else {
|
||||
quote! {}
|
||||
};
|
||||
@@ -244,7 +227,8 @@ fn prop_builder_fields(vis: &Visibility, props: &[Prop]) -> TokenStream {
|
||||
ty,
|
||||
} = prop;
|
||||
|
||||
let builder_attrs = TypedBuilderOpts::from_opts(prop_opts, ty);
|
||||
let builder_attrs =
|
||||
TypedBuilderOpts::from_opts(prop_opts, is_option(ty));
|
||||
|
||||
let builder_docs = prop_to_doc(prop, PropDocStyle::Inline);
|
||||
|
||||
|
||||
@@ -90,7 +90,7 @@ pub(crate) fn component_to_tokens(
|
||||
|
||||
if optional {
|
||||
optional_props.push(quote! {
|
||||
props.#name = { #value }.map(::leptos::prelude::IntoReactiveValue::into_reactive_value);
|
||||
props.#name = { #value }.map(Into::into);
|
||||
})
|
||||
} else {
|
||||
required_props.push(quote! {
|
||||
@@ -176,9 +176,7 @@ pub(crate) fn component_to_tokens(
|
||||
let spreads = (!(spreads.is_empty())).then(|| {
|
||||
if cfg!(feature = "__internal_erase_components") {
|
||||
quote! {
|
||||
.add_any_attr({
|
||||
vec![#(::leptos::attr::any_attribute::IntoAnyAttribute::into_any_attr(#spreads),)*]
|
||||
})
|
||||
.add_any_attr(vec![#(#spreads.into_any_attr(),)*])
|
||||
}
|
||||
} else {
|
||||
quote! {
|
||||
|
||||
@@ -120,124 +120,6 @@ fn returns_static_lifetime() {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "nightly"))]
|
||||
#[component]
|
||||
pub fn IntoReactiveValueTestComponentSignal(
|
||||
#[prop(into)] arg1: Signal<String>,
|
||||
#[prop(into)] arg2: Signal<String>,
|
||||
#[prop(into)] arg3: Signal<String>,
|
||||
#[prop(into)] arg4: Signal<usize>,
|
||||
#[prop(into)] arg5: Signal<usize>,
|
||||
#[prop(into)] arg6: Signal<usize>,
|
||||
#[prop(into)] arg7: Signal<Option<usize>>,
|
||||
#[prop(into)] arg8: ArcSignal<String>,
|
||||
#[prop(into)] arg9: ArcSignal<String>,
|
||||
#[prop(into)] arg10: ArcSignal<String>,
|
||||
#[prop(into)] arg11: ArcSignal<usize>,
|
||||
#[prop(into)] arg12: ArcSignal<usize>,
|
||||
#[prop(into)] arg13: ArcSignal<usize>,
|
||||
#[prop(into)] arg14: ArcSignal<Option<usize>>,
|
||||
// Optionals:
|
||||
#[prop(into, optional)] arg15: Option<Signal<usize>>,
|
||||
#[prop(into, optional)] arg16_purposely_omitted: Option<Signal<usize>>,
|
||||
#[prop(into, optional)] arg17: Option<Signal<usize>>,
|
||||
#[prop(into, strip_option)] arg18: Option<Signal<usize>>,
|
||||
) -> impl IntoView {
|
||||
move || {
|
||||
view! {
|
||||
<div>
|
||||
<p>{arg1.get()}</p>
|
||||
<p>{arg2.get()}</p>
|
||||
<p>{arg3.get()}</p>
|
||||
<p>{arg4.get()}</p>
|
||||
<p>{arg5.get()}</p>
|
||||
<p>{arg6.get()}</p>
|
||||
<p>{arg7.get()}</p>
|
||||
<p>{arg8.get()}</p>
|
||||
<p>{arg9.get()}</p>
|
||||
<p>{arg10.get()}</p>
|
||||
<p>{arg11.get()}</p>
|
||||
<p>{arg12.get()}</p>
|
||||
<p>{arg13.get()}</p>
|
||||
<p>{arg14.get()}</p>
|
||||
<p>{arg15.get()}</p>
|
||||
<p>{arg16_purposely_omitted.get()}</p>
|
||||
<p>{arg17.get()}</p>
|
||||
<p>{arg18.get()}</p>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn IntoReactiveValueTestComponentCallback(
|
||||
#[prop(into)] arg1: Callback<(), String>,
|
||||
#[prop(into)] arg2: Callback<usize, String>,
|
||||
#[prop(into)] arg3: Callback<(usize,), String>,
|
||||
#[prop(into)] arg4: Callback<(usize, String), String>,
|
||||
#[prop(into)] arg5: UnsyncCallback<(), String>,
|
||||
#[prop(into)] arg6: UnsyncCallback<usize, String>,
|
||||
#[prop(into)] arg7: UnsyncCallback<(usize,), String>,
|
||||
#[prop(into)] arg8: UnsyncCallback<(usize, String), String>,
|
||||
) -> impl IntoView {
|
||||
move || {
|
||||
view! {
|
||||
<div>
|
||||
<p>{arg1.run(())}</p>
|
||||
<p>{arg2.run(1)}</p>
|
||||
<p>{arg3.run((2,))}</p>
|
||||
<p>{arg4.run((3, "three".into()))}</p>
|
||||
<p>{arg5.run(())}</p>
|
||||
<p>{arg6.run(1)}</p>
|
||||
<p>{arg7.run((2,))}</p>
|
||||
<p>{arg8.run((3, "three".into()))}</p>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "nightly"))]
|
||||
#[test]
|
||||
fn test_into_reactive_value_signal() {
|
||||
let _ = view! {
|
||||
<IntoReactiveValueTestComponentSignal
|
||||
arg1=move || "I was a reactive closure!"
|
||||
arg2="I was a basic str!"
|
||||
arg3=Signal::stored("I was already a signal!")
|
||||
arg4=move || 2
|
||||
arg5=3
|
||||
arg6=Signal::stored(4)
|
||||
arg7=|| 2
|
||||
arg8=move || "I was a reactive closure!"
|
||||
arg9="I was a basic str!"
|
||||
arg10=ArcSignal::stored("I was already a signal!".to_string())
|
||||
arg11=move || 2
|
||||
arg12=3
|
||||
arg13=ArcSignal::stored(4)
|
||||
arg14=|| 2
|
||||
arg15=|| 2
|
||||
nostrip:arg17=Some(|| 2)
|
||||
arg18=|| 2
|
||||
/>
|
||||
};
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_into_reactive_value_callback() {
|
||||
let _ = view! {
|
||||
<IntoReactiveValueTestComponentCallback
|
||||
arg1=|| "I was a callback static str!"
|
||||
arg2=|_n| "I was a callback static str!"
|
||||
arg3=|(_n,)| "I was a callback static str!"
|
||||
arg4=|(_n, _s)| "I was a callback static str!"
|
||||
arg5=|| "I was a callback static str!"
|
||||
arg6=|_n| "I was a callback static str!"
|
||||
arg7=|(_n,)| "I was a callback static str!"
|
||||
arg8=|(_n, _s)| "I was a callback static str!"
|
||||
/>
|
||||
};
|
||||
}
|
||||
|
||||
// an attempt to catch unhygienic macros regression
|
||||
mod macro_hygiene {
|
||||
// To ensure no relative module path to leptos inside macros.
|
||||
@@ -270,7 +152,12 @@ mod macro_hygiene {
|
||||
|
||||
#[component]
|
||||
fn Component() -> impl IntoView {
|
||||
view! { <div>{().into_any()} {()}</div> }
|
||||
view! {
|
||||
<div>
|
||||
{().into_any()}
|
||||
{()}
|
||||
</div>
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "leptos_server"
|
||||
version = "0.8.6"
|
||||
version = "0.8.5"
|
||||
authors = ["Greg Johnston"]
|
||||
license = "MIT"
|
||||
repository = "https://github.com/leptos-rs/leptos"
|
||||
|
||||
@@ -15,7 +15,7 @@ use codee::{
|
||||
Decoder, Encoder,
|
||||
};
|
||||
use core::{fmt::Debug, marker::PhantomData};
|
||||
use futures::{Future, FutureExt};
|
||||
use futures::Future;
|
||||
use or_poisoned::OrPoisoned;
|
||||
use reactive_graph::{
|
||||
computed::{
|
||||
@@ -258,17 +258,11 @@ where
|
||||
if let Some(suspense_context) = use_context::<SuspenseContext>() {
|
||||
if self.value.read().or_poisoned().is_none() {
|
||||
let handle = suspense_context.task_id();
|
||||
let mut ready =
|
||||
Box::pin(SpecialNonReactiveFuture::new(self.ready()));
|
||||
match ready.as_mut().now_or_never() {
|
||||
Some(_) => drop(handle),
|
||||
None => {
|
||||
reactive_graph::spawn(async move {
|
||||
ready.await;
|
||||
drop(handle);
|
||||
});
|
||||
}
|
||||
}
|
||||
let ready = SpecialNonReactiveFuture::new(self.ready());
|
||||
reactive_graph::spawn(async move {
|
||||
ready.await;
|
||||
drop(handle);
|
||||
});
|
||||
self.suspenses.write().or_poisoned().push(suspense_context);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -188,39 +188,6 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
thread_local! {
|
||||
static RESOURCE_SOURCE_SIGNAL_ACTIVE: AtomicBool = const { AtomicBool::new(false) };
|
||||
}
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
/// Returns whether the current thread is currently running a resource source signal.
|
||||
pub fn in_resource_source_signal() -> bool {
|
||||
RESOURCE_SOURCE_SIGNAL_ACTIVE
|
||||
.with(|scope| scope.load(std::sync::atomic::Ordering::Relaxed))
|
||||
}
|
||||
|
||||
/// Set a static to true whilst running the given function.
|
||||
/// [`is_in_effect_scope`] will return true whilst the function is running.
|
||||
fn run_in_resource_source_signal<T>(fun: impl FnOnce() -> T) -> T {
|
||||
#[cfg(debug_assertions)]
|
||||
{
|
||||
// For the theoretical nested case, set back to initial value rather than false:
|
||||
let initial = RESOURCE_SOURCE_SIGNAL_ACTIVE.with(|scope| {
|
||||
scope.swap(true, std::sync::atomic::Ordering::Relaxed)
|
||||
});
|
||||
let result = fun();
|
||||
RESOURCE_SOURCE_SIGNAL_ACTIVE.with(|scope| {
|
||||
scope.store(initial, std::sync::atomic::Ordering::Relaxed)
|
||||
});
|
||||
result
|
||||
}
|
||||
#[cfg(not(debug_assertions))]
|
||||
{
|
||||
fun()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, Ser> ReadUntracked for ArcResource<T, Ser>
|
||||
where
|
||||
T: 'static,
|
||||
@@ -235,9 +202,7 @@ where
|
||||
computed::suspense::SuspenseContext, effect::in_effect_scope,
|
||||
owner::use_context,
|
||||
};
|
||||
if !in_effect_scope()
|
||||
&& !in_resource_source_signal()
|
||||
&& use_context::<SuspenseContext>().is_none()
|
||||
if !in_effect_scope() && use_context::<SuspenseContext>().is_none()
|
||||
{
|
||||
let location = std::panic::Location::caller();
|
||||
reactive_graph::log_warning(format_args!(
|
||||
@@ -306,7 +271,7 @@ where
|
||||
let refetch = ArcRwSignal::new(0);
|
||||
let source = ArcMemo::new({
|
||||
let refetch = refetch.clone();
|
||||
move |_| (refetch.get(), run_in_resource_source_signal(&source))
|
||||
move |_| (refetch.get(), source())
|
||||
});
|
||||
let fun = {
|
||||
let source = source.clone();
|
||||
@@ -944,9 +909,7 @@ where
|
||||
computed::suspense::SuspenseContext, effect::in_effect_scope,
|
||||
owner::use_context,
|
||||
};
|
||||
if !in_effect_scope()
|
||||
&& !in_resource_source_signal()
|
||||
&& use_context::<SuspenseContext>().is_none()
|
||||
if !in_effect_scope() && use_context::<SuspenseContext>().is_none()
|
||||
{
|
||||
let location = std::panic::Location::caller();
|
||||
reactive_graph::log_warning(format_args!(
|
||||
|
||||
@@ -20,7 +20,7 @@ pub fn Demo1() -> impl IntoView {
|
||||
|
||||
// We need to add the 3D view onto the canvas post render.
|
||||
Effect::new(move |_| {
|
||||
_ = request_animation_frame(move || {
|
||||
request_animation_frame(move || {
|
||||
scene_sig.get_untracked().setup();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -95,7 +95,7 @@ pub fn App() -> impl IntoView {
|
||||
// if expires_in isn't 0, then set a timeout that rerfresh a minute short of the refresh.
|
||||
let expires_in = rw_expires_in.get();
|
||||
if expires_in != 0 && email.get_untracked().is_some() {
|
||||
let handle = set_timeout(
|
||||
let handle = set_timeout_with_handle(
|
||||
move || {
|
||||
refresh_token.dispatch(RefreshToken {
|
||||
email: email.get_untracked().unwrap(),
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "reactive_graph"
|
||||
version = "0.2.12"
|
||||
version = "0.2.9"
|
||||
authors = ["Greg Johnston"]
|
||||
license = "MIT"
|
||||
readme = "../README.md"
|
||||
@@ -29,10 +29,9 @@ send_wrapper = { features = [
|
||||
], workspace = true, default-features = true }
|
||||
subsecond = { workspace = true, default-features = true, optional = true }
|
||||
indexmap = { workspace = true, default-features = true }
|
||||
paste = { workspace = true, default-features = true }
|
||||
|
||||
[target.'cfg(all(target_arch = "wasm32", target_os = "unknown"))'.dependencies]
|
||||
web-sys = { version = "0.3.83", features = ["console"] }
|
||||
web-sys = { version = "0.3.77", features = ["console"] }
|
||||
|
||||
[dev-dependencies]
|
||||
tokio = { features = [
|
||||
@@ -41,7 +40,6 @@ tokio = { features = [
|
||||
], workspace = true, default-features = true }
|
||||
tokio-test = { workspace = true, default-features = true }
|
||||
any_spawner = { workspace = true, features = ["futures-executor", "tokio"] }
|
||||
typed-builder.workspace = true
|
||||
|
||||
[build-dependencies]
|
||||
rustc_version = { workspace = true, default-features = true }
|
||||
|
||||
@@ -632,29 +632,12 @@ impl<T: 'static> ReadUntracked for ArcAsyncDerived<T> {
|
||||
|
||||
fn try_read_untracked(&self) -> Option<Self::Value> {
|
||||
if let Some(suspense_context) = use_context::<SuspenseContext>() {
|
||||
// create a handle to register it with suspense
|
||||
let handle = suspense_context.task_id();
|
||||
|
||||
// check if the task is *already* ready
|
||||
let mut ready =
|
||||
Box::pin(SpecialNonReactiveFuture::new(self.ready()));
|
||||
match ready.as_mut().now_or_never() {
|
||||
Some(_) => {
|
||||
// if it's already ready, drop the handle immediately
|
||||
// this will immediately notify the suspense context that it's complete
|
||||
drop(handle);
|
||||
}
|
||||
None => {
|
||||
// otherwise, spawn a task to wait for it to be ready, then drop the handle,
|
||||
// which will notify the suspense
|
||||
crate::spawn(async move {
|
||||
ready.await;
|
||||
drop(handle);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// register the suspense context with our list of them, to be notified later if this re-runs
|
||||
let ready = SpecialNonReactiveFuture::new(self.ready());
|
||||
crate::spawn(async move {
|
||||
ready.await;
|
||||
drop(handle);
|
||||
});
|
||||
self.inner
|
||||
.write()
|
||||
.or_poisoned()
|
||||
|
||||
@@ -23,11 +23,10 @@ pin_project! {
|
||||
#[derive(Clone)]
|
||||
#[allow(missing_docs)]
|
||||
pub struct ScopedFuture<Fut> {
|
||||
owner: Owner,
|
||||
observer: Option<AnySubscriber>,
|
||||
diagnostics: bool,
|
||||
pub owner: Owner,
|
||||
pub observer: Option<AnySubscriber>,
|
||||
#[pin]
|
||||
fut: Fut,
|
||||
pub fut: Fut,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,7 +39,6 @@ impl<Fut> ScopedFuture<Fut> {
|
||||
Self {
|
||||
owner,
|
||||
observer,
|
||||
diagnostics: true,
|
||||
fut,
|
||||
}
|
||||
}
|
||||
@@ -53,19 +51,19 @@ impl<Fut> ScopedFuture<Fut> {
|
||||
Self {
|
||||
owner,
|
||||
observer: None,
|
||||
diagnostics: false,
|
||||
fut,
|
||||
}
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
#[track_caller]
|
||||
pub fn new_untracked_with_diagnostics(fut: Fut) -> Self {
|
||||
pub fn new_untracked_with_diagnostics(
|
||||
fut: Fut,
|
||||
) -> ScopedFutureUntrackedWithDiagnostics<Fut> {
|
||||
let owner = Owner::current().unwrap_or_default();
|
||||
Self {
|
||||
ScopedFutureUntrackedWithDiagnostics {
|
||||
owner,
|
||||
observer: None,
|
||||
diagnostics: true,
|
||||
fut,
|
||||
}
|
||||
}
|
||||
@@ -77,19 +75,41 @@ impl<Fut: Future> Future for ScopedFuture<Fut> {
|
||||
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
||||
let this = self.project();
|
||||
this.owner.with(|| {
|
||||
this.observer.with_observer(|| {
|
||||
#[cfg(debug_assertions)]
|
||||
let _maybe_guard = if *this.diagnostics {
|
||||
None
|
||||
} else {
|
||||
Some(crate::diagnostics::SpecialNonReactiveZone::enter())
|
||||
};
|
||||
this.fut.poll(cx)
|
||||
})
|
||||
#[cfg(debug_assertions)]
|
||||
let _maybe_guard = if this.observer.is_none() {
|
||||
Some(crate::diagnostics::SpecialNonReactiveZone::enter())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
this.observer.with_observer(|| this.fut.poll(cx))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pin_project! {
|
||||
/// A [`Future`] wrapper that sets the [`Owner`] and [`Observer`] before polling the inner
|
||||
/// `Future`, output of [`ScopedFuture::new_untracked_with_diagnostics`].
|
||||
///
|
||||
/// In leptos 0.9 this will be replaced with `ScopedFuture` itself.
|
||||
#[derive(Clone)]
|
||||
pub struct ScopedFutureUntrackedWithDiagnostics<Fut> {
|
||||
owner: Owner,
|
||||
observer: Option<AnySubscriber>,
|
||||
#[pin]
|
||||
fut: Fut,
|
||||
}
|
||||
}
|
||||
|
||||
impl<Fut: Future> Future for ScopedFutureUntrackedWithDiagnostics<Fut> {
|
||||
type Output = Fut::Output;
|
||||
|
||||
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
||||
let this = self.project();
|
||||
this.owner
|
||||
.with(|| this.observer.with_observer(|| this.fut.poll(cx)))
|
||||
}
|
||||
}
|
||||
|
||||
/// Utilities used to track whether asynchronous computeds are currently loading.
|
||||
pub mod suspense {
|
||||
use crate::{
|
||||
|
||||
@@ -110,12 +110,10 @@ fn effect_base() -> (Receiver, Owner, Arc<RwLock<EffectInner>>) {
|
||||
(rx, owner, inner)
|
||||
}
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
thread_local! {
|
||||
static EFFECT_SCOPE_ACTIVE: AtomicBool = const { AtomicBool::new(false) };
|
||||
}
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
/// Returns whether the current thread is currently running an effect.
|
||||
pub fn in_effect_scope() -> bool {
|
||||
EFFECT_SCOPE_ACTIVE
|
||||
@@ -125,22 +123,14 @@ pub fn in_effect_scope() -> bool {
|
||||
/// Set a static to true whilst running the given function.
|
||||
/// [`is_in_effect_scope`] will return true whilst the function is running.
|
||||
fn run_in_effect_scope<T>(fun: impl FnOnce() -> T) -> T {
|
||||
#[cfg(debug_assertions)]
|
||||
{
|
||||
// For the theoretical nested case, set back to initial value rather than false:
|
||||
let initial = EFFECT_SCOPE_ACTIVE.with(|scope| {
|
||||
scope.swap(true, std::sync::atomic::Ordering::Relaxed)
|
||||
});
|
||||
let result = fun();
|
||||
EFFECT_SCOPE_ACTIVE.with(|scope| {
|
||||
scope.store(initial, std::sync::atomic::Ordering::Relaxed)
|
||||
});
|
||||
result
|
||||
}
|
||||
#[cfg(not(debug_assertions))]
|
||||
{
|
||||
fun()
|
||||
}
|
||||
// For the theoretical nested case, set back to initial value rather than false:
|
||||
let initial = EFFECT_SCOPE_ACTIVE
|
||||
.with(|scope| scope.swap(true, std::sync::atomic::Ordering::Relaxed));
|
||||
let result = fun();
|
||||
EFFECT_SCOPE_ACTIVE.with(|scope| {
|
||||
scope.store(initial, std::sync::atomic::Ordering::Relaxed)
|
||||
});
|
||||
result
|
||||
}
|
||||
|
||||
impl<S> Effect<S>
|
||||
|
||||
@@ -1,80 +0,0 @@
|
||||
#[doc(hidden)]
|
||||
pub struct __IntoReactiveValueMarkerBaseCase;
|
||||
|
||||
/// A helper trait that works like `Into<T>` but uses a marker generic
|
||||
/// to allow more `From` implementations than would be allowed with just `Into<T>`.
|
||||
pub trait IntoReactiveValue<T, M> {
|
||||
/// Converts `self` into a `T`.
|
||||
fn into_reactive_value(self) -> T;
|
||||
}
|
||||
|
||||
// The base case, which allows anything which implements .into() to work:
|
||||
impl<T, I> IntoReactiveValue<T, __IntoReactiveValueMarkerBaseCase> for I
|
||||
where
|
||||
I: Into<T>,
|
||||
{
|
||||
fn into_reactive_value(self) -> T {
|
||||
self.into()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
|
||||
use crate::{
|
||||
into_reactive_value::IntoReactiveValue,
|
||||
owner::{LocalStorage, Owner},
|
||||
traits::GetUntracked,
|
||||
wrappers::read::Signal,
|
||||
};
|
||||
use typed_builder::TypedBuilder;
|
||||
|
||||
#[test]
|
||||
fn test_into_signal_compiles() {
|
||||
let owner = Owner::new();
|
||||
owner.set();
|
||||
|
||||
let _: Signal<usize> = (|| 2).into_reactive_value();
|
||||
let _: Signal<usize, LocalStorage> = 2.into_reactive_value();
|
||||
let _: Signal<usize, LocalStorage> = (|| 2).into_reactive_value();
|
||||
let _: Signal<String> = "str".into_reactive_value();
|
||||
let _: Signal<String, LocalStorage> = "str".into_reactive_value();
|
||||
|
||||
// Confirm doesn't affect nightly function syntax:
|
||||
#[cfg(all(rustc_nightly, feature = "nightly"))]
|
||||
{
|
||||
let sig: Signal<usize> = Signal::stored(2).into_reactive_value();
|
||||
assert_eq!(sig(), 2);
|
||||
}
|
||||
|
||||
// Confirm can be used in more complex expressions:
|
||||
{
|
||||
use crate::traits::Get;
|
||||
let a: Signal<usize> = (|| 2).into_reactive_value();
|
||||
let b: Signal<usize> = Signal::stored(2).into_reactive_value();
|
||||
let _: Signal<usize> =
|
||||
(move || a.get() + b.get()).into_reactive_value();
|
||||
}
|
||||
|
||||
#[derive(TypedBuilder)]
|
||||
struct Foo {
|
||||
#[builder(setter(
|
||||
fn transform<M>(value: impl IntoReactiveValue<Signal<usize>, M>) {
|
||||
value.into_reactive_value()
|
||||
}
|
||||
))]
|
||||
sig: Signal<usize>,
|
||||
}
|
||||
|
||||
assert_eq!(Foo::builder().sig(2).build().sig.get_untracked(), 2);
|
||||
assert_eq!(Foo::builder().sig(|| 2).build().sig.get_untracked(), 2);
|
||||
assert_eq!(
|
||||
Foo::builder()
|
||||
.sig(Signal::stored(2))
|
||||
.build()
|
||||
.sig
|
||||
.get_untracked(),
|
||||
2
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -90,12 +90,6 @@ pub mod traits;
|
||||
pub mod transition;
|
||||
pub mod wrappers;
|
||||
|
||||
mod into_reactive_value;
|
||||
pub use into_reactive_value::*;
|
||||
|
||||
/// A standard way to wrap functions and closures to pass them to components.
|
||||
pub mod callback;
|
||||
|
||||
use computed::ScopedFuture;
|
||||
|
||||
#[cfg(all(feature = "nightly", rustc_nightly))]
|
||||
@@ -103,9 +97,7 @@ mod nightly;
|
||||
|
||||
/// Reexports frequently-used traits.
|
||||
pub mod prelude {
|
||||
pub use crate::{
|
||||
into_reactive_value::IntoReactiveValue, owner::FromLocal, traits::*,
|
||||
};
|
||||
pub use crate::{owner::FromLocal, traits::*};
|
||||
}
|
||||
|
||||
// TODO remove this, it's just useful while developing
|
||||
|
||||
@@ -145,90 +145,16 @@ macro_rules! impl_get_fn_traits_get_arena {
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! impl_get_fn_traits_get_arena_with_readable_deref_impl {
|
||||
($($ty:ident),*) => {
|
||||
$(
|
||||
/// Allow calling $ty() syntax
|
||||
impl<T: Clone + 'static, S: Storage<T> + 'static> std::ops::Deref
|
||||
for $ty<T, S>
|
||||
where
|
||||
$ty<T, S>: crate::traits::Get<Value = T>,
|
||||
$ty<T, S>: Get, S: Storage<T> + Storage<Option<T>> + Storage<SignalTypes<Option<T>, S>>
|
||||
{
|
||||
type Target = dyn Fn() -> T;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
unsafe { readable_deref_impl::ReadableDerefImpl::deref_impl(self) }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Clone + 'static, S: Storage<T> + 'static> readable_deref_impl::ReadableDerefImpl for $ty<T, S>
|
||||
where
|
||||
$ty<T, S>: crate::traits::Get<Value = T>,
|
||||
$ty<T, S>: Get, S: Storage<T> + Storage<Option<T>> + Storage<SignalTypes<Option<T>, S>>
|
||||
{
|
||||
}
|
||||
|
||||
)*
|
||||
};
|
||||
}
|
||||
|
||||
impl_get_fn_traits_get![ArcReadSignal, ArcRwSignal];
|
||||
impl_get_fn_traits_get_arena![
|
||||
ReadSignal,
|
||||
RwSignal,
|
||||
ArcMemo,
|
||||
ArcSignal,
|
||||
Signal,
|
||||
MaybeSignal,
|
||||
Memo,
|
||||
MaybeProp
|
||||
];
|
||||
impl_get_fn_traits_get_arena_with_readable_deref_impl![ArcSignal, Signal];
|
||||
impl_set_fn_traits![ArcRwSignal, ArcWriteSignal];
|
||||
impl_set_fn_traits_arena![RwSignal, WriteSignal, SignalSetter];
|
||||
|
||||
mod readable_deref_impl {
|
||||
/// Derived from the implementation and original creaters at dioxus
|
||||
/// https://docs.rs/dioxus-signals/0.6.3/src/dioxus_signals/signal.rs.html#485-494
|
||||
pub trait ReadableDerefImpl: crate::traits::Get {
|
||||
/// SAFETY: You must call this function directly with `self` as the argument.
|
||||
/// This function relies on the size of the object you return from the deref
|
||||
/// being the same as the object you pass in
|
||||
#[doc(hidden)]
|
||||
unsafe fn deref_impl<'a>(&self) -> &'a dyn Fn() -> Self::Value
|
||||
where
|
||||
Self: Sized + 'a,
|
||||
Self::Value: Clone + 'static,
|
||||
{
|
||||
// https://github.com/dtolnay/case-studies/tree/master/callable-types
|
||||
|
||||
// First we create a closure that captures something with the Same in memory layout as Self (MaybeUninit<Self>).
|
||||
let uninit_callable = std::mem::MaybeUninit::<Self>::uninit();
|
||||
// Then move that value into the closure. We assume that the closure now has a in memory layout of Self.
|
||||
let uninit_closure =
|
||||
move || Self::get(unsafe { &*uninit_callable.as_ptr() });
|
||||
|
||||
// Check that the size of the closure is the same as the size of Self in case the compiler changed the layout of the closure.
|
||||
let size_of_closure = std::mem::size_of_val(&uninit_closure);
|
||||
assert_eq!(size_of_closure, std::mem::size_of::<Self>());
|
||||
|
||||
// Then cast the lifetime of the closure to the lifetime of &self.
|
||||
fn cast_lifetime<'a, T>(_a: &T, b: &'a T) -> &'a T {
|
||||
b
|
||||
}
|
||||
let reference_to_closure = cast_lifetime(
|
||||
{
|
||||
// The real closure that we will never use.
|
||||
&uninit_closure
|
||||
},
|
||||
#[allow(clippy::missing_transmute_annotations)]
|
||||
// We transmute self into a reference to the closure. This is safe because we know that the closure has the same memory layout as Self so &Closure == &Self.
|
||||
unsafe {
|
||||
std::mem::transmute(self)
|
||||
},
|
||||
);
|
||||
|
||||
// Cast the closure to a trait object.
|
||||
reference_to_closure as &_
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -324,22 +324,6 @@ pub mod read {
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> From<&'static str> for ArcSignal<String, S>
|
||||
where
|
||||
S: Storage<&'static str> + Storage<String>,
|
||||
{
|
||||
#[track_caller]
|
||||
fn from(value: &'static str) -> Self {
|
||||
Self {
|
||||
inner: SignalTypes::Stored(ArcStoredValue::new(
|
||||
value.to_string(),
|
||||
)),
|
||||
#[cfg(any(debug_assertions, leptos_debuginfo))]
|
||||
defined_at: std::panic::Location::caller(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S> DefinedAt for ArcSignal<T, S>
|
||||
where
|
||||
S: Storage<T>,
|
||||
@@ -1065,13 +1049,6 @@ pub mod read {
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Signal<&'static str, LocalStorage>> for Signal<String, LocalStorage> {
|
||||
#[track_caller]
|
||||
fn from(value: Signal<&'static str, LocalStorage>) -> Self {
|
||||
Signal::derive_local(move || value.read().to_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Signal<&'static str>> for Signal<String, LocalStorage> {
|
||||
#[track_caller]
|
||||
fn from(value: Signal<&'static str>) -> Self {
|
||||
@@ -1100,15 +1077,6 @@ pub mod read {
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Signal<Option<&'static str>, LocalStorage>>
|
||||
for Signal<Option<String>, LocalStorage>
|
||||
{
|
||||
#[track_caller]
|
||||
fn from(value: Signal<Option<&'static str>, LocalStorage>) -> Self {
|
||||
Signal::derive_local(move || value.read().map(str::to_string))
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Signal<Option<&'static str>>>
|
||||
for Signal<Option<String>, LocalStorage>
|
||||
{
|
||||
@@ -1118,177 +1086,6 @@ pub mod read {
|
||||
}
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub struct __IntoReactiveValueMarkerSignalFromReactiveClosure;
|
||||
#[doc(hidden)]
|
||||
pub struct __IntoReactiveValueMarkerSignalStrOutputToString;
|
||||
#[doc(hidden)]
|
||||
pub struct __IntoReactiveValueMarkerOptionalSignalFromReactiveClosureAlways;
|
||||
|
||||
impl<T, F>
|
||||
crate::IntoReactiveValue<
|
||||
Signal<T, SyncStorage>,
|
||||
__IntoReactiveValueMarkerSignalFromReactiveClosure,
|
||||
> for F
|
||||
where
|
||||
T: Send + Sync + 'static,
|
||||
F: Fn() -> T + Send + Sync + 'static,
|
||||
{
|
||||
fn into_reactive_value(self) -> Signal<T, SyncStorage> {
|
||||
Signal::derive(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, F>
|
||||
crate::IntoReactiveValue<
|
||||
ArcSignal<T, SyncStorage>,
|
||||
__IntoReactiveValueMarkerSignalFromReactiveClosure,
|
||||
> for F
|
||||
where
|
||||
T: Send + Sync + 'static,
|
||||
F: Fn() -> T + Send + Sync + 'static,
|
||||
{
|
||||
fn into_reactive_value(self) -> ArcSignal<T, SyncStorage> {
|
||||
ArcSignal::derive(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, F>
|
||||
crate::IntoReactiveValue<
|
||||
Signal<T, LocalStorage>,
|
||||
__IntoReactiveValueMarkerSignalFromReactiveClosure,
|
||||
> for F
|
||||
where
|
||||
T: 'static,
|
||||
F: Fn() -> T + 'static,
|
||||
{
|
||||
fn into_reactive_value(self) -> Signal<T, LocalStorage> {
|
||||
Signal::derive_local(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, F>
|
||||
crate::IntoReactiveValue<
|
||||
ArcSignal<T, LocalStorage>,
|
||||
__IntoReactiveValueMarkerSignalFromReactiveClosure,
|
||||
> for F
|
||||
where
|
||||
T: 'static,
|
||||
F: Fn() -> T + 'static,
|
||||
{
|
||||
fn into_reactive_value(self) -> ArcSignal<T, LocalStorage> {
|
||||
ArcSignal::derive_local(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl<F>
|
||||
crate::IntoReactiveValue<
|
||||
Signal<String, SyncStorage>,
|
||||
__IntoReactiveValueMarkerSignalStrOutputToString,
|
||||
> for F
|
||||
where
|
||||
F: Fn() -> &'static str + Send + Sync + 'static,
|
||||
{
|
||||
fn into_reactive_value(self) -> Signal<String, SyncStorage> {
|
||||
Signal::derive(move || self().to_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl<F>
|
||||
crate::IntoReactiveValue<
|
||||
ArcSignal<String, SyncStorage>,
|
||||
__IntoReactiveValueMarkerSignalStrOutputToString,
|
||||
> for F
|
||||
where
|
||||
F: Fn() -> &'static str + Send + Sync + 'static,
|
||||
{
|
||||
fn into_reactive_value(self) -> ArcSignal<String, SyncStorage> {
|
||||
ArcSignal::derive(move || self().to_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl<F>
|
||||
crate::IntoReactiveValue<
|
||||
Signal<String, LocalStorage>,
|
||||
__IntoReactiveValueMarkerSignalStrOutputToString,
|
||||
> for F
|
||||
where
|
||||
F: Fn() -> &'static str + 'static,
|
||||
{
|
||||
fn into_reactive_value(self) -> Signal<String, LocalStorage> {
|
||||
Signal::derive_local(move || self().to_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl<F>
|
||||
crate::IntoReactiveValue<
|
||||
ArcSignal<String, LocalStorage>,
|
||||
__IntoReactiveValueMarkerSignalStrOutputToString,
|
||||
> for F
|
||||
where
|
||||
F: Fn() -> &'static str + 'static,
|
||||
{
|
||||
fn into_reactive_value(self) -> ArcSignal<String, LocalStorage> {
|
||||
ArcSignal::derive_local(move || self().to_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, F>
|
||||
crate::IntoReactiveValue<
|
||||
Signal<Option<T>, SyncStorage>,
|
||||
__IntoReactiveValueMarkerOptionalSignalFromReactiveClosureAlways,
|
||||
> for F
|
||||
where
|
||||
T: Send + Sync + 'static,
|
||||
F: Fn() -> T + Send + Sync + 'static,
|
||||
{
|
||||
fn into_reactive_value(self) -> Signal<Option<T>, SyncStorage> {
|
||||
Signal::derive(move || Some(self()))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, F>
|
||||
crate::IntoReactiveValue<
|
||||
ArcSignal<Option<T>, SyncStorage>,
|
||||
__IntoReactiveValueMarkerOptionalSignalFromReactiveClosureAlways,
|
||||
> for F
|
||||
where
|
||||
T: Send + Sync + 'static,
|
||||
F: Fn() -> T + Send + Sync + 'static,
|
||||
{
|
||||
fn into_reactive_value(self) -> ArcSignal<Option<T>, SyncStorage> {
|
||||
ArcSignal::derive(move || Some(self()))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, F>
|
||||
crate::IntoReactiveValue<
|
||||
Signal<Option<T>, LocalStorage>,
|
||||
__IntoReactiveValueMarkerOptionalSignalFromReactiveClosureAlways,
|
||||
> for F
|
||||
where
|
||||
T: 'static,
|
||||
F: Fn() -> T + 'static,
|
||||
{
|
||||
fn into_reactive_value(self) -> Signal<Option<T>, LocalStorage> {
|
||||
Signal::derive_local(move || Some(self()))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, F>
|
||||
crate::IntoReactiveValue<
|
||||
ArcSignal<Option<T>, LocalStorage>,
|
||||
__IntoReactiveValueMarkerOptionalSignalFromReactiveClosureAlways,
|
||||
> for F
|
||||
where
|
||||
T: 'static,
|
||||
F: Fn() -> T + 'static,
|
||||
{
|
||||
fn into_reactive_value(self) -> ArcSignal<Option<T>, LocalStorage> {
|
||||
ArcSignal::derive_local(move || Some(self()))
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(deprecated)]
|
||||
impl<T> From<MaybeSignal<T>> for Signal<T>
|
||||
where
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "reactive_stores"
|
||||
version = "0.3.1"
|
||||
version = "0.3.0"
|
||||
authors = ["Greg Johnston"]
|
||||
license = "MIT"
|
||||
readme = "../README.md"
|
||||
|
||||
@@ -29,7 +29,6 @@ where
|
||||
#[cfg(any(debug_assertions, leptos_debuginfo))]
|
||||
defined_at: &'static Location<'static>,
|
||||
path: Arc<dyn Fn() -> StorePath + Send + Sync>,
|
||||
path_unkeyed: Arc<dyn Fn() -> StorePath + Send + Sync>,
|
||||
get_trigger: Arc<dyn Fn(StorePath) -> StoreFieldTrigger + Send + Sync>,
|
||||
get_trigger_unkeyed:
|
||||
Arc<dyn Fn(StorePath) -> StoreFieldTrigger + Send + Sync>,
|
||||
@@ -114,10 +113,6 @@ impl<T> StoreField for ArcField<T> {
|
||||
(self.path)()
|
||||
}
|
||||
|
||||
fn path_unkeyed(&self) -> impl IntoIterator<Item = StorePathSegment> {
|
||||
(self.path_unkeyed)()
|
||||
}
|
||||
|
||||
fn reader(&self) -> Option<Self::Reader> {
|
||||
(self.read)().map(StoreFieldReader::new)
|
||||
}
|
||||
@@ -142,9 +137,6 @@ where
|
||||
#[cfg(any(debug_assertions, leptos_debuginfo))]
|
||||
defined_at: Location::caller(),
|
||||
path: Arc::new(move || value.path().into_iter().collect()),
|
||||
path_unkeyed: Arc::new(move || {
|
||||
value.path_unkeyed().into_iter().collect()
|
||||
}),
|
||||
get_trigger: Arc::new(move |path| value.get_trigger(path)),
|
||||
get_trigger_unkeyed: Arc::new(move |path| {
|
||||
value.get_trigger_unkeyed(path)
|
||||
@@ -171,10 +163,6 @@ where
|
||||
let value = value.clone();
|
||||
move || value.path().into_iter().collect()
|
||||
}),
|
||||
path_unkeyed: Arc::new({
|
||||
let value = value.clone();
|
||||
move || value.path_unkeyed().into_iter().collect()
|
||||
}),
|
||||
get_trigger: Arc::new({
|
||||
let value = value.clone();
|
||||
move |path| value.get_trigger(path)
|
||||
@@ -223,10 +211,6 @@ where
|
||||
let value = value.clone();
|
||||
move || value.path().into_iter().collect()
|
||||
}),
|
||||
path_unkeyed: Arc::new({
|
||||
let value = value.clone();
|
||||
move || value.path_unkeyed().into_iter().collect()
|
||||
}),
|
||||
get_trigger: Arc::new({
|
||||
let value = value.clone();
|
||||
move |path| value.get_trigger(path)
|
||||
@@ -274,10 +258,6 @@ where
|
||||
let value = value.clone();
|
||||
move || value.path().into_iter().collect()
|
||||
}),
|
||||
path_unkeyed: Arc::new({
|
||||
let value = value.clone();
|
||||
move || value.path_unkeyed().into_iter().collect()
|
||||
}),
|
||||
get_trigger: Arc::new({
|
||||
let value = value.clone();
|
||||
move |path| value.get_trigger(path)
|
||||
@@ -326,10 +306,6 @@ where
|
||||
let value = value.clone();
|
||||
move || value.path().into_iter().collect()
|
||||
}),
|
||||
path_unkeyed: Arc::new({
|
||||
let value = value.clone();
|
||||
move || value.path_unkeyed().into_iter().collect()
|
||||
}),
|
||||
get_trigger: Arc::new({
|
||||
let value = value.clone();
|
||||
move |path| value.get_trigger(path)
|
||||
@@ -382,10 +358,6 @@ where
|
||||
let value = value.clone();
|
||||
move || value.path().into_iter().collect()
|
||||
}),
|
||||
path_unkeyed: Arc::new({
|
||||
let value = value.clone();
|
||||
move || value.path_unkeyed().into_iter().collect()
|
||||
}),
|
||||
get_trigger: Arc::new({
|
||||
let value = value.clone();
|
||||
move |path| value.get_trigger(path)
|
||||
@@ -424,7 +396,6 @@ impl<T> Clone for ArcField<T> {
|
||||
#[cfg(any(debug_assertions, leptos_debuginfo))]
|
||||
defined_at: self.defined_at,
|
||||
path: self.path.clone(),
|
||||
path_unkeyed: self.path_unkeyed.clone(),
|
||||
get_trigger: Arc::clone(&self.get_trigger),
|
||||
get_trigger_unkeyed: Arc::clone(&self.get_trigger_unkeyed),
|
||||
read: Arc::clone(&self.read),
|
||||
|
||||
@@ -76,11 +76,6 @@ where
|
||||
fn path(&self) -> impl IntoIterator<Item = StorePathSegment> {
|
||||
self.inner.path()
|
||||
}
|
||||
|
||||
fn path_unkeyed(&self) -> impl IntoIterator<Item = StorePathSegment> {
|
||||
self.inner.path_unkeyed()
|
||||
}
|
||||
|
||||
fn reader(&self) -> Option<Self::Reader> {
|
||||
let inner = self.inner.reader()?;
|
||||
Some(Mapped::new_with_guard(inner, |n| n.deref()))
|
||||
|
||||
@@ -73,13 +73,6 @@ where
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn path_unkeyed(&self) -> impl IntoIterator<Item = StorePathSegment> {
|
||||
self.inner
|
||||
.try_get_value()
|
||||
.map(|inner| inner.path_unkeyed().into_iter().collect::<Vec<_>>())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn reader(&self) -> Option<Self::Reader> {
|
||||
self.inner.try_get_value().and_then(|inner| inner.reader())
|
||||
}
|
||||
|
||||
@@ -80,13 +80,6 @@ where
|
||||
.chain(iter::once(self.index.into()))
|
||||
}
|
||||
|
||||
fn path_unkeyed(&self) -> impl IntoIterator<Item = StorePathSegment> {
|
||||
self.inner
|
||||
.path_unkeyed()
|
||||
.into_iter()
|
||||
.chain(iter::once(self.index.into()))
|
||||
}
|
||||
|
||||
fn get_trigger(&self, path: StorePath) -> StoreFieldTrigger {
|
||||
self.inner.get_trigger(path)
|
||||
}
|
||||
|
||||
@@ -106,13 +106,6 @@ where
|
||||
.chain(iter::once(self.path_segment))
|
||||
}
|
||||
|
||||
fn path_unkeyed(&self) -> impl IntoIterator<Item = StorePathSegment> {
|
||||
self.inner
|
||||
.path_unkeyed()
|
||||
.into_iter()
|
||||
.chain(iter::once(self.path_segment))
|
||||
}
|
||||
|
||||
fn get_trigger(&self, path: StorePath) -> StoreFieldTrigger {
|
||||
self.inner.get_trigger(path)
|
||||
}
|
||||
@@ -140,20 +133,13 @@ where
|
||||
}
|
||||
|
||||
fn track_field(&self) {
|
||||
let mut full_path = self.path().into_iter().collect::<StorePath>();
|
||||
let inner = self
|
||||
.inner
|
||||
.get_trigger(self.inner.path().into_iter().collect());
|
||||
inner.this.track();
|
||||
let trigger = self.get_trigger(self.path().into_iter().collect());
|
||||
trigger.this.track();
|
||||
trigger.children.track();
|
||||
|
||||
// tracks `this` for all ancestors: i.e., it will track any change that is made
|
||||
// directly to one of its ancestors, but not a change made to a *child* of an ancestor
|
||||
// (which would end up with every subfield tracking its own siblings, because they are
|
||||
// children of its parent)
|
||||
while !full_path.is_empty() {
|
||||
full_path.pop();
|
||||
let inner = self.get_trigger(full_path.clone());
|
||||
inner.this.track();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -183,7 +169,6 @@ where
|
||||
{
|
||||
inner: KeyedSubfield<Inner, Prev, K, T>,
|
||||
guard: Option<Guard>,
|
||||
untracked: bool,
|
||||
}
|
||||
|
||||
impl<Inner, Prev, K, T, Guard> Deref
|
||||
@@ -235,7 +220,6 @@ where
|
||||
K: Debug + Send + Sync + PartialEq + Eq + Hash + 'static,
|
||||
{
|
||||
fn untrack(&mut self) {
|
||||
self.untracked = true;
|
||||
if let Some(inner) = self.guard.as_mut() {
|
||||
inner.untrack();
|
||||
}
|
||||
@@ -260,10 +244,7 @@ where
|
||||
// now that the write lock is release, we can get a read lock to refresh this keyed field
|
||||
// based on the new value
|
||||
self.inner.update_keys();
|
||||
|
||||
if !self.untracked {
|
||||
self.inner.notify();
|
||||
}
|
||||
self.inner.notify();
|
||||
|
||||
// reactive updates happen on the next tick
|
||||
}
|
||||
@@ -356,7 +337,6 @@ where
|
||||
Some(KeyedSubfieldWriteGuard {
|
||||
inner: self.clone(),
|
||||
guard: Some(guard),
|
||||
untracked: false,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -368,7 +348,6 @@ where
|
||||
Some(KeyedSubfieldWriteGuard {
|
||||
inner: self.clone(),
|
||||
guard: Some(guard),
|
||||
untracked: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -465,24 +444,6 @@ where
|
||||
inner.into_iter().chain(this)
|
||||
}
|
||||
|
||||
fn path_unkeyed(&self) -> impl IntoIterator<Item = StorePathSegment> {
|
||||
let inner =
|
||||
self.inner.path_unkeyed().into_iter().collect::<StorePath>();
|
||||
let keys = self
|
||||
.inner
|
||||
.keys()
|
||||
.expect("using keys on a store with no keys");
|
||||
let this = keys
|
||||
.with_field_keys(
|
||||
inner.clone(),
|
||||
|keys| (keys.get(&self.key), vec![]),
|
||||
|| self.inner.latest_keys(),
|
||||
)
|
||||
.flatten()
|
||||
.map(|(_, idx)| StorePathSegment(idx));
|
||||
inner.into_iter().chain(this)
|
||||
}
|
||||
|
||||
fn get_trigger(&self, path: StorePath) -> StoreFieldTrigger {
|
||||
self.inner.get_trigger(path)
|
||||
}
|
||||
@@ -752,182 +713,3 @@ where
|
||||
.map(|key| AtKeyed::new(self.inner.clone(), key))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::{self as reactive_stores, tests::tick, AtKeyed, Store};
|
||||
use reactive_graph::{
|
||||
effect::Effect,
|
||||
traits::{GetUntracked, ReadUntracked, Set, Track, Write},
|
||||
};
|
||||
use reactive_stores::Patch;
|
||||
use std::sync::{
|
||||
atomic::{AtomicUsize, Ordering},
|
||||
Arc,
|
||||
};
|
||||
|
||||
#[derive(Debug, Store, Default, Patch)]
|
||||
struct Todos {
|
||||
#[store(key: usize = |todo| todo.id)]
|
||||
todos: Vec<Todo>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Store, Default, Clone, PartialEq, Eq, Patch)]
|
||||
struct Todo {
|
||||
id: usize,
|
||||
label: String,
|
||||
}
|
||||
|
||||
impl Todo {
|
||||
pub fn new(id: usize, label: impl ToString) -> Self {
|
||||
Self {
|
||||
id,
|
||||
label: label.to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn data() -> Todos {
|
||||
Todos {
|
||||
todos: vec![
|
||||
Todo {
|
||||
id: 10,
|
||||
label: "A".to_string(),
|
||||
},
|
||||
Todo {
|
||||
id: 11,
|
||||
label: "B".to_string(),
|
||||
},
|
||||
Todo {
|
||||
id: 12,
|
||||
label: "C".to_string(),
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn keyed_fields_can_be_moved() {
|
||||
_ = any_spawner::Executor::init_tokio();
|
||||
|
||||
let store = Store::new(data());
|
||||
assert_eq!(store.read_untracked().todos.len(), 3);
|
||||
|
||||
// create an effect to read from each keyed field
|
||||
let a_count = Arc::new(AtomicUsize::new(0));
|
||||
let b_count = Arc::new(AtomicUsize::new(0));
|
||||
let c_count = Arc::new(AtomicUsize::new(0));
|
||||
|
||||
let a = AtKeyed::new(store.todos(), 10);
|
||||
let b = AtKeyed::new(store.todos(), 11);
|
||||
let c = AtKeyed::new(store.todos(), 12);
|
||||
|
||||
Effect::new_sync({
|
||||
let a_count = Arc::clone(&a_count);
|
||||
move || {
|
||||
a.track();
|
||||
a_count.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
});
|
||||
Effect::new_sync({
|
||||
let b_count = Arc::clone(&b_count);
|
||||
move || {
|
||||
b.track();
|
||||
b_count.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
});
|
||||
Effect::new_sync({
|
||||
let c_count = Arc::clone(&c_count);
|
||||
move || {
|
||||
c.track();
|
||||
c_count.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
});
|
||||
|
||||
tick().await;
|
||||
assert_eq!(a_count.load(Ordering::Relaxed), 1);
|
||||
assert_eq!(b_count.load(Ordering::Relaxed), 1);
|
||||
assert_eq!(c_count.load(Ordering::Relaxed), 1);
|
||||
|
||||
// writing at a key doesn't notify siblings
|
||||
*a.label().write() = "Foo".into();
|
||||
tick().await;
|
||||
assert_eq!(a_count.load(Ordering::Relaxed), 2);
|
||||
assert_eq!(b_count.load(Ordering::Relaxed), 1);
|
||||
assert_eq!(c_count.load(Ordering::Relaxed), 1);
|
||||
|
||||
// the keys can be reorganized
|
||||
store.todos().write().swap(0, 2);
|
||||
let after = store.todos().get_untracked();
|
||||
assert_eq!(
|
||||
after,
|
||||
vec![Todo::new(12, "C"), Todo::new(11, "B"), Todo::new(10, "Foo")]
|
||||
);
|
||||
|
||||
tick().await;
|
||||
assert_eq!(a_count.load(Ordering::Relaxed), 2);
|
||||
assert_eq!(b_count.load(Ordering::Relaxed), 1);
|
||||
assert_eq!(c_count.load(Ordering::Relaxed), 1);
|
||||
|
||||
// and after we move the keys around, they still update the moved items
|
||||
a.label().set("Bar".into());
|
||||
let after = store.todos().get_untracked();
|
||||
assert_eq!(
|
||||
after,
|
||||
vec![Todo::new(12, "C"), Todo::new(11, "B"), Todo::new(10, "Bar")]
|
||||
);
|
||||
tick().await;
|
||||
assert_eq!(a_count.load(Ordering::Relaxed), 3);
|
||||
assert_eq!(b_count.load(Ordering::Relaxed), 1);
|
||||
assert_eq!(c_count.load(Ordering::Relaxed), 1);
|
||||
|
||||
// we can remove a key and add a new one
|
||||
store.todos().write().pop();
|
||||
store.todos().write().push(Todo::new(13, "New"));
|
||||
let after = store.todos().get_untracked();
|
||||
assert_eq!(
|
||||
after,
|
||||
vec![Todo::new(12, "C"), Todo::new(11, "B"), Todo::new(13, "New")]
|
||||
);
|
||||
tick().await;
|
||||
assert_eq!(a_count.load(Ordering::Relaxed), 3);
|
||||
assert_eq!(b_count.load(Ordering::Relaxed), 1);
|
||||
assert_eq!(c_count.load(Ordering::Relaxed), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn untracked_write_on_keyed_subfield_shouldnt_notify() {
|
||||
_ = any_spawner::Executor::init_tokio();
|
||||
|
||||
let store = Store::new(data());
|
||||
assert_eq!(store.read_untracked().todos.len(), 3);
|
||||
|
||||
// create an effect to read from the keyed subfield
|
||||
let todos_count = Arc::new(AtomicUsize::new(0));
|
||||
Effect::new_sync({
|
||||
let todos_count = Arc::clone(&todos_count);
|
||||
move || {
|
||||
store.todos().track();
|
||||
todos_count.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
});
|
||||
|
||||
tick().await;
|
||||
assert_eq!(todos_count.load(Ordering::Relaxed), 1);
|
||||
|
||||
// writing to keyed subfield notifies the iterator
|
||||
store.todos().write().push(Todo {
|
||||
id: 13,
|
||||
label: "D".into(),
|
||||
});
|
||||
tick().await;
|
||||
assert_eq!(todos_count.load(Ordering::Relaxed), 2);
|
||||
|
||||
// but an untracked write doesn't
|
||||
store.todos().write_untracked().push(Todo {
|
||||
id: 14,
|
||||
label: "E".into(),
|
||||
});
|
||||
tick().await;
|
||||
assert_eq!(todos_count.load(Ordering::Relaxed), 2);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -57,11 +57,11 @@
|
||||
//! # if false { // don't run effect in doctests
|
||||
//! Effect::new(move |_| {
|
||||
//! // you can access individual store fields with a getter
|
||||
//! println!("user: {:?}", &*store.user().read());
|
||||
//! println!("todos: {:?}", &*store.todos().read());
|
||||
//! });
|
||||
//! # }
|
||||
//!
|
||||
//! // won't notify the effect that listens to `user`
|
||||
//! // won't notify the effect that listens to `todos`
|
||||
//! store.todos().write().push(Todo {
|
||||
//! label: "Test".to_string(),
|
||||
//! completed: false,
|
||||
@@ -833,7 +833,7 @@ mod tests {
|
||||
use reactive_graph::{
|
||||
effect::Effect,
|
||||
owner::StoredValue,
|
||||
traits::{Read, ReadUntracked, Set, Track, Update, Write},
|
||||
traits::{Read, ReadUntracked, Set, Update, Write},
|
||||
};
|
||||
use std::sync::{
|
||||
atomic::{AtomicUsize, Ordering},
|
||||
@@ -1375,34 +1375,4 @@ mod tests {
|
||||
|
||||
assert_eq!(combined_count.load(Ordering::Relaxed), 3);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn untracked_write_on_subfield_shouldnt_notify() {
|
||||
_ = any_spawner::Executor::init_tokio();
|
||||
|
||||
let name_count = Arc::new(AtomicUsize::new(0));
|
||||
|
||||
let store = Store::new(data());
|
||||
|
||||
let tracked_field = store.user();
|
||||
|
||||
Effect::new_sync({
|
||||
let name_count = Arc::clone(&name_count);
|
||||
move |_| {
|
||||
tracked_field.track();
|
||||
name_count.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
});
|
||||
|
||||
tick().await;
|
||||
assert_eq!(name_count.load(Ordering::Relaxed), 1);
|
||||
|
||||
tracked_field.write().push('!');
|
||||
tick().await;
|
||||
assert_eq!(name_count.load(Ordering::Relaxed), 2);
|
||||
|
||||
tracked_field.write_untracked().push('!');
|
||||
tick().await;
|
||||
assert_eq!(name_count.load(Ordering::Relaxed), 2);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,7 +30,7 @@ where
|
||||
type Value = T::Value;
|
||||
|
||||
fn patch(&self, new: Self::Value) {
|
||||
let path = self.path_unkeyed().into_iter().collect::<StorePath>();
|
||||
let path = self.path().into_iter().collect::<StorePath>();
|
||||
if let Some(mut writer) = self.writer() {
|
||||
// don't track the writer for the whole store
|
||||
writer.untrack();
|
||||
|
||||
@@ -38,13 +38,6 @@ pub trait StoreField: Sized {
|
||||
#[track_caller]
|
||||
fn path(&self) -> impl IntoIterator<Item = StorePathSegment>;
|
||||
|
||||
/// The path of this field (see [`StorePath`]). Uses unkeyed indices for any keyed fields.
|
||||
#[track_caller]
|
||||
fn path_unkeyed(&self) -> impl IntoIterator<Item = StorePathSegment> {
|
||||
// TODO remove default impl next time we do a breaking release
|
||||
self.path()
|
||||
}
|
||||
|
||||
/// Reactively tracks this field.
|
||||
#[track_caller]
|
||||
fn track_field(&self) {
|
||||
@@ -136,9 +129,7 @@ where
|
||||
trigger
|
||||
}
|
||||
|
||||
#[track_caller]
|
||||
fn get_trigger_unkeyed(&self, path: StorePath) -> StoreFieldTrigger {
|
||||
let caller = std::panic::Location::caller();
|
||||
let orig_path = path.clone();
|
||||
|
||||
let mut path = StorePath::with_capacity(orig_path.len());
|
||||
@@ -149,13 +140,7 @@ where
|
||||
let key = self
|
||||
.keys
|
||||
.get_key_for_index(&(path.clone(), segment.0))
|
||||
.unwrap_or_else(|| {
|
||||
panic!(
|
||||
"could not find key for index {:?} at {}",
|
||||
&(path.clone(), segment.0),
|
||||
caller
|
||||
)
|
||||
});
|
||||
.expect("could not find key for index");
|
||||
path.push(key);
|
||||
} else {
|
||||
path.push(*segment);
|
||||
@@ -169,11 +154,6 @@ where
|
||||
iter::empty()
|
||||
}
|
||||
|
||||
#[track_caller]
|
||||
fn path_unkeyed(&self) -> impl IntoIterator<Item = StorePathSegment> {
|
||||
iter::empty()
|
||||
}
|
||||
|
||||
#[track_caller]
|
||||
fn reader(&self) -> Option<Self::Reader> {
|
||||
Plain::try_new(Arc::clone(&self.value))
|
||||
@@ -225,14 +205,6 @@ where
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
#[track_caller]
|
||||
fn path_unkeyed(&self) -> impl IntoIterator<Item = StorePathSegment> {
|
||||
self.inner
|
||||
.try_get_value()
|
||||
.map(|n| n.path_unkeyed().into_iter().collect::<Vec<_>>())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
#[track_caller]
|
||||
fn reader(&self) -> Option<Self::Reader> {
|
||||
self.inner.try_get_value().and_then(|n| n.reader())
|
||||
|
||||
@@ -84,13 +84,6 @@ where
|
||||
.chain(iter::once(self.path_segment))
|
||||
}
|
||||
|
||||
fn path_unkeyed(&self) -> impl IntoIterator<Item = StorePathSegment> {
|
||||
self.inner
|
||||
.path_unkeyed()
|
||||
.into_iter()
|
||||
.chain(iter::once(self.path_segment))
|
||||
}
|
||||
|
||||
fn get_trigger(&self, path: StorePath) -> StoreFieldTrigger {
|
||||
self.inner.get_trigger(path)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "leptos_router"
|
||||
version = "0.8.11"
|
||||
version = "0.8.9"
|
||||
authors = ["Greg Johnston", "Ben Wishovich"]
|
||||
license = "MIT"
|
||||
readme = "../README.md"
|
||||
|
||||
@@ -658,7 +658,7 @@ pub fn RoutingProgress(
|
||||
move |prev: Option<Option<IntervalHandle>>| {
|
||||
if is_routing.get() && !is_showing.get() {
|
||||
set_is_showing.set(true);
|
||||
set_interval(
|
||||
set_interval_with_handle(
|
||||
move || {
|
||||
set_progress.update(|n| *n += percent_per_increment);
|
||||
},
|
||||
@@ -670,7 +670,7 @@ pub fn RoutingProgress(
|
||||
prev?
|
||||
} else {
|
||||
set_progress.set(100.0);
|
||||
_ = set_timeout(
|
||||
set_timeout(
|
||||
move || {
|
||||
set_progress.set(0.0);
|
||||
set_is_showing.set(false);
|
||||
|
||||
@@ -131,14 +131,14 @@ where
|
||||
|
||||
if !IS_NAVIGATING.load(Ordering::Relaxed) {
|
||||
IS_NAVIGATING.store(true, Ordering::Relaxed);
|
||||
_ = request_animation_frame({
|
||||
request_animation_frame({
|
||||
let navigate = navigate.clone();
|
||||
let nav_options = nav_options.clone();
|
||||
move || {
|
||||
navigate(&new_url, nav_options.clone());
|
||||
IS_NAVIGATING.store(false, Ordering::Relaxed)
|
||||
}
|
||||
});
|
||||
})
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -105,7 +105,7 @@
|
||||
//! move || params.read().get("id").unwrap_or_default(),
|
||||
//! move |id| contact_data(id)
|
||||
//! );
|
||||
//! // ... return some view
|
||||
//! todo!()
|
||||
//! }
|
||||
//! ```
|
||||
//!
|
||||
|
||||
@@ -259,7 +259,7 @@ impl LocationProvider for BrowserUrl {
|
||||
if url.origin() == current_origin {
|
||||
let navigate = navigate.clone();
|
||||
// delay by a tick here, so that the Action updates *before* the redirect
|
||||
_ = request_animation_frame(move || {
|
||||
request_animation_frame(move || {
|
||||
navigate(&url.href(), Default::default());
|
||||
});
|
||||
// Use set_href() if the conditions for client-side navigation were not satisfied
|
||||
|
||||
@@ -199,56 +199,31 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
/// Helpers for the `Params` derive macro to allow specialization without nightly.
|
||||
pub mod macro_helpers {
|
||||
use crate::params::{IntoParam, ParamsError};
|
||||
// TODO can we support Option<T> and T in a non-nightly way?
|
||||
#[cfg(all(feature = "nightly", rustc_nightly))]
|
||||
mod option_param {
|
||||
use super::{IntoParam, ParamsError};
|
||||
use std::{str::FromStr, sync::Arc};
|
||||
|
||||
/// This struct is never actually created; it just exists so that we can impl associated
|
||||
/// functions on it.
|
||||
pub struct Wrapper<T>(T);
|
||||
auto trait NotOption {}
|
||||
impl<T> !NotOption for Option<T> {}
|
||||
|
||||
impl<T: IntoParam> Wrapper<T> {
|
||||
/// This is the 'preferred' impl to be used for all `T` that implement `IntoParam`.
|
||||
/// Because it is directly on the struct, the compiler will pick this over the impl from
|
||||
/// the `Fallback` trait.
|
||||
#[inline]
|
||||
pub fn __into_param(
|
||||
value: Option<&str>,
|
||||
name: &str,
|
||||
) -> Result<T, ParamsError> {
|
||||
T::into_param(value, name)
|
||||
}
|
||||
}
|
||||
|
||||
/// If the Fallback trait is in scope, then the compiler has two possible implementations for
|
||||
/// `__into_params`. It will pick the one from this trait if the inherent one doesn't exist.
|
||||
/// (which it won't if `T` does not implement `IntoParam`)
|
||||
pub trait Fallback<T>: Sized
|
||||
impl<T> IntoParam for T
|
||||
where
|
||||
T: FromStr,
|
||||
T: FromStr + NotOption,
|
||||
<T as FromStr>::Err: std::error::Error + Send + Sync + 'static,
|
||||
{
|
||||
/// Fallback function in case the inherent impl on the Wrapper struct does not exist for
|
||||
/// `T`
|
||||
#[inline]
|
||||
fn __into_param(
|
||||
fn into_param(
|
||||
value: Option<&str>,
|
||||
name: &str,
|
||||
) -> Result<T, ParamsError> {
|
||||
) -> Result<Self, ParamsError> {
|
||||
let value = value
|
||||
.ok_or_else(|| ParamsError::MissingParam(name.to_string()))?;
|
||||
T::from_str(value).map_err(|e| ParamsError::Params(Arc::new(e)))
|
||||
Self::from_str(value).map_err(|e| ParamsError::Params(Arc::new(e)))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Fallback<T> for Wrapper<T>
|
||||
where
|
||||
T: FromStr,
|
||||
<T as FromStr>::Err: std::error::Error + Send + Sync + 'static,
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
/// Errors that can occur while parsing params using [`Params`].
|
||||
#[derive(Error, Debug, Clone)]
|
||||
pub enum ParamsError {
|
||||
|
||||
@@ -5,7 +5,7 @@ license = "MIT"
|
||||
repository = "https://github.com/leptos-rs/leptos"
|
||||
description = "RPC for any web framework."
|
||||
readme = "../README.md"
|
||||
version = "0.8.9"
|
||||
version = "0.8.8"
|
||||
rust-version.workspace = true
|
||||
edition.workspace = true
|
||||
|
||||
@@ -32,7 +32,7 @@ dashmap = { workspace = true, default-features = true }
|
||||
|
||||
## servers
|
||||
# actix
|
||||
actix-web = { optional = true, workspace = true, default-features = false, features = ["ws"] }
|
||||
actix-web = { optional = true, workspace = true, default-features = false }
|
||||
actix-ws = { optional = true, workspace = true, default-features = true }
|
||||
|
||||
# axum
|
||||
|
||||
@@ -58,8 +58,7 @@ where
|
||||
{
|
||||
async fn from_req(req: Request) -> Result<Self, E> {
|
||||
let string_data = req.as_query().unwrap_or_default();
|
||||
let args = serde_qs::Config::new()
|
||||
.use_form_encoding(true)
|
||||
let args = serde_qs::Config::new(5, false)
|
||||
.deserialize_str::<Self>(string_data)
|
||||
.map_err(|e| {
|
||||
ServerFnErrorErr::Args(e.to_string()).into_app_error()
|
||||
@@ -98,8 +97,7 @@ where
|
||||
{
|
||||
async fn from_req(req: Request) -> Result<Self, E> {
|
||||
let string_data = req.try_into_string().await?;
|
||||
let args = serde_qs::Config::new()
|
||||
.use_form_encoding(true)
|
||||
let args = serde_qs::Config::new(5, false)
|
||||
.deserialize_str::<Self>(&string_data)
|
||||
.map_err(|e| {
|
||||
ServerFnErrorErr::Args(e.to_string()).into_app_error()
|
||||
@@ -138,8 +136,7 @@ where
|
||||
{
|
||||
async fn from_req(req: Request) -> Result<Self, E> {
|
||||
let string_data = req.as_query().unwrap_or_default();
|
||||
let args = serde_qs::Config::new()
|
||||
.use_form_encoding(true)
|
||||
let args = serde_qs::Config::new(5, false)
|
||||
.deserialize_str::<Self>(string_data)
|
||||
.map_err(|e| {
|
||||
ServerFnErrorErr::Args(e.to_string()).into_app_error()
|
||||
@@ -178,8 +175,7 @@ where
|
||||
{
|
||||
async fn from_req(req: Request) -> Result<Self, E> {
|
||||
let string_data = req.try_into_string().await?;
|
||||
let args = serde_qs::Config::new()
|
||||
.use_form_encoding(true)
|
||||
let args = serde_qs::Config::new(5, false)
|
||||
.deserialize_str::<Self>(&string_data)
|
||||
.map_err(|e| {
|
||||
ServerFnErrorErr::Args(e.to_string()).into_app_error()
|
||||
@@ -218,8 +214,7 @@ where
|
||||
{
|
||||
async fn from_req(req: Request) -> Result<Self, E> {
|
||||
let string_data = req.try_into_string().await?;
|
||||
let args = serde_qs::Config::new()
|
||||
.use_form_encoding(true)
|
||||
let args = serde_qs::Config::new(5, false)
|
||||
.deserialize_str::<Self>(&string_data)
|
||||
.map_err(|e| {
|
||||
ServerFnErrorErr::Args(e.to_string()).into_app_error()
|
||||
|
||||
@@ -309,16 +309,6 @@ impl ServerFnCall {
|
||||
.collect::<TokenStream2>()
|
||||
}
|
||||
|
||||
/// Get the lint attributes for the server function.
|
||||
pub fn lint_attrs(&self) -> TokenStream2 {
|
||||
// pass through lint attributes from the function body
|
||||
self.body
|
||||
.lint_attrs
|
||||
.iter()
|
||||
.map(|lint_attr| quote!(#lint_attr))
|
||||
.collect::<TokenStream2>()
|
||||
}
|
||||
|
||||
fn fn_name_as_str(&self) -> String {
|
||||
self.body.ident.to_string()
|
||||
}
|
||||
@@ -398,8 +388,6 @@ impl ServerFnCall {
|
||||
PathInfo::None => quote! {},
|
||||
};
|
||||
|
||||
let lint_attrs = self.lint_attrs();
|
||||
|
||||
let vis = &self.body.vis;
|
||||
let struct_name = self.struct_name();
|
||||
let fields = self
|
||||
@@ -422,7 +410,6 @@ impl ServerFnCall {
|
||||
#docs
|
||||
#[derive(Debug, #derives)]
|
||||
#addl_path
|
||||
#lint_attrs
|
||||
#vis struct #struct_name {
|
||||
#(#fields),*
|
||||
}
|
||||
@@ -1478,8 +1465,6 @@ pub struct ServerFnBody {
|
||||
pub block: TokenStream2,
|
||||
/// The documentation of the server function.
|
||||
pub docs: Vec<(String, Span)>,
|
||||
/// The lint attributes of the server function.
|
||||
pub lint_attrs: Vec<Attribute>,
|
||||
/// The middleware attributes applied to the server function.
|
||||
pub middlewares: Vec<Middleware>,
|
||||
}
|
||||
@@ -1537,27 +1522,6 @@ impl Parse for ServerFnBody {
|
||||
};
|
||||
!attr.path.is_ident("doc")
|
||||
});
|
||||
|
||||
let lint_attrs = attrs
|
||||
.iter()
|
||||
.filter_map(|attr| {
|
||||
if attr.path().is_ident("allow")
|
||||
|| attr.path().is_ident("warn")
|
||||
|| attr.path().is_ident("deny")
|
||||
|| attr.path().is_ident("forbid")
|
||||
{
|
||||
return Some(attr.clone());
|
||||
}
|
||||
None
|
||||
})
|
||||
.collect();
|
||||
attrs.retain(|attr| {
|
||||
!attr.path().is_ident("allow")
|
||||
&& !attr.path().is_ident("warn")
|
||||
&& !attr.path().is_ident("deny")
|
||||
&& !attr.path().is_ident("forbid")
|
||||
});
|
||||
|
||||
// extract all #[middleware] attributes, removing them from signature of dummy
|
||||
let mut middlewares: Vec<Middleware> = vec![];
|
||||
attrs.retain(|attr| {
|
||||
@@ -1593,7 +1557,6 @@ impl Parse for ServerFnBody {
|
||||
block,
|
||||
attrs,
|
||||
docs,
|
||||
lint_attrs,
|
||||
middlewares,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "tachys"
|
||||
version = "0.2.11"
|
||||
version = "0.2.10"
|
||||
authors = ["Greg Johnston"]
|
||||
license = "MIT"
|
||||
readme = "../README.md"
|
||||
@@ -72,7 +72,6 @@ web-sys = { features = [
|
||||
"SecurityPolicyViolationEvent",
|
||||
"StorageEvent",
|
||||
"SubmitEvent",
|
||||
"ToggleEvent",
|
||||
"TouchEvent",
|
||||
"TransitionEvent",
|
||||
"UiEvent",
|
||||
@@ -180,7 +179,6 @@ default = ["testing"]
|
||||
delegation = [] # enables event delegation
|
||||
error-hook = []
|
||||
hydrate = []
|
||||
lazy = []
|
||||
islands = ["dep:serde", "dep:serde_json"]
|
||||
ssr = []
|
||||
oco = ["dep:oco_ref"]
|
||||
|
||||
@@ -57,10 +57,6 @@ where
|
||||
_style: &mut String,
|
||||
_inner_html: &mut String,
|
||||
) {
|
||||
// If this is a class="..." attribute (not class:name=value), clear previous value
|
||||
if self.class.should_overwrite() {
|
||||
class.clear();
|
||||
}
|
||||
class.push(' ');
|
||||
self.class.to_html(class);
|
||||
}
|
||||
@@ -160,12 +156,6 @@ pub trait IntoClass: Send {
|
||||
/// Renders the class to HTML.
|
||||
fn to_html(self, class: &mut String);
|
||||
|
||||
/// Whether this class attribute should overwrite previous class values.
|
||||
/// Returns `true` for `class="..."` attributes, `false` for `class:name=value` directives.
|
||||
fn should_overwrite(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// Renders the class to HTML for a `<template>`.
|
||||
#[allow(unused)] // it's used with `nightly` feature
|
||||
fn to_template(class: &mut String) {}
|
||||
@@ -299,10 +289,6 @@ impl IntoClass for &str {
|
||||
class.push_str(self);
|
||||
}
|
||||
|
||||
fn should_overwrite(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn hydrate<const FROM_SERVER: bool>(
|
||||
self,
|
||||
el: &crate::renderer::types::Element,
|
||||
@@ -360,10 +346,6 @@ impl IntoClass for Cow<'_, str> {
|
||||
IntoClass::to_html(&*self, class);
|
||||
}
|
||||
|
||||
fn should_overwrite(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn hydrate<const FROM_SERVER: bool>(
|
||||
self,
|
||||
el: &crate::renderer::types::Element,
|
||||
@@ -421,10 +403,6 @@ impl IntoClass for String {
|
||||
IntoClass::to_html(self.as_str(), class);
|
||||
}
|
||||
|
||||
fn should_overwrite(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn hydrate<const FROM_SERVER: bool>(
|
||||
self,
|
||||
el: &crate::renderer::types::Element,
|
||||
@@ -482,10 +460,6 @@ impl IntoClass for Arc<str> {
|
||||
IntoClass::to_html(self.as_ref(), class);
|
||||
}
|
||||
|
||||
fn should_overwrite(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn hydrate<const FROM_SERVER: bool>(
|
||||
self,
|
||||
el: &crate::renderer::types::Element,
|
||||
|
||||
@@ -47,13 +47,11 @@ pub fn directive<T, P, D>(handler: D, param: P) -> Directive<T, D, P>
|
||||
where
|
||||
D: IntoDirective<T, P>,
|
||||
{
|
||||
Directive((!cfg!(feature = "ssr")).then(|| {
|
||||
SendWrapper::new(DirectiveInner {
|
||||
handler,
|
||||
param,
|
||||
t: PhantomData,
|
||||
})
|
||||
}))
|
||||
Directive(Some(SendWrapper::new(DirectiveInner {
|
||||
handler,
|
||||
param,
|
||||
t: PhantomData,
|
||||
})))
|
||||
}
|
||||
|
||||
/// Custom logic that runs in the browser when the element is created or hydrated.
|
||||
@@ -153,7 +151,13 @@ where
|
||||
Directive(inner)
|
||||
}
|
||||
|
||||
fn dry_resolve(&mut self) {}
|
||||
fn dry_resolve(&mut self) {
|
||||
// dry_resolve() only runs during SSR, and we should use it to
|
||||
// synchronously remove and drop the SendWrapper value
|
||||
// we don't need this value during SSR and leaving it here could drop it
|
||||
// from a different thread
|
||||
self.0.take();
|
||||
}
|
||||
|
||||
async fn resolve(self) -> Self::AsyncOutput {
|
||||
self
|
||||
|
||||
@@ -113,7 +113,7 @@ where
|
||||
event,
|
||||
#[cfg(feature = "reactive_graph")]
|
||||
owner: reactive_graph::owner::Owner::current().unwrap_or_default(),
|
||||
cb: (!cfg!(feature = "ssr")).then(|| SendWrapper::new(cb)),
|
||||
cb: Some(SendWrapper::new(cb)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -352,7 +352,13 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
fn dry_resolve(&mut self) {}
|
||||
fn dry_resolve(&mut self) {
|
||||
// dry_resolve() only runs during SSR, and we should use it to
|
||||
// synchronously remove and drop the SendWrapper value
|
||||
// we don't need this value during SSR and leaving it here could drop it
|
||||
// from a different thread
|
||||
self.cb.take();
|
||||
}
|
||||
|
||||
async fn resolve(self) -> Self::AsyncOutput {
|
||||
self
|
||||
@@ -608,7 +614,7 @@ generate_event_types! {
|
||||
animation start: AnimationEvent,
|
||||
aux click: MouseEvent,
|
||||
before input: InputEvent,
|
||||
before toggle: ToggleEvent,
|
||||
before toggle: Event, // web_sys does not include `ToggleEvent`
|
||||
#[does_not_bubble]
|
||||
blur: FocusEvent,
|
||||
#[does_not_bubble]
|
||||
@@ -719,7 +725,7 @@ generate_event_types! {
|
||||
#[does_not_bubble]
|
||||
time update: Event,
|
||||
#[does_not_bubble]
|
||||
toggle: ToggleEvent,
|
||||
toggle: Event,
|
||||
touch cancel: TouchEvent,
|
||||
touch end: TouchEvent,
|
||||
touch move: TouchEvent,
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user