mirror of
https://github.com/leptos-rs/leptos.git
synced 2025-12-28 07:52:34 -05:00
Compare commits
149 Commits
0.7.0-docs
...
cargo-lept
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0b62a6db8c | ||
|
|
32be3a023a | ||
|
|
d9043e4f34 | ||
|
|
e3010c7f1f | ||
|
|
1dcc5838f7 | ||
|
|
1ff373dbc2 | ||
|
|
c35c42c6e3 | ||
|
|
d4cbba7c63 | ||
|
|
9cc8ee3c5a | ||
|
|
f0c5ffe55f | ||
|
|
586c330995 | ||
|
|
72f960a026 | ||
|
|
b62ae56094 | ||
|
|
9ccefbbd8c | ||
|
|
d1108826cc | ||
|
|
d6c4cd2a81 | ||
|
|
f8acdf9168 | ||
|
|
09bbae2a72 | ||
|
|
ac3352724b | ||
|
|
3413825638 | ||
|
|
22b2d8ec84 | ||
|
|
1c3e013a63 | ||
|
|
9d4b1bc4b7 | ||
|
|
f303ff9706 | ||
|
|
9fd2a75da4 | ||
|
|
429d1b1262 | ||
|
|
035586e5d8 | ||
|
|
fdd5671fe1 | ||
|
|
293149eeb2 | ||
|
|
a9ce608433 | ||
|
|
62196ff638 | ||
|
|
db9cabb365 | ||
|
|
5293afddb7 | ||
|
|
eeb01e2d52 | ||
|
|
7d9cd43c0e | ||
|
|
723685c370 | ||
|
|
6d19e1a921 | ||
|
|
165911b2e6 | ||
|
|
575186349c | ||
|
|
10db2f83eb | ||
|
|
357f3be393 | ||
|
|
a1f5d6f79f | ||
|
|
34ecd2d541 | ||
|
|
df38b075d8 | ||
|
|
46233e3097 | ||
|
|
46f6d9ae26 | ||
|
|
8264d478e4 | ||
|
|
9c54da304e | ||
|
|
1c002a2df8 | ||
|
|
6e4dac91bf | ||
|
|
6493b0b359 | ||
|
|
d58042b7ba | ||
|
|
7a5b27ad20 | ||
|
|
78d0dbdfa2 | ||
|
|
1c30a4c131 | ||
|
|
b91429d4f0 | ||
|
|
6663fddf76 | ||
|
|
28af33d511 | ||
|
|
5a3413d3b3 | ||
|
|
702d2e247b | ||
|
|
71f698f322 | ||
|
|
8d4776bf5f | ||
|
|
65798e430f | ||
|
|
d46d1a4fab | ||
|
|
f9533ab75b | ||
|
|
d08f8822c0 | ||
|
|
7357839efb | ||
|
|
1b8ad58114 | ||
|
|
ef72f1ce96 | ||
|
|
6a5bfe9a5d | ||
|
|
1661fe2412 | ||
|
|
2324853155 | ||
|
|
28a3859365 | ||
|
|
6b50179189 | ||
|
|
0bb825f6bd | ||
|
|
a6aa111122 | ||
|
|
753cfe8e44 | ||
|
|
bc9c3add87 | ||
|
|
d0bb45dbc4 | ||
|
|
2a4b80cf22 | ||
|
|
881734b43a | ||
|
|
68fdc8d9c4 | ||
|
|
03ed805137 | ||
|
|
5d4603e988 | ||
|
|
e65969cfcd | ||
|
|
e1e90b8595 | ||
|
|
71a136c7af | ||
|
|
49366be2a5 | ||
|
|
6f5bdcc675 | ||
|
|
726a99441f | ||
|
|
775bea46d9 | ||
|
|
2aa9827a1f | ||
|
|
be3c1811fc | ||
|
|
8df4f3c71d | ||
|
|
3028a9acd0 | ||
|
|
4b167fb809 | ||
|
|
46ae8ef9b2 | ||
|
|
21f26e7a6b | ||
|
|
204648d388 | ||
|
|
a04bca55a2 | ||
|
|
1fec678174 | ||
|
|
4dbb8d1a42 | ||
|
|
fc2c52eb04 | ||
|
|
1ae35ce5b3 | ||
|
|
8edb11f324 | ||
|
|
5a01a7f2ed | ||
|
|
f252460d02 | ||
|
|
6331b488e4 | ||
|
|
fcba8b3b17 | ||
|
|
d665dd4b89 | ||
|
|
be740b38ee | ||
|
|
d2803c938c | ||
|
|
f29224415a | ||
|
|
292772c4d6 | ||
|
|
5947aa299e | ||
|
|
6098836cf7 | ||
|
|
2dfa61ff6a | ||
|
|
4f39b0b0ef | ||
|
|
980595f1f0 | ||
|
|
14eb707e82 | ||
|
|
3de0414ed5 | ||
|
|
75cae91661 | ||
|
|
8b258b0d26 | ||
|
|
84bdd6b568 | ||
|
|
809023a2ad | ||
|
|
1477ae2cfb | ||
|
|
26995f8efd | ||
|
|
3c174b26a5 | ||
|
|
0c7e77800a | ||
|
|
fee2421047 | ||
|
|
89f26f6e9b | ||
|
|
e76b22bec8 | ||
|
|
cff277b3db | ||
|
|
0258ac6df4 | ||
|
|
36132a5823 | ||
|
|
6f35f8d197 | ||
|
|
3973c4f420 | ||
|
|
7f2237b91e | ||
|
|
aa6cd08387 | ||
|
|
15fc7dd7be | ||
|
|
eac979e309 | ||
|
|
f7ac7be32b | ||
|
|
2462a1dc92 | ||
|
|
2c6d790cdb | ||
|
|
1c26261fd7 | ||
|
|
c2b239dba2 | ||
|
|
d4044cd5a1 | ||
|
|
43912f4fd0 | ||
|
|
a5293f0b79 |
12
.github/dependabot.yml
vendored
12
.github/dependabot.yml
vendored
@@ -1,12 +0,0 @@
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: "github-actions"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "daily"
|
||||
- package-ecosystem: "cargo"
|
||||
directories:
|
||||
- "/"
|
||||
schedule:
|
||||
interval: "daily"
|
||||
open-pull-requests-limit: 10
|
||||
54
.github/workflows/autofix.yml
vendored
Normal file
54
.github/workflows/autofix.yml
vendored
Normal file
@@ -0,0 +1,54 @@
|
||||
name: autofix.ci
|
||||
on:
|
||||
pull_request:
|
||||
# Running this workflow on main branch pushes requires write permission to apply changes.
|
||||
# Leave it alone for future uses.
|
||||
# push:
|
||||
# branches: ["main"]
|
||||
permissions:
|
||||
contents: read
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
RUST_BACKTRACE: 1
|
||||
DEBIAN_FRONTEND: noninteractive
|
||||
jobs:
|
||||
autofix:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions-rust-lang/setup-rust-toolchain@v1
|
||||
with: {toolchain: nightly, components: "rustfmt, clippy", target: "wasm32-unknown-unknown", rustflags: ""}
|
||||
- name: Install Glib
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y libglib2.0-dev
|
||||
- name: Install jq
|
||||
run: sudo apt-get install jq
|
||||
- run: |
|
||||
echo "Formatting the workspace"
|
||||
cargo fmt --all
|
||||
|
||||
echo "Running Clippy against each member's features (default features included)"
|
||||
for member in $(cargo metadata --no-deps --format-version 1 | jq -r '.packages[] | .name'); do
|
||||
echo "Working on member $member":
|
||||
echo -e "\tdefault-features/no-features:"
|
||||
# this will also run on members with no features or default features
|
||||
cargo clippy --allow-dirty --fix --lib --package "$member"
|
||||
|
||||
features=$(cargo metadata --no-deps --format-version 1 | jq -r ".packages[] | select(.name == \"$member\") | .features | keys[]")
|
||||
for feature in $features; do
|
||||
if [ "$feature" = "default" ]; then
|
||||
continue
|
||||
fi
|
||||
echo -e "\tfeature $feature"
|
||||
cargo clippy --allow-dirty --fix --lib --package "$member" --features "$feature"
|
||||
done
|
||||
done
|
||||
- uses: autofix-ci/action@v1.3.1
|
||||
if: ${{ always() }}
|
||||
with:
|
||||
fail-fast: false
|
||||
2
.github/workflows/ci-changed-examples.yml
vendored
2
.github/workflows/ci-changed-examples.yml
vendored
@@ -4,10 +4,12 @@ on:
|
||||
branches:
|
||||
- main
|
||||
- leptos_0.6
|
||||
- leptos_0.8
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
- leptos_0.6
|
||||
- leptos_0.8
|
||||
jobs:
|
||||
get-example-changed:
|
||||
uses: ./.github/workflows/get-example-changed.yml
|
||||
|
||||
2
.github/workflows/ci-examples.yml
vendored
2
.github/workflows/ci-examples.yml
vendored
@@ -4,10 +4,12 @@ on:
|
||||
branches:
|
||||
- main
|
||||
- leptos_0.6
|
||||
- leptos_0.8
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
- leptos_0.6
|
||||
- leptos_0.8
|
||||
jobs:
|
||||
get-leptos-changed:
|
||||
uses: ./.github/workflows/get-leptos-changed.yml
|
||||
|
||||
10
.github/workflows/ci-semver.yml
vendored
10
.github/workflows/ci-semver.yml
vendored
@@ -4,19 +4,27 @@ on:
|
||||
branches:
|
||||
- main
|
||||
- leptos_0.6
|
||||
- leptos_0.8
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
- leptos_0.6
|
||||
- leptos_0.8
|
||||
env:
|
||||
DEBIAN_FRONTEND: noninteractive
|
||||
jobs:
|
||||
get-leptos-changed:
|
||||
uses: ./.github/workflows/get-leptos-changed.yml
|
||||
test:
|
||||
needs: [get-leptos-changed]
|
||||
if: github.event.pull_request.labels[0].name == 'semver' # needs.get-leptos-changed.outputs.leptos_changed == 'true' && github.event.pull_request.labels[0].name != 'breaking'
|
||||
if: needs.get-leptos-changed.outputs.leptos_changed == 'true' && github.event.pull_request.labels[0].name != 'breaking'
|
||||
name: Run semver check (nightly-2024-08-01)
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Install Glib
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y libglib2.0-dev
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
- name: Semver Checks
|
||||
|
||||
2
.github/workflows/ci.yml
vendored
2
.github/workflows/ci.yml
vendored
@@ -4,10 +4,12 @@ on:
|
||||
branches:
|
||||
- main
|
||||
- leptos_0.6
|
||||
- leptos_0.8
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
- leptos_0.6
|
||||
- leptos_0.8
|
||||
jobs:
|
||||
get-leptos-changed:
|
||||
uses: ./.github/workflows/get-leptos-changed.yml
|
||||
|
||||
5
.github/workflows/run-cargo-make-task.yml
vendored
5
.github/workflows/run-cargo-make-task.yml
vendored
@@ -14,6 +14,7 @@ on:
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
CARGO_REGISTRIES_CRATES_IO_PROTOCOL: sparse
|
||||
DEBIAN_FRONTEND: noninteractive
|
||||
jobs:
|
||||
test:
|
||||
name: Run ${{ inputs.cargo_make_task }} (${{ inputs.toolchain }})
|
||||
@@ -33,6 +34,10 @@ jobs:
|
||||
echo "Disk space after cleanup:"
|
||||
df -h
|
||||
# Setup environment
|
||||
- name: Install Glib
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y libglib2.0-dev
|
||||
- uses: actions/checkout@v4
|
||||
- name: Setup Rust
|
||||
uses: dtolnay/rust-toolchain@master
|
||||
|
||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -14,3 +14,4 @@ blob.rs
|
||||
|
||||
.vscode
|
||||
vendor
|
||||
hash.txt
|
||||
|
||||
844
Cargo.lock
generated
844
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
52
Cargo.toml
52
Cargo.toml
@@ -40,36 +40,36 @@ members = [
|
||||
exclude = ["benchmarks", "examples", "projects"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.7.0-rc1"
|
||||
version = "0.7.5"
|
||||
edition = "2021"
|
||||
rust-version = "1.76"
|
||||
|
||||
[workspace.dependencies]
|
||||
throw_error = { path = "./any_error/", version = "0.2.0-rc1" }
|
||||
any_spawner = { path = "./any_spawner/", version = "0.1.0" }
|
||||
const_str_slice_concat = { path = "./const_str_slice_concat", version = "0.1.0" }
|
||||
throw_error = { path = "./any_error/", version = "0.2.0" }
|
||||
any_spawner = { path = "./any_spawner/", version = "0.2.0" }
|
||||
const_str_slice_concat = { path = "./const_str_slice_concat", version = "0.1" }
|
||||
either_of = { path = "./either_of/", version = "0.1.0" }
|
||||
hydration_context = { path = "./hydration_context", version = "0.2.0-rc1" }
|
||||
leptos = { path = "./leptos", version = "0.7.0-rc1" }
|
||||
leptos_config = { path = "./leptos_config", version = "0.7.0-rc1" }
|
||||
leptos_dom = { path = "./leptos_dom", version = "0.7.0-rc1" }
|
||||
leptos_hot_reload = { path = "./leptos_hot_reload", version = "0.7.0-rc1" }
|
||||
leptos_integration_utils = { path = "./integrations/utils", version = "0.7.0-rc1" }
|
||||
leptos_macro = { path = "./leptos_macro", version = "0.7.0-rc1" }
|
||||
leptos_router = { path = "./router", version = "0.7.0-rc1" }
|
||||
leptos_router_macro = { path = "./router_macro", version = "0.7.0-rc1" }
|
||||
leptos_server = { path = "./leptos_server", version = "0.7.0-rc1" }
|
||||
leptos_meta = { path = "./meta", version = "0.7.0-rc1" }
|
||||
next_tuple = { path = "./next_tuple", version = "0.1.0-rc1" }
|
||||
hydration_context = { path = "./hydration_context", version = "0.2.0" }
|
||||
leptos = { path = "./leptos", version = "0.7.5" }
|
||||
leptos_config = { path = "./leptos_config", version = "0.7.5" }
|
||||
leptos_dom = { path = "./leptos_dom", version = "0.7.5" }
|
||||
leptos_hot_reload = { path = "./leptos_hot_reload", version = "0.7.5" }
|
||||
leptos_integration_utils = { path = "./integrations/utils", version = "0.7.5" }
|
||||
leptos_macro = { path = "./leptos_macro", version = "0.7.5" }
|
||||
leptos_router = { path = "./router", version = "0.7.5" }
|
||||
leptos_router_macro = { path = "./router_macro", version = "0.7.5" }
|
||||
leptos_server = { path = "./leptos_server", version = "0.7.5" }
|
||||
leptos_meta = { path = "./meta", version = "0.7.5" }
|
||||
next_tuple = { path = "./next_tuple", version = "0.1.0" }
|
||||
oco_ref = { path = "./oco", version = "0.2.0" }
|
||||
or_poisoned = { path = "./or_poisoned", version = "0.1.0" }
|
||||
reactive_graph = { path = "./reactive_graph", version = "0.1.0-rc1" }
|
||||
reactive_stores = { path = "./reactive_stores", version = "0.1.0-rc1" }
|
||||
reactive_stores_macro = { path = "./reactive_stores_macro", version = "0.1.0-rc1" }
|
||||
server_fn = { path = "./server_fn", version = "0.7.0-rc1" }
|
||||
server_fn_macro = { path = "./server_fn_macro", version = "0.7.0-rc1" }
|
||||
server_fn_macro_default = { path = "./server_fn/server_fn_macro_default", version = "0.7.0-rc1" }
|
||||
tachys = { path = "./tachys", version = "0.1.0-rc1" }
|
||||
reactive_graph = { path = "./reactive_graph", version = "0.1.5" }
|
||||
reactive_stores = { path = "./reactive_stores", version = "0.1.3" }
|
||||
reactive_stores_macro = { path = "./reactive_stores_macro", version = "0.1.0" }
|
||||
server_fn = { path = "./server_fn", version = "0.7.5" }
|
||||
server_fn_macro = { path = "./server_fn_macro", version = "0.7.5" }
|
||||
server_fn_macro_default = { path = "./server_fn/server_fn_macro_default", version = "0.7.5" }
|
||||
tachys = { path = "./tachys", version = "0.1.5" }
|
||||
|
||||
[profile.release]
|
||||
codegen-units = 1
|
||||
@@ -78,3 +78,9 @@ opt-level = 'z'
|
||||
|
||||
[workspace.metadata.cargo-all-features]
|
||||
skip_feature_sets = [["csr", "ssr"], ["csr", "hydrate"], ["ssr", "hydrate"]]
|
||||
|
||||
[workspace.lints.rust]
|
||||
unexpected_cfgs = { level = "warn", check-cfg = [
|
||||
'cfg(leptos_debuginfo)',
|
||||
'cfg(erase_components)',
|
||||
] }
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
|
||||
[](https://crates.io/crates/leptos)
|
||||
[](https://docs.rs/leptos)
|
||||

|
||||
[](https://discord.gg/YdRAhS7eQB)
|
||||
[](https://matrix.to/#/#leptos:matrix.org)
|
||||
|
||||
@@ -12,8 +13,6 @@
|
||||
|
||||
You can find a list of useful libraries and example projects at [`awesome-leptos`](https://github.com/leptos-rs/awesome-leptos).
|
||||
|
||||
# The `main` branch is currently undergoing major changes in preparation for the [0.7](https://github.com/leptos-rs/leptos/milestone/4) release. For a stable version, please use the [v0.6.13 tag](https://github.com/leptos-rs/leptos/tree/v0.6.13)
|
||||
|
||||
# Leptos
|
||||
|
||||
```rust
|
||||
@@ -169,14 +168,14 @@ Yew is the most-used library for Rust web UI development, but there are several
|
||||
- **Performance:** This has huge performance implications: Leptos is simply much faster at both creating and updating the UI than Yew is.
|
||||
- **Server integration:** Yew was created in an era in which browser-rendered single-page apps (SPAs) were the dominant paradigm. While Leptos supports client-side rendering, it also focuses on integrating with the server side of your application via server functions and multiple modes of serving HTML, including out-of-order streaming.
|
||||
|
||||
- ### How is this different from Dioxus?
|
||||
### How is this different from Dioxus?
|
||||
|
||||
Like Leptos, Dioxus is a framework for building UIs using web technologies. However, there are significant differences in approach and features.
|
||||
|
||||
- **VDOM vs. fine-grained:** While Dioxus has a performant virtual DOM (VDOM), it still uses coarse-grained/component-scoped reactivity: changing a stateful value reruns the component function and diffs the old UI against the new one. Leptos components use a different mental model, creating (and returning) actual DOM nodes and setting up a reactive system to update those DOM nodes.
|
||||
- **Web vs. desktop priorities:** Dioxus uses Leptos server functions in its fullstack mode, but does not have the same `<Suspense>`-based support for things like streaming HTML rendering, or share the same focus on holistic web performance. Leptos tends to prioritize holistic web performance (streaming HTML rendering, smaller WASM binary sizes, etc.), whereas Dioxus has an unparalleled experience when building desktop apps, because your application logic runs as a native Rust binary.
|
||||
|
||||
- ### How is this different from Sycamore?
|
||||
### How is this different from Sycamore?
|
||||
|
||||
Sycamore and Leptos are both heavily influenced by SolidJS. At this point, Leptos has a larger community and ecosystem and is more actively developed. Other differences:
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "throw_error"
|
||||
version = "0.2.0-rc1"
|
||||
version = "0.2.0"
|
||||
authors = ["Greg Johnston"]
|
||||
license = "MIT"
|
||||
readme = "../README.md"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "any_spawner"
|
||||
version = "0.1.1"
|
||||
version = "0.2.1"
|
||||
authors = ["Greg Johnston"]
|
||||
license = "MIT"
|
||||
readme = "../README.md"
|
||||
@@ -11,13 +11,13 @@ edition.workspace = true
|
||||
[dependencies]
|
||||
async-executor = { version = "1.13.1", optional = true }
|
||||
futures = "0.3.31"
|
||||
glib = { version = "0.20.5", optional = true }
|
||||
glib = { version = "0.20.6", optional = true }
|
||||
thiserror = "2.0"
|
||||
tokio = { version = "1.41", optional = true, default-features = false, features = [
|
||||
"rt",
|
||||
] }
|
||||
tracing = { version = "0.1.40", optional = true }
|
||||
wasm-bindgen-futures = { version = "0.4.45", optional = true }
|
||||
tracing = { version = "0.1.41", optional = true }
|
||||
wasm-bindgen-futures = { version = "0.4.47", optional = true }
|
||||
|
||||
[features]
|
||||
async-executor = ["dep:async-executor"]
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "either_of"
|
||||
version = "0.1.0"
|
||||
version = "0.1.5"
|
||||
authors = ["Greg Johnston"]
|
||||
license = "MIT"
|
||||
readme = "../README.md"
|
||||
@@ -10,4 +10,9 @@ rust-version.workspace = true
|
||||
edition.workspace = true
|
||||
|
||||
[dependencies]
|
||||
pin-project-lite = "0.2.15"
|
||||
pin-project-lite = "0.2.16"
|
||||
paste = "1.0.15"
|
||||
|
||||
[features]
|
||||
default = ["no_std"]
|
||||
no_std = []
|
||||
|
||||
@@ -1,140 +1,758 @@
|
||||
#![no_std]
|
||||
#![cfg_attr(feature = "no_std", no_std)]
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
//! Utilities for working with enumerated types that contain one of `2..n` other types.
|
||||
|
||||
use core::{
|
||||
cmp::Ordering,
|
||||
fmt::Display,
|
||||
future::Future,
|
||||
iter::{Product, Sum},
|
||||
pin::Pin,
|
||||
task::{Context, Poll},
|
||||
};
|
||||
use paste::paste;
|
||||
use pin_project_lite::pin_project;
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub enum Either<A, B> {
|
||||
Left(A),
|
||||
Right(B),
|
||||
}
|
||||
|
||||
impl<Item, A, B> Iterator for Either<A, B>
|
||||
where
|
||||
A: Iterator<Item = Item>,
|
||||
B: Iterator<Item = Item>,
|
||||
{
|
||||
type Item = Item;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
match self {
|
||||
Either::Left(i) => i.next(),
|
||||
Either::Right(i) => i.next(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pin_project! {
|
||||
#[project = EitherFutureProj]
|
||||
pub enum EitherFuture<A, B> {
|
||||
Left { #[pin] inner: A },
|
||||
Right { #[pin] inner: B },
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, B> Future for EitherFuture<A, B>
|
||||
where
|
||||
A: Future,
|
||||
B: Future,
|
||||
{
|
||||
type Output = Either<A::Output, B::Output>;
|
||||
|
||||
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
||||
let this = self.project();
|
||||
match this {
|
||||
EitherFutureProj::Left { inner } => match inner.poll(cx) {
|
||||
Poll::Pending => Poll::Pending,
|
||||
Poll::Ready(inner) => Poll::Ready(Either::Left(inner)),
|
||||
},
|
||||
EitherFutureProj::Right { inner } => match inner.poll(cx) {
|
||||
Poll::Pending => Poll::Pending,
|
||||
Poll::Ready(inner) => Poll::Ready(Either::Right(inner)),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
#[cfg(not(feature = "no_std"))]
|
||||
use std::error::Error; // TODO: replace with core::error::Error once MSRV is >= 1.81.0
|
||||
|
||||
macro_rules! tuples {
|
||||
($name:ident + $fut_name:ident + $fut_proj:ident => $($ty:ident),*) => {
|
||||
($name:ident + $fut_name:ident + $fut_proj:ident {
|
||||
$($ty:ident => ($($rest_variant:ident),*) + <$($mapped_ty:ident),+>),+$(,)?
|
||||
}) => {
|
||||
tuples!($name + $fut_name + $fut_proj {
|
||||
$($ty($ty) => ($($rest_variant),*) + <$($mapped_ty),+>),+
|
||||
});
|
||||
};
|
||||
($name:ident + $fut_name:ident + $fut_proj:ident {
|
||||
$($variant:ident($ty:ident) => ($($rest_variant:ident),*) + <$($mapped_ty:ident),+>),+$(,)?
|
||||
}) => {
|
||||
#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
|
||||
pub enum $name<$($ty,)*> {
|
||||
$($ty ($ty),)*
|
||||
pub enum $name<$($ty),+> {
|
||||
$($variant ($ty),)+
|
||||
}
|
||||
|
||||
impl<$($ty,)*> Display for $name<$($ty,)*>
|
||||
impl<$($ty),+> $name<$($ty),+> {
|
||||
paste! {
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn map<$([<F $ty>]),+, $([<$ty 1>]),+>(self, $([<$variant:lower>]: [<F $ty>]),+) -> $name<$([<$ty 1>]),+>
|
||||
where
|
||||
$([<F $ty>]: FnOnce($ty) -> [<$ty 1>],)+
|
||||
{
|
||||
match self {
|
||||
$($name::$variant(inner) => $name::$variant([<$variant:lower>](inner)),)+
|
||||
}
|
||||
}
|
||||
|
||||
$(
|
||||
pub fn [<map_ $variant:lower>]<Fun, [<$ty 1>]>(self, f: Fun) -> $name<$($mapped_ty),+>
|
||||
where
|
||||
Fun: FnOnce($ty) -> [<$ty 1>],
|
||||
{
|
||||
match self {
|
||||
$name::$variant(inner) => $name::$variant(f(inner)),
|
||||
$($name::$rest_variant(inner) => $name::$rest_variant(inner),)*
|
||||
}
|
||||
}
|
||||
|
||||
pub fn [<inspect_ $variant:lower>]<Fun, [<$ty 1>]>(self, f: Fun) -> Self
|
||||
where
|
||||
Fun: FnOnce(&$ty),
|
||||
{
|
||||
if let $name::$variant(inner) = &self {
|
||||
f(inner);
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
pub fn [<is_ $variant:lower>](&self) -> bool {
|
||||
matches!(self, $name::$variant(_))
|
||||
}
|
||||
|
||||
pub fn [<as_ $variant:lower>](&self) -> Option<&$ty> {
|
||||
match self {
|
||||
$name::$variant(inner) => Some(inner),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn [<as_ $variant:lower _mut>](&mut self) -> Option<&mut $ty> {
|
||||
match self {
|
||||
$name::$variant(inner) => Some(inner),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn [<unwrap_ $variant:lower>](self) -> $ty {
|
||||
match self {
|
||||
$name::$variant(inner) => inner,
|
||||
_ => panic!(concat!(
|
||||
"called `unwrap_", stringify!([<$variant:lower>]), "()` on a non-`", stringify!($variant), "` variant of `", stringify!($name), "`"
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn [<into_ $variant:lower>](self) -> Result<$ty, Self> {
|
||||
match self {
|
||||
$name::$variant(inner) => Ok(inner),
|
||||
_ => Err(self),
|
||||
}
|
||||
}
|
||||
)+
|
||||
}
|
||||
}
|
||||
|
||||
impl<$($ty),+> Display for $name<$($ty),+>
|
||||
where
|
||||
$($ty: Display,)*
|
||||
$($ty: Display,)+
|
||||
{
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
match self {
|
||||
$($name::$ty(this) => this.fmt(f),)*
|
||||
$($name::$variant(this) => this.fmt(f),)+
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<Item, $($ty,)*> Iterator for $name<$($ty,)*>
|
||||
#[cfg(not(feature = "no_std"))]
|
||||
impl<$($ty),+> Error for $name<$($ty),+>
|
||||
where
|
||||
$($ty: Iterator<Item = Item>,)*
|
||||
$($ty: Error,)+
|
||||
{
|
||||
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
||||
match self {
|
||||
$($name::$variant(this) => this.source(),)+
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<Item, $($ty),+> Iterator for $name<$($ty),+>
|
||||
where
|
||||
$($ty: Iterator<Item = Item>,)+
|
||||
{
|
||||
type Item = Item;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
match self {
|
||||
$($name::$ty(i) => i.next(),)*
|
||||
$($name::$variant(i) => i.next(),)+
|
||||
}
|
||||
}
|
||||
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
match self {
|
||||
$($name::$variant(i) => i.size_hint(),)+
|
||||
}
|
||||
}
|
||||
|
||||
fn count(self) -> usize
|
||||
where
|
||||
Self: Sized,
|
||||
{
|
||||
match self {
|
||||
$($name::$variant(i) => i.count(),)+
|
||||
}
|
||||
}
|
||||
|
||||
fn last(self) -> Option<Self::Item>
|
||||
where
|
||||
Self: Sized,
|
||||
{
|
||||
match self {
|
||||
$($name::$variant(i) => i.last(),)+
|
||||
}
|
||||
}
|
||||
|
||||
fn nth(&mut self, n: usize) -> Option<Self::Item> {
|
||||
match self {
|
||||
$($name::$variant(i) => i.nth(n),)+
|
||||
}
|
||||
}
|
||||
|
||||
fn for_each<Fun>(self, f: Fun)
|
||||
where
|
||||
Self: Sized,
|
||||
Fun: FnMut(Self::Item),
|
||||
{
|
||||
match self {
|
||||
$($name::$variant(i) => i.for_each(f),)+
|
||||
}
|
||||
}
|
||||
|
||||
fn collect<Col: FromIterator<Self::Item>>(self) -> Col
|
||||
where
|
||||
Self: Sized,
|
||||
{
|
||||
match self {
|
||||
$($name::$variant(i) => i.collect(),)+
|
||||
}
|
||||
}
|
||||
|
||||
fn partition<Col, Fun>(self, f: Fun) -> (Col, Col)
|
||||
where
|
||||
Self: Sized,
|
||||
Col: Default + Extend<Self::Item>,
|
||||
Fun: FnMut(&Self::Item) -> bool,
|
||||
{
|
||||
match self {
|
||||
$($name::$variant(i) => i.partition(f),)+
|
||||
}
|
||||
}
|
||||
|
||||
fn fold<Acc, Fun>(self, init: Acc, f: Fun) -> Acc
|
||||
where
|
||||
Self: Sized,
|
||||
Fun: FnMut(Acc, Self::Item) -> Acc,
|
||||
{
|
||||
match self {
|
||||
$($name::$variant(i) => i.fold(init, f),)+
|
||||
}
|
||||
}
|
||||
|
||||
fn reduce<Fun>(self, f: Fun) -> Option<Self::Item>
|
||||
where
|
||||
Self: Sized,
|
||||
Fun: FnMut(Self::Item, Self::Item) -> Self::Item,
|
||||
{
|
||||
match self {
|
||||
$($name::$variant(i) => i.reduce(f),)+
|
||||
}
|
||||
}
|
||||
|
||||
fn all<Fun>(&mut self, f: Fun) -> bool
|
||||
where
|
||||
Self: Sized,
|
||||
Fun: FnMut(Self::Item) -> bool,
|
||||
{
|
||||
match self {
|
||||
$($name::$variant(i) => i.all(f),)+
|
||||
}
|
||||
}
|
||||
|
||||
fn any<Fun>(&mut self, f: Fun) -> bool
|
||||
where
|
||||
Self: Sized,
|
||||
Fun: FnMut(Self::Item) -> bool,
|
||||
{
|
||||
match self {
|
||||
$($name::$variant(i) => i.any(f),)+
|
||||
}
|
||||
}
|
||||
|
||||
fn find<Pre>(&mut self, predicate: Pre) -> Option<Self::Item>
|
||||
where
|
||||
Self: Sized,
|
||||
Pre: FnMut(&Self::Item) -> bool,
|
||||
{
|
||||
match self {
|
||||
$($name::$variant(i) => i.find(predicate),)+
|
||||
}
|
||||
}
|
||||
|
||||
fn find_map<Out, Fun>(&mut self, f: Fun) -> Option<Out>
|
||||
where
|
||||
Self: Sized,
|
||||
Fun: FnMut(Self::Item) -> Option<Out>,
|
||||
{
|
||||
match self {
|
||||
$($name::$variant(i) => i.find_map(f),)+
|
||||
}
|
||||
}
|
||||
|
||||
fn position<Pre>(&mut self, predicate: Pre) -> Option<usize>
|
||||
where
|
||||
Self: Sized,
|
||||
Pre: FnMut(Self::Item) -> bool,
|
||||
{
|
||||
match self {
|
||||
$($name::$variant(i) => i.position(predicate),)+
|
||||
}
|
||||
}
|
||||
|
||||
fn max(self) -> Option<Self::Item>
|
||||
where
|
||||
Self: Sized,
|
||||
Self::Item: Ord,
|
||||
{
|
||||
match self {
|
||||
$($name::$variant(i) => i.max(),)+
|
||||
}
|
||||
}
|
||||
|
||||
fn min(self) -> Option<Self::Item>
|
||||
where
|
||||
Self: Sized,
|
||||
Self::Item: Ord,
|
||||
{
|
||||
match self {
|
||||
$($name::$variant(i) => i.min(),)+
|
||||
}
|
||||
}
|
||||
|
||||
fn max_by_key<Key: Ord, Fun>(self, f: Fun) -> Option<Self::Item>
|
||||
where
|
||||
Self: Sized,
|
||||
Fun: FnMut(&Self::Item) -> Key,
|
||||
{
|
||||
match self {
|
||||
$($name::$variant(i) => i.max_by_key(f),)+
|
||||
}
|
||||
}
|
||||
|
||||
fn max_by<Cmp>(self, compare: Cmp) -> Option<Self::Item>
|
||||
where
|
||||
Self: Sized,
|
||||
Cmp: FnMut(&Self::Item, &Self::Item) -> Ordering,
|
||||
{
|
||||
match self {
|
||||
$($name::$variant(i) => i.max_by(compare),)+
|
||||
}
|
||||
}
|
||||
|
||||
fn min_by_key<Key: Ord, Fun>(self, f: Fun) -> Option<Self::Item>
|
||||
where
|
||||
Self: Sized,
|
||||
Fun: FnMut(&Self::Item) -> Key,
|
||||
{
|
||||
match self {
|
||||
$($name::$variant(i) => i.min_by_key(f),)+
|
||||
}
|
||||
}
|
||||
|
||||
fn min_by<Cmp>(self, compare: Cmp) -> Option<Self::Item>
|
||||
where
|
||||
Self: Sized,
|
||||
Cmp: FnMut(&Self::Item, &Self::Item) -> Ordering,
|
||||
{
|
||||
match self {
|
||||
$($name::$variant(i) => i.min_by(compare),)+
|
||||
}
|
||||
}
|
||||
|
||||
fn sum<Out>(self) -> Out
|
||||
where
|
||||
Self: Sized,
|
||||
Out: Sum<Self::Item>,
|
||||
{
|
||||
match self {
|
||||
$($name::$variant(i) => i.sum(),)+
|
||||
}
|
||||
}
|
||||
|
||||
fn product<Out>(self) -> Out
|
||||
where
|
||||
Self: Sized,
|
||||
Out: Product<Self::Item>,
|
||||
{
|
||||
match self {
|
||||
$($name::$variant(i) => i.product(),)+
|
||||
}
|
||||
}
|
||||
|
||||
fn cmp<Other>(self, other: Other) -> Ordering
|
||||
where
|
||||
Other: IntoIterator<Item = Self::Item>,
|
||||
Self::Item: Ord,
|
||||
Self: Sized,
|
||||
{
|
||||
match self {
|
||||
$($name::$variant(i) => i.cmp(other),)+
|
||||
}
|
||||
}
|
||||
|
||||
fn partial_cmp<Other>(self, other: Other) -> Option<Ordering>
|
||||
where
|
||||
Other: IntoIterator,
|
||||
Self::Item: PartialOrd<Other::Item>,
|
||||
Self: Sized,
|
||||
{
|
||||
match self {
|
||||
$($name::$variant(i) => i.partial_cmp(other),)+
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: uncomment once MSRV is >= 1.82.0
|
||||
// fn is_sorted(self) -> bool
|
||||
// where
|
||||
// Self: Sized,
|
||||
// Self::Item: PartialOrd,
|
||||
// {
|
||||
// match self {
|
||||
// $($name::$variant(i) => i.is_sorted(),)+
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// fn is_sorted_by<Cmp>(self, compare: Cmp) -> bool
|
||||
// where
|
||||
// Self: Sized,
|
||||
// Cmp: FnMut(&Self::Item, &Self::Item) -> bool,
|
||||
// {
|
||||
// match self {
|
||||
// $($name::$variant(i) => i.is_sorted_by(compare),)+
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// fn is_sorted_by_key<Fun, Key>(self, f: Fun) -> bool
|
||||
// where
|
||||
// Self: Sized,
|
||||
// Fun: FnMut(Self::Item) -> Key,
|
||||
// Key: PartialOrd,
|
||||
// {
|
||||
// match self {
|
||||
// $($name::$variant(i) => i.is_sorted_by_key(f),)+
|
||||
// }
|
||||
// }
|
||||
}
|
||||
|
||||
impl<Item, $($ty),+> ExactSizeIterator for $name<$($ty),+>
|
||||
where
|
||||
$($ty: ExactSizeIterator<Item = Item>,)+
|
||||
{
|
||||
fn len(&self) -> usize {
|
||||
match self {
|
||||
$($name::$variant(i) => i.len(),)+
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<Item, $($ty),+> DoubleEndedIterator for $name<$($ty),+>
|
||||
where
|
||||
$($ty: DoubleEndedIterator<Item = Item>,)+
|
||||
{
|
||||
fn next_back(&mut self) -> Option<Self::Item> {
|
||||
match self {
|
||||
$($name::$variant(i) => i.next_back(),)+
|
||||
}
|
||||
}
|
||||
|
||||
fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
|
||||
match self {
|
||||
$($name::$variant(i) => i.nth_back(n),)+
|
||||
}
|
||||
}
|
||||
|
||||
fn rfind<Pre>(&mut self, predicate: Pre) -> Option<Self::Item>
|
||||
where
|
||||
Pre: FnMut(&Self::Item) -> bool,
|
||||
{
|
||||
match self {
|
||||
$($name::$variant(i) => i.rfind(predicate),)+
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pin_project! {
|
||||
#[project = $fut_proj]
|
||||
pub enum $fut_name<$($ty,)*> {
|
||||
$($ty { #[pin] inner: $ty },)*
|
||||
pub enum $fut_name<$($ty),+> {
|
||||
$($variant { #[pin] inner: $ty },)+
|
||||
}
|
||||
}
|
||||
|
||||
impl<$($ty,)*> Future for $fut_name<$($ty,)*>
|
||||
impl<$($ty),+> Future for $fut_name<$($ty),+>
|
||||
where
|
||||
$($ty: Future,)*
|
||||
$($ty: Future,)+
|
||||
{
|
||||
type Output = $name<$($ty::Output,)*>;
|
||||
type Output = $name<$($ty::Output),+>;
|
||||
|
||||
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
||||
let this = self.project();
|
||||
match this {
|
||||
$($fut_proj::$ty { inner } => match inner.poll(cx) {
|
||||
$($fut_proj::$variant { inner } => match inner.poll(cx) {
|
||||
Poll::Pending => Poll::Pending,
|
||||
Poll::Ready(inner) => Poll::Ready($name::$ty(inner)),
|
||||
},)*
|
||||
Poll::Ready(inner) => Poll::Ready($name::$variant(inner)),
|
||||
},)+
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
tuples!(EitherOf3 + EitherOf3Future + EitherOf3FutureProj => A, B, C);
|
||||
tuples!(EitherOf4 + EitherOf4Future + EitherOf4FutureProj => A, B, C, D);
|
||||
tuples!(EitherOf5 + EitherOf5Future + EitherOf5FutureProj => A, B, C, D, E);
|
||||
tuples!(EitherOf6 + EitherOf6Future + EitherOf6FutureProj => A, B, C, D, E, F);
|
||||
tuples!(EitherOf7 + EitherOf7Future + EitherOf7FutureProj => A, B, C, D, E, F, G);
|
||||
tuples!(EitherOf8 + EitherOf8Future + EitherOf8FutureProj => A, B, C, D, E, F, G, H);
|
||||
tuples!(EitherOf9 + EitherOf9Future + EitherOf9FutureProj => A, B, C, D, E, F, G, H, I);
|
||||
tuples!(EitherOf10 + EitherOf10Future + EitherOf10FutureProj => A, B, C, D, E, F, G, H, I, J);
|
||||
tuples!(EitherOf11 + EitherOf11Future + EitherOf11FutureProj => A, B, C, D, E, F, G, H, I, J, K);
|
||||
tuples!(EitherOf12 + EitherOf12Future + EitherOf12FutureProj => A, B, C, D, E, F, G, H, I, J, K, L);
|
||||
tuples!(EitherOf13 + EitherOf13Future + EitherOf13FutureProj => A, B, C, D, E, F, G, H, I, J, K, L, M);
|
||||
tuples!(EitherOf14 + EitherOf14Future + EitherOf14FutureProj => A, B, C, D, E, F, G, H, I, J, K, L, M, N);
|
||||
tuples!(EitherOf15 + EitherOf15Future + EitherOf15FutureProj => A, B, C, D, E, F, G, H, I, J, K, L, M, N, O);
|
||||
tuples!(EitherOf16 + EitherOf16Future + EitherOf16FutureProj => A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P);
|
||||
tuples!(Either + EitherFuture + EitherFutureProj {
|
||||
Left(A) => (Right) + <A1, B>,
|
||||
Right(B) => (Left) + <A, B1>,
|
||||
});
|
||||
|
||||
/// Matches over the first expression and returns an either ([`Either`], [`EitherOf3`], ... [`EitherOf6`])
|
||||
impl<A, B> Either<A, B> {
|
||||
pub fn swap(self) -> Either<B, A> {
|
||||
match self {
|
||||
Either::Left(a) => Either::Right(a),
|
||||
Either::Right(b) => Either::Left(b),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, B> From<Result<A, B>> for Either<A, B> {
|
||||
fn from(value: Result<A, B>) -> Self {
|
||||
match value {
|
||||
Ok(left) => Either::Left(left),
|
||||
Err(right) => Either::Right(right),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub trait EitherOr {
|
||||
type Left;
|
||||
type Right;
|
||||
fn either_or<FA, A, FB, B>(self, a: FA, b: FB) -> Either<A, B>
|
||||
where
|
||||
FA: FnOnce(Self::Left) -> A,
|
||||
FB: FnOnce(Self::Right) -> B;
|
||||
}
|
||||
|
||||
impl EitherOr for bool {
|
||||
type Left = ();
|
||||
type Right = ();
|
||||
|
||||
fn either_or<FA, A, FB, B>(self, a: FA, b: FB) -> Either<A, B>
|
||||
where
|
||||
FA: FnOnce(Self::Left) -> A,
|
||||
FB: FnOnce(Self::Right) -> B,
|
||||
{
|
||||
if self {
|
||||
Either::Left(a(()))
|
||||
} else {
|
||||
Either::Right(b(()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> EitherOr for Option<T> {
|
||||
type Left = T;
|
||||
type Right = ();
|
||||
|
||||
fn either_or<FA, A, FB, B>(self, a: FA, b: FB) -> Either<A, B>
|
||||
where
|
||||
FA: FnOnce(Self::Left) -> A,
|
||||
FB: FnOnce(Self::Right) -> B,
|
||||
{
|
||||
match self {
|
||||
Some(t) => Either::Left(a(t)),
|
||||
None => Either::Right(b(())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, E> EitherOr for Result<T, E> {
|
||||
type Left = T;
|
||||
type Right = E;
|
||||
|
||||
fn either_or<FA, A, FB, B>(self, a: FA, b: FB) -> Either<A, B>
|
||||
where
|
||||
FA: FnOnce(Self::Left) -> A,
|
||||
FB: FnOnce(Self::Right) -> B,
|
||||
{
|
||||
match self {
|
||||
Ok(t) => Either::Left(a(t)),
|
||||
Err(err) => Either::Right(b(err)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, B> EitherOr for Either<A, B> {
|
||||
type Left = A;
|
||||
type Right = B;
|
||||
|
||||
#[inline]
|
||||
fn either_or<FA, A1, FB, B1>(self, a: FA, b: FB) -> Either<A1, B1>
|
||||
where
|
||||
FA: FnOnce(<Self as EitherOr>::Left) -> A1,
|
||||
FB: FnOnce(<Self as EitherOr>::Right) -> B1,
|
||||
{
|
||||
self.map(a, b)
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_either_or() {
|
||||
let right = false.either_or(|_| 'a', |_| 12);
|
||||
assert!(matches!(right, Either::Right(12)));
|
||||
|
||||
let left = true.either_or(|_| 'a', |_| 12);
|
||||
assert!(matches!(left, Either::Left('a')));
|
||||
|
||||
let left = Some(12).either_or(|a| a, |_| 'a');
|
||||
assert!(matches!(left, Either::Left(12)));
|
||||
let right = None.either_or(|a: i32| a, |_| 'a');
|
||||
assert!(matches!(right, Either::Right('a')));
|
||||
|
||||
let result: Result<_, ()> = Ok(1.2f32);
|
||||
let left = result.either_or(|a| a * 2f32, |b| b);
|
||||
assert!(matches!(left, Either::Left(2.4f32)));
|
||||
|
||||
let result: Result<i32, _> = Err("12");
|
||||
let right = result.either_or(|a| a, |b| b.chars().next());
|
||||
assert!(matches!(right, Either::Right(Some('1'))));
|
||||
|
||||
let either = Either::<i32, char>::Left(12);
|
||||
let left = either.either_or(|a| a, |b| b);
|
||||
assert!(matches!(left, Either::Left(12)));
|
||||
|
||||
let either = Either::<i32, char>::Right('a');
|
||||
let right = either.either_or(|a| a, |b| b);
|
||||
assert!(matches!(right, Either::Right('a')));
|
||||
}
|
||||
|
||||
tuples!(EitherOf3 + EitherOf3Future + EitherOf3FutureProj {
|
||||
A => (B, C) + <A1, B, C>,
|
||||
B => (A, C) + <A, B1, C>,
|
||||
C => (A, B) + <A, B, C1>,
|
||||
});
|
||||
tuples!(EitherOf4 + EitherOf4Future + EitherOf4FutureProj {
|
||||
A => (B, C, D) + <A1, B, C, D>,
|
||||
B => (A, C, D) + <A, B1, C, D>,
|
||||
C => (A, B, D) + <A, B, C1, D>,
|
||||
D => (A, B, C) + <A, B, C, D1>,
|
||||
});
|
||||
tuples!(EitherOf5 + EitherOf5Future + EitherOf5FutureProj {
|
||||
A => (B, C, D, E) + <A1, B, C, D, E>,
|
||||
B => (A, C, D, E) + <A, B1, C, D, E>,
|
||||
C => (A, B, D, E) + <A, B, C1, D, E>,
|
||||
D => (A, B, C, E) + <A, B, C, D1, E>,
|
||||
E => (A, B, C, D) + <A, B, C, D, E1>,
|
||||
});
|
||||
tuples!(EitherOf6 + EitherOf6Future + EitherOf6FutureProj {
|
||||
A => (B, C, D, E, F) + <A1, B, C, D, E, F>,
|
||||
B => (A, C, D, E, F) + <A, B1, C, D, E, F>,
|
||||
C => (A, B, D, E, F) + <A, B, C1, D, E, F>,
|
||||
D => (A, B, C, E, F) + <A, B, C, D1, E, F>,
|
||||
E => (A, B, C, D, F) + <A, B, C, D, E1, F>,
|
||||
F => (A, B, C, D, E) + <A, B, C, D, E, F1>,
|
||||
});
|
||||
tuples!(EitherOf7 + EitherOf7Future + EitherOf7FutureProj {
|
||||
A => (B, C, D, E, F, G) + <A1, B, C, D, E, F, G>,
|
||||
B => (A, C, D, E, F, G) + <A, B1, C, D, E, F, G>,
|
||||
C => (A, B, D, E, F, G) + <A, B, C1, D, E, F, G>,
|
||||
D => (A, B, C, E, F, G) + <A, B, C, D1, E, F, G>,
|
||||
E => (A, B, C, D, F, G) + <A, B, C, D, E1, F, G>,
|
||||
F => (A, B, C, D, E, G) + <A, B, C, D, E, F1, G>,
|
||||
G => (A, B, C, D, E, F) + <A, B, C, D, E, F, G1>,
|
||||
});
|
||||
tuples!(EitherOf8 + EitherOf8Future + EitherOf8FutureProj {
|
||||
A => (B, C, D, E, F, G, H) + <A1, B, C, D, E, F, G, H>,
|
||||
B => (A, C, D, E, F, G, H) + <A, B1, C, D, E, F, G, H>,
|
||||
C => (A, B, D, E, F, G, H) + <A, B, C1, D, E, F, G, H>,
|
||||
D => (A, B, C, E, F, G, H) + <A, B, C, D1, E, F, G, H>,
|
||||
E => (A, B, C, D, F, G, H) + <A, B, C, D, E1, F, G, H>,
|
||||
F => (A, B, C, D, E, G, H) + <A, B, C, D, E, F1, G, H>,
|
||||
G => (A, B, C, D, E, F, H) + <A, B, C, D, E, F, G1, H>,
|
||||
H => (A, B, C, D, E, F, G) + <A, B, C, D, E, F, G, H1>,
|
||||
});
|
||||
tuples!(EitherOf9 + EitherOf9Future + EitherOf9FutureProj {
|
||||
A => (B, C, D, E, F, G, H, I) + <A1, B, C, D, E, F, G, H, I>,
|
||||
B => (A, C, D, E, F, G, H, I) + <A, B1, C, D, E, F, G, H, I>,
|
||||
C => (A, B, D, E, F, G, H, I) + <A, B, C1, D, E, F, G, H, I>,
|
||||
D => (A, B, C, E, F, G, H, I) + <A, B, C, D1, E, F, G, H, I>,
|
||||
E => (A, B, C, D, F, G, H, I) + <A, B, C, D, E1, F, G, H, I>,
|
||||
F => (A, B, C, D, E, G, H, I) + <A, B, C, D, E, F1, G, H, I>,
|
||||
G => (A, B, C, D, E, F, H, I) + <A, B, C, D, E, F, G1, H, I>,
|
||||
H => (A, B, C, D, E, F, G, I) + <A, B, C, D, E, F, G, H1, I>,
|
||||
I => (A, B, C, D, E, F, G, H) + <A, B, C, D, E, F, G, H, I1>,
|
||||
});
|
||||
tuples!(EitherOf10 + EitherOf10Future + EitherOf10FutureProj {
|
||||
A => (B, C, D, E, F, G, H, I, J) + <A1, B, C, D, E, F, G, H, I, J>,
|
||||
B => (A, C, D, E, F, G, H, I, J) + <A, B1, C, D, E, F, G, H, I, J>,
|
||||
C => (A, B, D, E, F, G, H, I, J) + <A, B, C1, D, E, F, G, H, I, J>,
|
||||
D => (A, B, C, E, F, G, H, I, J) + <A, B, C, D1, E, F, G, H, I, J>,
|
||||
E => (A, B, C, D, F, G, H, I, J) + <A, B, C, D, E1, F, G, H, I, J>,
|
||||
F => (A, B, C, D, E, G, H, I, J) + <A, B, C, D, E, F1, G, H, I, J>,
|
||||
G => (A, B, C, D, E, F, H, I, J) + <A, B, C, D, E, F, G1, H, I, J>,
|
||||
H => (A, B, C, D, E, F, G, I, J) + <A, B, C, D, E, F, G, H1, I, J>,
|
||||
I => (A, B, C, D, E, F, G, H, J) + <A, B, C, D, E, F, G, H, I1, J>,
|
||||
J => (A, B, C, D, E, F, G, H, I) + <A, B, C, D, E, F, G, H, I, J1>,
|
||||
});
|
||||
tuples!(EitherOf11 + EitherOf11Future + EitherOf11FutureProj {
|
||||
A => (B, C, D, E, F, G, H, I, J, K) + <A1, B, C, D, E, F, G, H, I, J, K>,
|
||||
B => (A, C, D, E, F, G, H, I, J, K) + <A, B1, C, D, E, F, G, H, I, J, K>,
|
||||
C => (A, B, D, E, F, G, H, I, J, K) + <A, B, C1, D, E, F, G, H, I, J, K>,
|
||||
D => (A, B, C, E, F, G, H, I, J, K) + <A, B, C, D1, E, F, G, H, I, J, K>,
|
||||
E => (A, B, C, D, F, G, H, I, J, K) + <A, B, C, D, E1, F, G, H, I, J, K>,
|
||||
F => (A, B, C, D, E, G, H, I, J, K) + <A, B, C, D, E, F1, G, H, I, J, K>,
|
||||
G => (A, B, C, D, E, F, H, I, J, K) + <A, B, C, D, E, F, G1, H, I, J, K>,
|
||||
H => (A, B, C, D, E, F, G, I, J, K) + <A, B, C, D, E, F, G, H1, I, J, K>,
|
||||
I => (A, B, C, D, E, F, G, H, J, K) + <A, B, C, D, E, F, G, H, I1, J, K>,
|
||||
J => (A, B, C, D, E, F, G, H, I, K) + <A, B, C, D, E, F, G, H, I, J1, K>,
|
||||
K => (A, B, C, D, E, F, G, H, I, J) + <A, B, C, D, E, F, G, H, I, J, K1>,
|
||||
});
|
||||
tuples!(EitherOf12 + EitherOf12Future + EitherOf12FutureProj {
|
||||
A => (B, C, D, E, F, G, H, I, J, K, L) + <A1, B, C, D, E, F, G, H, I, J, K, L>,
|
||||
B => (A, C, D, E, F, G, H, I, J, K, L) + <A, B1, C, D, E, F, G, H, I, J, K, L>,
|
||||
C => (A, B, D, E, F, G, H, I, J, K, L) + <A, B, C1, D, E, F, G, H, I, J, K, L>,
|
||||
D => (A, B, C, E, F, G, H, I, J, K, L) + <A, B, C, D1, E, F, G, H, I, J, K, L>,
|
||||
E => (A, B, C, D, F, G, H, I, J, K, L) + <A, B, C, D, E1, F, G, H, I, J, K, L>,
|
||||
F => (A, B, C, D, E, G, H, I, J, K, L) + <A, B, C, D, E, F1, G, H, I, J, K, L>,
|
||||
G => (A, B, C, D, E, F, H, I, J, K, L) + <A, B, C, D, E, F, G1, H, I, J, K, L>,
|
||||
H => (A, B, C, D, E, F, G, I, J, K, L) + <A, B, C, D, E, F, G, H1, I, J, K, L>,
|
||||
I => (A, B, C, D, E, F, G, H, J, K, L) + <A, B, C, D, E, F, G, H, I1, J, K, L>,
|
||||
J => (A, B, C, D, E, F, G, H, I, K, L) + <A, B, C, D, E, F, G, H, I, J1, K, L>,
|
||||
K => (A, B, C, D, E, F, G, H, I, J, L) + <A, B, C, D, E, F, G, H, I, J, K1, L>,
|
||||
L => (A, B, C, D, E, F, G, H, I, J, K) + <A, B, C, D, E, F, G, H, I, J, K, L1>,
|
||||
});
|
||||
tuples!(EitherOf13 + EitherOf13Future + EitherOf13FutureProj {
|
||||
A => (B, C, D, E, F, G, H, I, J, K, L, M) + <A1, B, C, D, E, F, G, H, I, J, K, L, M>,
|
||||
B => (A, C, D, E, F, G, H, I, J, K, L, M) + <A, B1, C, D, E, F, G, H, I, J, K, L, M>,
|
||||
C => (A, B, D, E, F, G, H, I, J, K, L, M) + <A, B, C1, D, E, F, G, H, I, J, K, L, M>,
|
||||
D => (A, B, C, E, F, G, H, I, J, K, L, M) + <A, B, C, D1, E, F, G, H, I, J, K, L, M>,
|
||||
E => (A, B, C, D, F, G, H, I, J, K, L, M) + <A, B, C, D, E1, F, G, H, I, J, K, L, M>,
|
||||
F => (A, B, C, D, E, G, H, I, J, K, L, M) + <A, B, C, D, E, F1, G, H, I, J, K, L, M>,
|
||||
G => (A, B, C, D, E, F, H, I, J, K, L, M) + <A, B, C, D, E, F, G1, H, I, J, K, L, M>,
|
||||
H => (A, B, C, D, E, F, G, I, J, K, L, M) + <A, B, C, D, E, F, G, H1, I, J, K, L, M>,
|
||||
I => (A, B, C, D, E, F, G, H, J, K, L, M) + <A, B, C, D, E, F, G, H, I1, J, K, L, M>,
|
||||
J => (A, B, C, D, E, F, G, H, I, K, L, M) + <A, B, C, D, E, F, G, H, I, J1, K, L, M>,
|
||||
K => (A, B, C, D, E, F, G, H, I, J, L, M) + <A, B, C, D, E, F, G, H, I, J, K1, L, M>,
|
||||
L => (A, B, C, D, E, F, G, H, I, J, K, M) + <A, B, C, D, E, F, G, H, I, J, K, L1, M>,
|
||||
M => (A, B, C, D, E, F, G, H, I, J, K, L) + <A, B, C, D, E, F, G, H, I, J, K, L, M1>,
|
||||
});
|
||||
tuples!(EitherOf14 + EitherOf14Future + EitherOf14FutureProj {
|
||||
A => (B, C, D, E, F, G, H, I, J, K, L, M, N) + <A1, B, C, D, E, F, G, H, I, J, K, L, M, N>,
|
||||
B => (A, C, D, E, F, G, H, I, J, K, L, M, N) + <A, B1, C, D, E, F, G, H, I, J, K, L, M, N>,
|
||||
C => (A, B, D, E, F, G, H, I, J, K, L, M, N) + <A, B, C1, D, E, F, G, H, I, J, K, L, M, N>,
|
||||
D => (A, B, C, E, F, G, H, I, J, K, L, M, N) + <A, B, C, D1, E, F, G, H, I, J, K, L, M, N>,
|
||||
E => (A, B, C, D, F, G, H, I, J, K, L, M, N) + <A, B, C, D, E1, F, G, H, I, J, K, L, M, N>,
|
||||
F => (A, B, C, D, E, G, H, I, J, K, L, M, N) + <A, B, C, D, E, F1, G, H, I, J, K, L, M, N>,
|
||||
G => (A, B, C, D, E, F, H, I, J, K, L, M, N) + <A, B, C, D, E, F, G1, H, I, J, K, L, M, N>,
|
||||
H => (A, B, C, D, E, F, G, I, J, K, L, M, N) + <A, B, C, D, E, F, G, H1, I, J, K, L, M, N>,
|
||||
I => (A, B, C, D, E, F, G, H, J, K, L, M, N) + <A, B, C, D, E, F, G, H, I1, J, K, L, M, N>,
|
||||
J => (A, B, C, D, E, F, G, H, I, K, L, M, N) + <A, B, C, D, E, F, G, H, I, J1, K, L, M, N>,
|
||||
K => (A, B, C, D, E, F, G, H, I, J, L, M, N) + <A, B, C, D, E, F, G, H, I, J, K1, L, M, N>,
|
||||
L => (A, B, C, D, E, F, G, H, I, J, K, M, N) + <A, B, C, D, E, F, G, H, I, J, K, L1, M, N>,
|
||||
M => (A, B, C, D, E, F, G, H, I, J, K, L, N) + <A, B, C, D, E, F, G, H, I, J, K, L, M1, N>,
|
||||
N => (A, B, C, D, E, F, G, H, I, J, K, L, M) + <A, B, C, D, E, F, G, H, I, J, K, L, M, N1>,
|
||||
});
|
||||
tuples!(EitherOf15 + EitherOf15Future + EitherOf15FutureProj {
|
||||
A => (B, C, D, E, F, G, H, I, J, K, L, M, N, O) + <A1, B, C, D, E, F, G, H, I, J, K, L, M, N, O>,
|
||||
B => (A, C, D, E, F, G, H, I, J, K, L, M, N, O) + <A, B1, C, D, E, F, G, H, I, J, K, L, M, N, O>,
|
||||
C => (A, B, D, E, F, G, H, I, J, K, L, M, N, O) + <A, B, C1, D, E, F, G, H, I, J, K, L, M, N, O>,
|
||||
D => (A, B, C, E, F, G, H, I, J, K, L, M, N, O) + <A, B, C, D1, E, F, G, H, I, J, K, L, M, N, O>,
|
||||
E => (A, B, C, D, F, G, H, I, J, K, L, M, N, O) + <A, B, C, D, E1, F, G, H, I, J, K, L, M, N, O>,
|
||||
F => (A, B, C, D, E, G, H, I, J, K, L, M, N, O) + <A, B, C, D, E, F1, G, H, I, J, K, L, M, N, O>,
|
||||
G => (A, B, C, D, E, F, H, I, J, K, L, M, N, O) + <A, B, C, D, E, F, G1, H, I, J, K, L, M, N, O>,
|
||||
H => (A, B, C, D, E, F, G, I, J, K, L, M, N, O) + <A, B, C, D, E, F, G, H1, I, J, K, L, M, N, O>,
|
||||
I => (A, B, C, D, E, F, G, H, J, K, L, M, N, O) + <A, B, C, D, E, F, G, H, I1, J, K, L, M, N, O>,
|
||||
J => (A, B, C, D, E, F, G, H, I, K, L, M, N, O) + <A, B, C, D, E, F, G, H, I, J1, K, L, M, N, O>,
|
||||
K => (A, B, C, D, E, F, G, H, I, J, L, M, N, O) + <A, B, C, D, E, F, G, H, I, J, K1, L, M, N, O>,
|
||||
L => (A, B, C, D, E, F, G, H, I, J, K, M, N, O) + <A, B, C, D, E, F, G, H, I, J, K, L1, M, N, O>,
|
||||
M => (A, B, C, D, E, F, G, H, I, J, K, L, N, O) + <A, B, C, D, E, F, G, H, I, J, K, L, M1, N, O>,
|
||||
N => (A, B, C, D, E, F, G, H, I, J, K, L, M, O) + <A, B, C, D, E, F, G, H, I, J, K, L, M, N1, O>,
|
||||
O => (A, B, C, D, E, F, G, H, I, J, K, L, M, N) + <A, B, C, D, E, F, G, H, I, J, K, L, M, N, O1>,
|
||||
});
|
||||
tuples!(EitherOf16 + EitherOf16Future + EitherOf16FutureProj {
|
||||
A => (B, C, D, E, F, G, H, I, J, K, L, M, N, O, P) + <A1, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P>,
|
||||
B => (A, C, D, E, F, G, H, I, J, K, L, M, N, O, P) + <A, B1, C, D, E, F, G, H, I, J, K, L, M, N, O, P>,
|
||||
C => (A, B, D, E, F, G, H, I, J, K, L, M, N, O, P) + <A, B, C1, D, E, F, G, H, I, J, K, L, M, N, O, P>,
|
||||
D => (A, B, C, E, F, G, H, I, J, K, L, M, N, O, P) + <A, B, C, D1, E, F, G, H, I, J, K, L, M, N, O, P>,
|
||||
E => (A, B, C, D, F, G, H, I, J, K, L, M, N, O, P) + <A, B, C, D, E1, F, G, H, I, J, K, L, M, N, O, P>,
|
||||
F => (A, B, C, D, E, G, H, I, J, K, L, M, N, O, P) + <A, B, C, D, E, F1, G, H, I, J, K, L, M, N, O, P>,
|
||||
G => (A, B, C, D, E, F, H, I, J, K, L, M, N, O, P) + <A, B, C, D, E, F, G1, H, I, J, K, L, M, N, O, P>,
|
||||
H => (A, B, C, D, E, F, G, I, J, K, L, M, N, O, P) + <A, B, C, D, E, F, G, H1, I, J, K, L, M, N, O, P>,
|
||||
I => (A, B, C, D, E, F, G, H, J, K, L, M, N, O, P) + <A, B, C, D, E, F, G, H, I1, J, K, L, M, N, O, P>,
|
||||
J => (A, B, C, D, E, F, G, H, I, K, L, M, N, O, P) + <A, B, C, D, E, F, G, H, I, J1, K, L, M, N, O, P>,
|
||||
K => (A, B, C, D, E, F, G, H, I, J, L, M, N, O, P) + <A, B, C, D, E, F, G, H, I, J, K1, L, M, N, O, P>,
|
||||
L => (A, B, C, D, E, F, G, H, I, J, K, M, N, O, P) + <A, B, C, D, E, F, G, H, I, J, K, L1, M, N, O, P>,
|
||||
M => (A, B, C, D, E, F, G, H, I, J, K, L, N, O, P) + <A, B, C, D, E, F, G, H, I, J, K, L, M1, N, O, P>,
|
||||
N => (A, B, C, D, E, F, G, H, I, J, K, L, M, O, P) + <A, B, C, D, E, F, G, H, I, J, K, L, M, N1, O, P>,
|
||||
O => (A, B, C, D, E, F, G, H, I, J, K, L, M, N, P) + <A, B, C, D, E, F, G, H, I, J, K, L, M, N, O1, P>,
|
||||
P => (A, B, C, D, E, F, G, H, I, J, K, L, M, N, O) + <A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P1>,
|
||||
});
|
||||
|
||||
/// Matches over the first expression and returns an either ([`Either`], [`EitherOf3`], ... [`EitherOf8`])
|
||||
/// composed of the values returned by the match arms.
|
||||
///
|
||||
/// The pattern syntax is exactly the same as found in a match arm.
|
||||
@@ -197,40 +815,93 @@ macro_rules! either {
|
||||
$e_pattern => $crate::EitherOf6::E($e_expression),
|
||||
$f_pattern => $crate::EitherOf6::F($f_expression),
|
||||
}
|
||||
};
|
||||
($match:expr, $a_pattern:pat => $a_expression:expr, $b_pattern:pat => $b_expression:expr, $c_pattern:pat => $c_expression:expr, $d_pattern:pat => $d_expression:expr, $e_pattern:pat => $e_expression:expr, $f_pattern:pat => $f_expression:expr, $g_pattern:pat => $g_expression:expr,) => {
|
||||
match $match {
|
||||
$a_pattern => $crate::EitherOf7::A($a_expression),
|
||||
$b_pattern => $crate::EitherOf7::B($b_expression),
|
||||
$c_pattern => $crate::EitherOf7::C($c_expression),
|
||||
$d_pattern => $crate::EitherOf7::D($d_expression),
|
||||
$e_pattern => $crate::EitherOf7::E($e_expression),
|
||||
$f_pattern => $crate::EitherOf7::F($f_expression),
|
||||
$g_pattern => $crate::EitherOf7::G($g_expression),
|
||||
}
|
||||
};
|
||||
($match:expr, $a_pattern:pat => $a_expression:expr, $b_pattern:pat => $b_expression:expr, $c_pattern:pat => $c_expression:expr, $d_pattern:pat => $d_expression:expr, $e_pattern:pat => $e_expression:expr, $f_pattern:pat => $f_expression:expr, $g_pattern:pat => $g_expression:expr, $h_pattern:pat => $h_expression:expr,) => {
|
||||
match $match {
|
||||
$a_pattern => $crate::EitherOf8::A($a_expression),
|
||||
$b_pattern => $crate::EitherOf8::B($b_expression),
|
||||
$c_pattern => $crate::EitherOf8::C($c_expression),
|
||||
$d_pattern => $crate::EitherOf8::D($d_expression),
|
||||
$e_pattern => $crate::EitherOf8::E($e_expression),
|
||||
$f_pattern => $crate::EitherOf8::F($f_expression),
|
||||
$g_pattern => $crate::EitherOf8::G($g_expression),
|
||||
$h_pattern => $crate::EitherOf8::H($h_expression),
|
||||
}
|
||||
}; // if you need more eithers feel free to open a PR ;-)
|
||||
}
|
||||
|
||||
// compile time test
|
||||
#[test]
|
||||
fn either_macro() {
|
||||
let _: Either<&str, f64> = either!(12,
|
||||
12 => "12",
|
||||
_ => 0.0,
|
||||
);
|
||||
let _: EitherOf3<&str, f64, i32> = either!(12,
|
||||
12 => "12",
|
||||
13 => 0.0,
|
||||
_ => 12,
|
||||
);
|
||||
let _: EitherOf4<&str, f64, char, i32> = either!(12,
|
||||
12 => "12",
|
||||
13 => 0.0,
|
||||
14 => ' ',
|
||||
_ => 12,
|
||||
);
|
||||
let _: EitherOf5<&str, f64, char, f32, i32> = either!(12,
|
||||
12 => "12",
|
||||
13 => 0.0,
|
||||
14 => ' ',
|
||||
15 => 0.0f32,
|
||||
_ => 12,
|
||||
);
|
||||
let _: EitherOf6<&str, f64, char, f32, u8, i32> = either!(12,
|
||||
12 => "12",
|
||||
13 => 0.0,
|
||||
14 => ' ',
|
||||
15 => 0.0f32,
|
||||
16 => 24u8,
|
||||
_ => 12,
|
||||
);
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
// compile time test
|
||||
#[test]
|
||||
fn either_macro() {
|
||||
let _: Either<&str, f64> = either!(12,
|
||||
12 => "12",
|
||||
_ => 0.0,
|
||||
);
|
||||
let _: EitherOf3<&str, f64, i32> = either!(12,
|
||||
12 => "12",
|
||||
13 => 0.0,
|
||||
_ => 12,
|
||||
);
|
||||
let _: EitherOf4<&str, f64, char, i32> = either!(12,
|
||||
12 => "12",
|
||||
13 => 0.0,
|
||||
14 => ' ',
|
||||
_ => 12,
|
||||
);
|
||||
let _: EitherOf5<&str, f64, char, f32, i32> = either!(12,
|
||||
12 => "12",
|
||||
13 => 0.0,
|
||||
14 => ' ',
|
||||
15 => 0.0f32,
|
||||
_ => 12,
|
||||
);
|
||||
let _: EitherOf6<&str, f64, char, f32, u8, i32> = either!(12,
|
||||
12 => "12",
|
||||
13 => 0.0,
|
||||
14 => ' ',
|
||||
15 => 0.0f32,
|
||||
16 => 24u8,
|
||||
_ => 12,
|
||||
);
|
||||
let _: EitherOf7<&str, f64, char, f32, u8, i8, i32> = either!(12,
|
||||
12 => "12",
|
||||
13 => 0.0,
|
||||
14 => ' ',
|
||||
15 => 0.0f32,
|
||||
16 => 24u8,
|
||||
17 => 2i8,
|
||||
_ => 12,
|
||||
);
|
||||
let _: EitherOf8<&str, f64, char, f32, u8, i8, u32, i32> = either!(12,
|
||||
12 => "12",
|
||||
13 => 0.0,
|
||||
14 => ' ',
|
||||
15 => 0.0f32,
|
||||
16 => 24u8,
|
||||
17 => 2i8,
|
||||
18 => 42u32,
|
||||
_ => 12,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic]
|
||||
fn unwrap_wrong_either() {
|
||||
Either::<i32, &str>::Left(0).unwrap_right();
|
||||
}
|
||||
}
|
||||
|
||||
2
examples/axum_js_ssr/node_modules/@highlightjs/cdn-assets/es/highlight.min.js
generated
vendored
2
examples/axum_js_ssr/node_modules/@highlightjs/cdn-assets/es/highlight.min.js
generated
vendored
@@ -1227,4 +1227,4 @@ begin:"\\b[0-9]{4}(-[0-9][0-9]){0,2}([Tt \\t][0-9][0-9]?(:[0-9][0-9]){2})?(\\.[0
|
||||
;return c.pop(),c.push(i),r.contains=c,{name:"YAML",case_insensitive:!0,
|
||||
aliases:["yml"],contains:l}}});const Ke=te;for(const e of Object.keys(Pe)){
|
||||
const n=e.replace("grmr_","").replace("_","-");Ke.registerLanguage(n,Pe[e])}
|
||||
export{Ke as default};
|
||||
export{Ke as defaultMod};
|
||||
|
||||
@@ -13,13 +13,13 @@ mod csr {
|
||||
extern "C" {
|
||||
type HighlightOptions;
|
||||
|
||||
#[wasm_bindgen(catch, js_namespace = default, js_name = highlight)]
|
||||
#[wasm_bindgen(catch, js_namespace = defaultMod, js_name = highlight)]
|
||||
fn highlight_lang(
|
||||
code: String,
|
||||
options: Object,
|
||||
) -> Result<Object, JsValue>;
|
||||
|
||||
#[wasm_bindgen(js_namespace = default, js_name = highlightAll)]
|
||||
#[wasm_bindgen(js_namespace = defaultMod, js_name = highlightAll)]
|
||||
pub fn highlight_all();
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
[tasks.install-cargo-leptos]
|
||||
install_crate = { crate_name = "cargo-leptos", binary = "cargo-leptos", test_arg = "--help" }
|
||||
args = ["--locked"]
|
||||
|
||||
[tasks.cargo-leptos-e2e]
|
||||
command = "cargo"
|
||||
|
||||
@@ -12,7 +12,7 @@ lto = true
|
||||
|
||||
[dependencies]
|
||||
console_error_panic_hook = "0.1.7"
|
||||
leptos = { path = "../../leptos", features = ["experimental-islands"] }
|
||||
leptos = { path = "../../leptos", features = ["islands"] }
|
||||
leptos_axum = { path = "../../integrations/axum", optional = true }
|
||||
leptos_meta = { path = "../../meta" }
|
||||
leptos_router = { path = "../../router" }
|
||||
|
||||
@@ -12,7 +12,7 @@ futures = "0.3.30"
|
||||
http = "1.1"
|
||||
leptos = { path = "../../leptos", features = [
|
||||
"tracing",
|
||||
"experimental-islands",
|
||||
"islands",
|
||||
] }
|
||||
server_fn = { path = "../../server_fn", features = ["serde-lite"] }
|
||||
leptos_axum = { path = "../../integrations/axum", optional = true }
|
||||
|
||||
@@ -12,7 +12,7 @@ futures = "0.3.30"
|
||||
http = "1.1"
|
||||
leptos = { path = "../../leptos", features = [
|
||||
"tracing",
|
||||
"experimental-islands",
|
||||
"islands",
|
||||
] }
|
||||
leptos_router = { path = "../../router" }
|
||||
server_fn = { path = "../../server_fn", features = ["serde-lite"] }
|
||||
|
||||
@@ -10,7 +10,7 @@ crate-type = ["cdylib", "rlib"]
|
||||
actix-files = { version = "0.6.6", optional = true }
|
||||
actix-web = { version = "4.8", optional = true, features = ["macros"] }
|
||||
console_error_panic_hook = "0.1.7"
|
||||
js-sys = { version = "0.3.70", optional = true }
|
||||
js-sys = { version = "0.3.72" }
|
||||
leptos = { path = "../../leptos" }
|
||||
leptos_actix = { path = "../../integrations/actix", optional = true }
|
||||
leptos_router = { path = "../../router" }
|
||||
@@ -21,7 +21,7 @@ tokio = { version = "1.39", features = ["time", "rt"], optional = true }
|
||||
|
||||
[features]
|
||||
hydrate = [
|
||||
"dep:js-sys",
|
||||
|
||||
"leptos/hydrate",
|
||||
]
|
||||
ssr = [
|
||||
|
||||
121
examples/suspense_tests/e2e/features/check_aria_current.feature
Normal file
121
examples/suspense_tests/e2e/features/check_aria_current.feature
Normal file
@@ -0,0 +1,121 @@
|
||||
@check_aria_current
|
||||
Feature: Check aria-current being applied to make links bolded
|
||||
|
||||
Background:
|
||||
|
||||
Given I see the app
|
||||
|
||||
Scenario: Should see the base case working
|
||||
Then I see the Out-of-Order link being bolded
|
||||
And I see the following links being bolded
|
||||
| Out-of-Order |
|
||||
| Nested |
|
||||
And I see the In-Order link not being bolded
|
||||
And I see the following links not being bolded
|
||||
| In-Order |
|
||||
| Single |
|
||||
|
||||
Scenario: Should see client-side render the correct bolded links
|
||||
When I select the link In-Order
|
||||
And I select the link Single
|
||||
Then I see the following links being bolded
|
||||
| In-Order |
|
||||
| Single |
|
||||
And I see the following links not being bolded
|
||||
| Out-of-Order |
|
||||
| Nested |
|
||||
|
||||
Scenario: Should see server-side render the correct bolded links
|
||||
When I select the link In-Order
|
||||
And I select the link Single
|
||||
And I reload the page
|
||||
Then I see the following links being bolded
|
||||
| In-Order |
|
||||
| Single |
|
||||
And I see the following links not being bolded
|
||||
| Out-of-Order |
|
||||
| Nested |
|
||||
|
||||
Scenario: Check that the base nested route links are working
|
||||
When I select the link Instrumented
|
||||
Then I see the Instrumented link being bolded
|
||||
And I see the Item Listing link not being bolded
|
||||
|
||||
Scenario: Should see going deep down into nested routes bold links
|
||||
When I select the link Instrumented
|
||||
And I select the link Target 421
|
||||
Then I see the following links being bolded
|
||||
| Instrumented |
|
||||
| Item Listing |
|
||||
| Target 4## |
|
||||
| Target 42# |
|
||||
| Target 421 |
|
||||
| field1 |
|
||||
|
||||
Scenario: Should see going deep down into nested routes in SSR bold links
|
||||
When I select the link Instrumented
|
||||
And I select the link Target 421
|
||||
And I reload the page
|
||||
Then I see the following links being bolded
|
||||
| Instrumented |
|
||||
| Item Listing |
|
||||
| Target 4## |
|
||||
| Target 42# |
|
||||
| Target 421 |
|
||||
| field1 |
|
||||
|
||||
Scenario: Going deep down navigate around nested links bold correctly
|
||||
When I select the link Instrumented
|
||||
And I select the link Target 421
|
||||
And I select the link Inspect path2/field3
|
||||
Then I see the following links being bolded
|
||||
| Instrumented |
|
||||
| Item Listing |
|
||||
| Target 4## |
|
||||
| Target 42# |
|
||||
| field3 |
|
||||
And I see the following links not being bolded
|
||||
| Target 421 |
|
||||
| field1 |
|
||||
|
||||
Scenario: Going deep down navigate around nested links bold correctly, SSR
|
||||
When I select the link Instrumented
|
||||
And I select the link Target 421
|
||||
And I select the link Inspect path2/field3
|
||||
And I reload the page
|
||||
Then I see the following links being bolded
|
||||
| Instrumented |
|
||||
| Item Listing |
|
||||
| Target 4## |
|
||||
| Target 42# |
|
||||
| field3 |
|
||||
And I see the following links not being bolded
|
||||
| Target 421 |
|
||||
| field1 |
|
||||
|
||||
Scenario: Going deep down back out nested routes reset bolded states
|
||||
When I select the link Instrumented
|
||||
And I select the link Target 421
|
||||
And I select the link Counters
|
||||
Then I see the following links being bolded
|
||||
| Instrumented |
|
||||
| Counters |
|
||||
And I see the following links not being bolded
|
||||
| Item Listing |
|
||||
| Target 4## |
|
||||
| Target 42# |
|
||||
| Target 421 |
|
||||
|
||||
Scenario: Going deep down back out nested routes reset bolded states, SSR
|
||||
When I select the link Instrumented
|
||||
And I select the link Target 421
|
||||
And I select the link Counters
|
||||
And I reload the page
|
||||
Then I see the following links being bolded
|
||||
| Instrumented |
|
||||
| Counters |
|
||||
And I see the following links not being bolded
|
||||
| Item Listing |
|
||||
| Target 4## |
|
||||
| Target 42# |
|
||||
| Target 421 |
|
||||
@@ -81,3 +81,20 @@ pub async fn instrumented_counts(
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn link_text_is_aria_current(client: &Client, text: &str) -> Result<()> {
|
||||
let link = find::link_with_text(client, text).await?;
|
||||
|
||||
link.attr("aria-current").await?
|
||||
.expect(format!("aria-current missing for {text}").as_str());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn link_text_is_not_aria_current(client: &Client, text: &str) -> Result<()> {
|
||||
let link = find::link_with_text(client, text).await?;
|
||||
|
||||
link.attr("aria-current").await?
|
||||
.map(|_| anyhow::bail!("aria-current mistakenly set for {text}"))
|
||||
.unwrap_or(Ok(()))
|
||||
}
|
||||
|
||||
@@ -124,3 +124,12 @@ async fn component_message(client: &Client, id: &str) -> Result<String> {
|
||||
|
||||
Ok(text)
|
||||
}
|
||||
|
||||
pub async fn link_with_text(client: &Client, text: &str) -> Result<Element> {
|
||||
let link = client
|
||||
.wait()
|
||||
.for_element(Locator::LinkText(text))
|
||||
.await
|
||||
.expect(format!("Link not found by `{}`", text).as_str());
|
||||
Ok(link)
|
||||
}
|
||||
|
||||
@@ -80,6 +80,58 @@ async fn i_see_the_second_count_is(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[then(regex = r"^I see the (.*) link being bolded$")]
|
||||
async fn i_see_the_link_being_bolded(
|
||||
world: &mut AppWorld,
|
||||
text: String,
|
||||
) -> Result<()> {
|
||||
let client = &world.client;
|
||||
check::link_text_is_aria_current(client, &text).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[then(expr = "I see the following links being bolded")]
|
||||
async fn i_see_the_following_links_being_bolded(
|
||||
world: &mut AppWorld,
|
||||
step: &Step,
|
||||
) -> Result<()> {
|
||||
let client = &world.client;
|
||||
if let Some(table) = step.table.as_ref() {
|
||||
for row in table.rows.iter() {
|
||||
check::link_text_is_aria_current(client, &row[0]).await?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[then(regex = r"^I see the (.*) link not being bolded$")]
|
||||
async fn i_see_the_link_being_not_bolded(
|
||||
world: &mut AppWorld,
|
||||
text: String,
|
||||
) -> Result<()> {
|
||||
let client = &world.client;
|
||||
check::link_text_is_not_aria_current(client, &text).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[then(expr = "I see the following links not being bolded")]
|
||||
async fn i_see_the_following_links_not_being_bolded(
|
||||
world: &mut AppWorld,
|
||||
step: &Step,
|
||||
) -> Result<()> {
|
||||
let client = &world.client;
|
||||
if let Some(table) = step.table.as_ref() {
|
||||
for row in table.rows.iter() {
|
||||
check::link_text_is_not_aria_current(client, &row[0]).await?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[then(expr = "I see the following counters under section")]
|
||||
#[then(expr = "the following counters under section")]
|
||||
async fn i_see_the_following_counters_under_section(
|
||||
|
||||
@@ -4,25 +4,6 @@ use leptos::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use server_fn::ServerFnError;
|
||||
|
||||
pub fn shell(leptos_options: &LeptosOptions) -> impl IntoView {
|
||||
view! {
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8"/>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1"/>
|
||||
<AutoReload options=leptos_options.clone() />
|
||||
<HydrationScripts options=leptos_options.clone()/>
|
||||
<link rel="stylesheet" id="leptos" href="/pkg/todo_app_sqlite_csr.css"/>
|
||||
<link rel="shortcut icon" type="image/ico" href="/favicon.ico"/>
|
||||
</head>
|
||||
<body>
|
||||
<TodoApp/>
|
||||
</body>
|
||||
</html>
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[cfg_attr(feature = "ssr", derive(sqlx::FromRow))]
|
||||
pub struct Todo {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "hydration_context"
|
||||
version = "0.2.0-rc1"
|
||||
version = "0.2.1"
|
||||
authors = ["Greg Johnston"]
|
||||
license = "MIT"
|
||||
readme = "../README.md"
|
||||
@@ -14,8 +14,8 @@ throw_error = { workspace = true }
|
||||
or_poisoned = { workspace = true }
|
||||
futures = "0.3.31"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
wasm-bindgen = { version = "0.2.95", optional = true }
|
||||
js-sys = { version = "0.3.72", optional = true }
|
||||
wasm-bindgen = { version = "0.2.97", optional = true }
|
||||
js-sys = { version = "0.3.74", optional = true }
|
||||
once_cell = "1.20"
|
||||
pin-project-lite = "0.2.15"
|
||||
|
||||
@@ -25,3 +25,6 @@ browser = ["dep:wasm-bindgen", "dep:js-sys"]
|
||||
[package.metadata.docs.rs]
|
||||
all-features = true
|
||||
rustdoc-args = ["--cfg", "docsrs"]
|
||||
|
||||
[lints.rust]
|
||||
unexpected_cfgs = { level = "warn", check-cfg = ['cfg(leptos_debuginfo)'] }
|
||||
|
||||
@@ -1,3 +1,8 @@
|
||||
// #[wasm_bindgen(thread_local)] is deprecated in wasm-bindgen 0.2.96
|
||||
// but the replacement is also only shipped in that version
|
||||
// as a result, we'll just allow deprecated for now
|
||||
#![allow(deprecated)]
|
||||
|
||||
use super::{SerializedDataId, SharedContext};
|
||||
use crate::{PinnedFuture, PinnedStream};
|
||||
use core::fmt::Debug;
|
||||
|
||||
@@ -83,15 +83,14 @@ pub trait SharedContext: Debug {
|
||||
|
||||
/// Reads the current value of some data from the shared context, if it has been
|
||||
/// sent from the server. This returns the serialized data as a `String` that should
|
||||
/// be deserialized using [`Serializable::de`].
|
||||
/// be deserialized.
|
||||
///
|
||||
/// On the server and in client-side rendered implementations, this should
|
||||
/// always return [`None`].
|
||||
fn read_data(&self, id: &SerializedDataId) -> Option<String>;
|
||||
|
||||
/// Returns a [`Future`] that resolves with a `String` that should
|
||||
/// be deserialized using [`Serializable::de`] once the given piece of server
|
||||
/// data has resolved.
|
||||
/// be deserialized once the given piece of server data has resolved.
|
||||
///
|
||||
/// On the server and in client-side rendered implementations, this should
|
||||
/// return a [`Future`] that is immediately ready with [`None`].
|
||||
@@ -148,8 +147,8 @@ pub trait SharedContext: Debug {
|
||||
|
||||
/// Adds a `Future` to the set of “blocking resources” that should prevent the server’s
|
||||
/// response stream from beginning until all are resolved. The `Future` returned by
|
||||
/// [`blocking_resources`](Self::blocking_resources) will not resolve until every `Future`
|
||||
/// added by this method has resolved.
|
||||
/// blocking resources will not resolve until every `Future` added by this method
|
||||
/// has resolved.
|
||||
///
|
||||
/// In browser implementations, this should be a no-op.
|
||||
fn defer_stream(&self, wait_for: PinnedFuture<()>);
|
||||
|
||||
@@ -18,7 +18,7 @@ hydration_context = { workspace = true }
|
||||
leptos = { workspace = true, features = ["nonce", "ssr"] }
|
||||
leptos_integration_utils = { workspace = true }
|
||||
leptos_macro = { workspace = true, features = ["actix"] }
|
||||
leptos_meta = { workspace = true }
|
||||
leptos_meta = { workspace = true, features = ["nonce"] }
|
||||
leptos_router = { workspace = true, features = ["ssr"] }
|
||||
server_fn = { workspace = true, features = ["actix"] }
|
||||
serde_json = "1.0"
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
#![forbid(unsafe_code)]
|
||||
#![deny(missing_docs)]
|
||||
|
||||
//! Provides functions to easily integrate Leptos with Actix.
|
||||
//!
|
||||
@@ -9,7 +10,6 @@
|
||||
use actix_files::NamedFile;
|
||||
use actix_http::header::{HeaderName, HeaderValue, ACCEPT, LOCATION, REFERER};
|
||||
use actix_web::{
|
||||
body::BoxBody,
|
||||
dev::{ServiceFactory, ServiceRequest},
|
||||
http::header,
|
||||
test,
|
||||
@@ -56,8 +56,10 @@ use std::{
|
||||
/// Typically contained inside of a ResponseOptions. Setting this is useful for cookies and custom responses.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct ResponseParts {
|
||||
pub headers: header::HeaderMap,
|
||||
/// If provided, this will overwrite any other status code for this response.
|
||||
pub status: Option<StatusCode>,
|
||||
/// The map of headers that should be added to the response.
|
||||
pub headers: header::HeaderMap,
|
||||
}
|
||||
|
||||
impl ResponseParts {
|
||||
@@ -80,16 +82,18 @@ impl ResponseParts {
|
||||
}
|
||||
}
|
||||
|
||||
/// A wrapper for an Actix [`HttpRequest`](actix_web::HttpRequest) that allows it to be used in an
|
||||
/// A wrapper for an Actix [`HttpRequest`] that allows it to be used in an
|
||||
/// `Send`/`Sync` setting like Leptos's Context API.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Request(SendWrapper<HttpRequest>);
|
||||
|
||||
impl Request {
|
||||
/// Wraps an existing Actix request.
|
||||
pub fn new(req: &HttpRequest) -> Self {
|
||||
Self(SendWrapper::new(req.clone()))
|
||||
}
|
||||
|
||||
/// Consumes the wrapper and returns the inner Actix request.
|
||||
pub fn into_inner(self) -> HttpRequest {
|
||||
self.0.take()
|
||||
}
|
||||
@@ -299,7 +303,7 @@ pub fn redirect(path: &str) {
|
||||
/// ## Provided Context Types
|
||||
/// This function always provides context values including the following types:
|
||||
/// - [ResponseOptions]
|
||||
/// - [HttpRequest](actix_web::HttpRequest)
|
||||
/// - [Request]
|
||||
#[cfg_attr(
|
||||
feature = "tracing",
|
||||
tracing::instrument(level = "trace", fields(error), skip_all)
|
||||
@@ -326,7 +330,7 @@ pub fn handle_server_fns() -> Route {
|
||||
/// ## Provided Context Types
|
||||
/// This function always provides context values including the following types:
|
||||
/// - [ResponseOptions]
|
||||
/// - [HttpRequest](actix_web::HttpRequest)
|
||||
/// - [Request]
|
||||
#[cfg_attr(
|
||||
feature = "tracing",
|
||||
tracing::instrument(level = "trace", fields(error), skip_all)
|
||||
@@ -371,8 +375,8 @@ pub fn handle_server_fns_with_context(
|
||||
.take(),
|
||||
);
|
||||
|
||||
// it it accepts text/html (i.e., is a plain form post) and doesn't already have a
|
||||
// Location set, then redirect to to Referer
|
||||
// if it accepts text/html (i.e., is a plain form post) and doesn't already have a
|
||||
// Location set, then redirect to the Referer
|
||||
if accepts_html {
|
||||
if let Some(referrer) = referrer {
|
||||
let has_location =
|
||||
@@ -386,7 +390,20 @@ pub fn handle_server_fns_with_context(
|
||||
}
|
||||
}
|
||||
|
||||
// apply status code and headers if used changed them
|
||||
// the Location header may have been set to Referer, so any redirection by the
|
||||
// user must overwrite it
|
||||
{
|
||||
let mut res_options = res_options.0.write();
|
||||
let headers = res.0.headers_mut();
|
||||
|
||||
for location in
|
||||
res_options.headers.remove(header::LOCATION)
|
||||
{
|
||||
headers.insert(header::LOCATION, location);
|
||||
}
|
||||
}
|
||||
|
||||
// apply status code and headers if user changed them
|
||||
res.extend_response(&res_options);
|
||||
res.0
|
||||
})
|
||||
@@ -415,12 +432,6 @@ pub fn handle_server_fns_with_context(
|
||||
/// will include fallback content for any `<Suspense/>` nodes, and be immediately interactive,
|
||||
/// but requires some client-side JavaScript.
|
||||
///
|
||||
/// The provides a [MetaContext] and a [RouterIntegrationContext] to app’s context before
|
||||
/// rendering it, and includes any meta tags injected using [leptos_meta].
|
||||
///
|
||||
/// The HTML stream is rendered using [render_to_stream](leptos::ssr::render_to_stream), and
|
||||
/// includes everything described in the documentation for that function.
|
||||
///
|
||||
/// This can then be set up at an appropriate route in your application:
|
||||
/// ```
|
||||
/// use actix_web::{App, HttpServer};
|
||||
@@ -459,9 +470,8 @@ pub fn handle_server_fns_with_context(
|
||||
/// ## Provided Context Types
|
||||
/// This function always provides context values including the following types:
|
||||
/// - [ResponseOptions]
|
||||
/// - [HttpRequest](actix_web::HttpRequest)
|
||||
/// - [Request]
|
||||
/// - [MetaContext](leptos_meta::MetaContext)
|
||||
/// - [RouterIntegrationContext](leptos_router::RouterIntegrationContext)
|
||||
#[cfg_attr(
|
||||
feature = "tracing",
|
||||
tracing::instrument(level = "trace", fields(error), skip_all)
|
||||
@@ -481,13 +491,6 @@ where
|
||||
/// This stream will pause at each `<Suspense/>` node and wait for it to resolve before
|
||||
/// sending down its HTML. The app will become interactive once it has fully loaded.
|
||||
///
|
||||
/// The provides a [MetaContext] and a [RouterIntegrationContext] to app’s context before
|
||||
/// rendering it, and includes any meta tags injected using [leptos_meta].
|
||||
///
|
||||
/// The HTML stream is rendered using
|
||||
/// [render_to_stream_in_order](leptos::ssr::render_to_stream_in_order),
|
||||
/// and includes everything described in the documentation for that function.
|
||||
///
|
||||
/// This can then be set up at an appropriate route in your application:
|
||||
/// ```
|
||||
/// use actix_web::{App, HttpServer};
|
||||
@@ -529,9 +532,7 @@ where
|
||||
/// ## Provided Context Types
|
||||
/// This function always provides context values including the following types:
|
||||
/// - [ResponseOptions]
|
||||
/// - [HttpRequest](actix_web::HttpRequest)
|
||||
/// - [MetaContext](leptos_meta::MetaContext)
|
||||
/// - [RouterIntegrationContext](leptos_router::RouterIntegrationContext)
|
||||
/// - [Request]
|
||||
#[cfg_attr(
|
||||
feature = "tracing",
|
||||
tracing::instrument(level = "trace", fields(error), skip_all)
|
||||
@@ -548,13 +549,7 @@ where
|
||||
|
||||
/// Returns an Actix [struct@Route](actix_web::Route) that listens for a `GET` request and tries
|
||||
/// to route it using [leptos_router], asynchronously rendering an HTML page after all
|
||||
/// `async` [Resource](leptos::Resource)s have loaded.
|
||||
///
|
||||
/// The provides a [MetaContext] and a [RouterIntegrationContext] to the app’s context before
|
||||
/// rendering it, and includes any meta tags injected using [leptos_meta].
|
||||
///
|
||||
/// The HTML stream is rendered using [render_to_string_async](leptos::ssr::render_to_string_async), and
|
||||
/// includes everything described in the documentation for that function.
|
||||
/// `async` resources have loaded.
|
||||
///
|
||||
/// This can then be set up at an appropriate route in your application:
|
||||
/// ```
|
||||
@@ -594,9 +589,7 @@ where
|
||||
/// ## Provided Context Types
|
||||
/// This function always provides context values including the following types:
|
||||
/// - [ResponseOptions]
|
||||
/// - [HttpRequest](actix_web::HttpRequest)
|
||||
/// - [MetaContext](leptos_meta::MetaContext)
|
||||
/// - [RouterIntegrationContext](leptos_router::RouterIntegrationContext)
|
||||
/// - [Request]
|
||||
#[cfg_attr(
|
||||
feature = "tracing",
|
||||
tracing::instrument(level = "trace", fields(error), skip_all)
|
||||
@@ -620,9 +613,7 @@ where
|
||||
/// ## Provided Context Types
|
||||
/// This function always provides context values including the following types:
|
||||
/// - [ResponseOptions]
|
||||
/// - [HttpRequest](actix_web::HttpRequest)
|
||||
/// - [MetaContext](leptos_meta::MetaContext)
|
||||
/// - [RouterIntegrationContext](leptos_router::RouterIntegrationContext)
|
||||
/// - [Request]
|
||||
#[cfg_attr(
|
||||
feature = "tracing",
|
||||
tracing::instrument(level = "trace", fields(error), skip_all)
|
||||
@@ -657,9 +648,7 @@ where
|
||||
/// ## Provided Context Types
|
||||
/// This function always provides context values including the following types:
|
||||
/// - [ResponseOptions]
|
||||
/// - [HttpRequest](actix_web::HttpRequest)
|
||||
/// - [MetaContext](leptos_meta::MetaContext)
|
||||
/// - [RouterIntegrationContext](leptos_router::RouterIntegrationContext)
|
||||
/// - [Request]
|
||||
#[cfg_attr(
|
||||
feature = "tracing",
|
||||
tracing::instrument(level = "trace", fields(error), skip_all)
|
||||
@@ -691,9 +680,8 @@ where
|
||||
/// ## Provided Context Types
|
||||
/// This function always provides context values including the following types:
|
||||
/// - [ResponseOptions]
|
||||
/// - [HttpRequest](actix_web::HttpRequest)
|
||||
/// - [Request]
|
||||
/// - [MetaContext](leptos_meta::MetaContext)
|
||||
/// - [RouterIntegrationContext](leptos_router::RouterIntegrationContext)
|
||||
#[cfg_attr(
|
||||
feature = "tracing",
|
||||
tracing::instrument(level = "trace", fields(error), skip_all)
|
||||
@@ -716,7 +704,7 @@ where
|
||||
|
||||
/// Returns an Actix [struct@Route](actix_web::Route) that listens for a `GET` request and tries
|
||||
/// to route it using [leptos_router], asynchronously serving the page once all `async`
|
||||
/// [Resource](leptos::Resource)s have loaded.
|
||||
/// resources have loaded.
|
||||
///
|
||||
/// This function allows you to provide additional information to Leptos for your route.
|
||||
/// It could be used to pass in Path Info, Connection Info, or anything your heart desires.
|
||||
@@ -724,9 +712,7 @@ where
|
||||
/// ## Provided Context Types
|
||||
/// This function always provides context values including the following types:
|
||||
/// - [ResponseOptions]
|
||||
/// - [HttpRequest](actix_web::HttpRequest)
|
||||
/// - [MetaContext](leptos_meta::MetaContext)
|
||||
/// - [RouterIntegrationContext](leptos_router::RouterIntegrationContext)
|
||||
/// - [Request]
|
||||
#[cfg_attr(
|
||||
feature = "tracing",
|
||||
tracing::instrument(level = "trace", fields(error), skip_all)
|
||||
@@ -1319,14 +1305,12 @@ where
|
||||
web::get().to(handler)
|
||||
}
|
||||
|
||||
pub enum DataResponse<T> {
|
||||
Data(T),
|
||||
Response(actix_web::dev::Response<BoxBody>),
|
||||
}
|
||||
|
||||
/// This trait allows one to pass a list of routes and a render function to Actix's router, letting us avoid
|
||||
/// having to use wildcards or manually define all routes in multiple places.
|
||||
pub trait LeptosRoutes {
|
||||
/// Adds routes to the Axum router that have either
|
||||
/// 1) been generated by `leptos_router`, or
|
||||
/// 2) handle a server function.
|
||||
fn leptos_routes<IV>(
|
||||
self,
|
||||
paths: Vec<ActixRouteListing>,
|
||||
@@ -1335,6 +1319,12 @@ pub trait LeptosRoutes {
|
||||
where
|
||||
IV: IntoView + 'static;
|
||||
|
||||
/// Adds routes to the Axum router that have either
|
||||
/// 1) been generated by `leptos_router`, or
|
||||
/// 2) handle a server function.
|
||||
///
|
||||
/// Runs `additional_context` to provide additional data to the reactive system via context,
|
||||
/// when handling a route.
|
||||
fn leptos_routes_with_context<IV>(
|
||||
self,
|
||||
paths: Vec<ActixRouteListing>,
|
||||
|
||||
@@ -11,7 +11,7 @@ edition.workspace = true
|
||||
[dependencies]
|
||||
any_spawner = { workspace = true, features = ["tokio"] }
|
||||
hydration_context = { workspace = true }
|
||||
axum = { version = "0.7.7", default-features = false, features = [
|
||||
axum = { version = "0.7.9", default-features = false, features = [
|
||||
"matched-path",
|
||||
] }
|
||||
dashmap = "6"
|
||||
@@ -19,18 +19,18 @@ futures = "0.3.31"
|
||||
leptos = { workspace = true, features = ["nonce", "ssr"] }
|
||||
server_fn = { workspace = true, features = ["axum-no-default"] }
|
||||
leptos_macro = { workspace = true, features = ["axum"] }
|
||||
leptos_meta = { workspace = true, features = ["ssr"] }
|
||||
leptos_meta = { workspace = true, features = ["ssr", "nonce"] }
|
||||
leptos_router = { workspace = true, features = ["ssr"] }
|
||||
leptos_integration_utils = { workspace = true }
|
||||
once_cell = "1"
|
||||
parking_lot = "0.12.3"
|
||||
tokio = { version = "1.41", default-features = false }
|
||||
tower = { version = "0.5.1", features = ["util"] }
|
||||
tower-http = "0.6.1"
|
||||
tracing = { version = "0.1.40", optional = true }
|
||||
tower-http = "0.6.2"
|
||||
tracing = { version = "0.1.41", optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
axum = "0.7.7"
|
||||
axum = "0.7.9"
|
||||
tokio = { version = "1.41", features = ["net", "rt-multi-thread"] }
|
||||
|
||||
[features]
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
#![forbid(unsafe_code)]
|
||||
#![deny(missing_docs)]
|
||||
|
||||
//! Provides functions to easily integrate Leptos with Axum.
|
||||
//!
|
||||
//! ## JS Fetch Integration
|
||||
@@ -14,7 +16,6 @@
|
||||
//! - `default`: supports running in a typical native Tokio/Axum environment
|
||||
//! - `wasm`: with `default-features = false`, supports running in a JS Fetch-based
|
||||
//! environment
|
||||
//! - `experimental-islands`: activates Leptos [islands mode](https://leptos-rs.github.io/leptos/islands.html)
|
||||
//!
|
||||
//! ### Important Note
|
||||
//! Prior to 0.5, using `default-features = false` on `leptos_axum` simply did nothing. Now, it actively
|
||||
@@ -84,7 +85,9 @@ use tower_http::services::ServeDir;
|
||||
/// Typically contained inside of a ResponseOptions. Setting this is useful for cookies and custom responses.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct ResponseParts {
|
||||
/// If provided, this will overwrite any other status code for this response.
|
||||
pub status: Option<StatusCode>,
|
||||
/// The map of headers that should be added to the response.
|
||||
pub headers: HeaderMap,
|
||||
}
|
||||
|
||||
@@ -193,9 +196,9 @@ impl ExtendResponse for AxumResponse {
|
||||
/// 2. A server function that is called from WASM running in the client (e.g., a dispatched action
|
||||
/// or a spawned `Future`).
|
||||
/// 3. A `<form>` submitted to the server function endpoint using default browser APIs (often due
|
||||
/// to using [`ActionForm`](leptos::form::ActionForm) without JS/WASM present.)
|
||||
/// to using [`ActionForm`] without JS/WASM present.)
|
||||
///
|
||||
/// Using it with a non-blocking [`Resource`](leptos::server::Resource) will not work if you are using streaming rendering,
|
||||
/// Using it with a non-blocking [`Resource`] will not work if you are using streaming rendering,
|
||||
/// as the response's headers will already have been sent by the time the server function calls `redirect()`.
|
||||
///
|
||||
/// ### Implementation
|
||||
@@ -395,8 +398,8 @@ async fn handle_server_fns_inner(
|
||||
// actually run the server fn
|
||||
let mut res = AxumResponse(service.run(req).await);
|
||||
|
||||
// it it accepts text/html (i.e., is a plain form post) and doesn't already have a
|
||||
// Location set, then redirect to to Referer
|
||||
// if it accepts text/html (i.e., is a plain form post) and doesn't already have a
|
||||
// Location set, then redirect to the Referer
|
||||
if accepts_html {
|
||||
if let Some(referrer) = referrer {
|
||||
let has_location =
|
||||
@@ -408,7 +411,7 @@ async fn handle_server_fns_inner(
|
||||
}
|
||||
}
|
||||
|
||||
// apply status code and headers if used changed them
|
||||
// apply status code and headers if user changed them
|
||||
res.extend_response(&res_options);
|
||||
Ok(res.0)
|
||||
})
|
||||
@@ -431,18 +434,13 @@ async fn handle_server_fns_inner(
|
||||
.expect("could not build Response")
|
||||
}
|
||||
|
||||
/// A stream of bytes of HTML.
|
||||
pub type PinnedHtmlStream =
|
||||
Pin<Box<dyn Stream<Item = io::Result<Bytes>> + Send>>;
|
||||
|
||||
/// Returns an Axum [Handler](axum::handler::Handler) that listens for a `GET` request and tries
|
||||
/// to route it using [leptos_router], serving an HTML stream of your application.
|
||||
///
|
||||
/// The provides a [MetaContext] and a [RouterIntegrationContext] to app’s context before
|
||||
/// rendering it, and includes any meta tags injected using [leptos_meta].
|
||||
///
|
||||
/// The HTML stream is rendered using [render_to_stream](leptos::ssr::render_to_stream), and
|
||||
/// includes everything described in the documentation for that function.
|
||||
///
|
||||
/// This can then be set up at an appropriate route in your application:
|
||||
/// ```
|
||||
/// use axum::{handler::Handler, Router};
|
||||
@@ -480,8 +478,7 @@ pub type PinnedHtmlStream =
|
||||
/// This function always provides context values including the following types:
|
||||
/// - [`Parts`]
|
||||
/// - [`ResponseOptions`]
|
||||
/// - [`ServerMetaContext`](leptos_meta::ServerMetaContext)
|
||||
/// - [`RouterIntegrationContext`](leptos_router::RouterIntegrationContext)
|
||||
/// - [`ServerMetaContext`]
|
||||
#[cfg_attr(
|
||||
feature = "tracing",
|
||||
tracing::instrument(level = "trace", fields(error), skip_all)
|
||||
@@ -532,12 +529,6 @@ where
|
||||
/// This stream will pause at each `<Suspense/>` node and wait for it to resolve before
|
||||
/// sending down its HTML. The app will become interactive once it has fully loaded.
|
||||
///
|
||||
/// The provides a [MetaContext] and a [RouterIntegrationContext] to app’s context before
|
||||
/// rendering it, and includes any meta tags injected using [leptos_meta].
|
||||
///
|
||||
/// The HTML stream is rendered using [render_to_stream_in_order], and includes everything described in
|
||||
/// the documentation for that function.
|
||||
///
|
||||
/// This can then be set up at an appropriate route in your application:
|
||||
/// ```
|
||||
/// use axum::{handler::Handler, Router};
|
||||
@@ -575,8 +566,7 @@ where
|
||||
/// This function always provides context values including the following types:
|
||||
/// - [`Parts`]
|
||||
/// - [`ResponseOptions`]
|
||||
/// - [`ServerMetaContext`](leptos_meta::ServerMetaContext)
|
||||
/// - [`RouterIntegrationContext`](leptos_router::RouterIntegrationContext)
|
||||
/// - [`ServerMetaContext`]
|
||||
#[cfg_attr(
|
||||
feature = "tracing",
|
||||
tracing::instrument(level = "trace", fields(error), skip_all)
|
||||
@@ -629,8 +619,7 @@ where
|
||||
/// This function always provides context values including the following types:
|
||||
/// - [`Parts`]
|
||||
/// - [`ResponseOptions`]
|
||||
/// - [`ServerMetaContext`](leptos_meta::ServerMetaContext)
|
||||
/// - [`RouterIntegrationContext`](leptos_router::RouterIntegrationContext)
|
||||
/// - [`ServerMetaContext`]
|
||||
#[cfg_attr(
|
||||
feature = "tracing",
|
||||
tracing::instrument(level = "trace", fields(error), skip_all)
|
||||
@@ -761,8 +750,7 @@ where
|
||||
/// This function always provides context values including the following types:
|
||||
/// - [`Parts`]
|
||||
/// - [`ResponseOptions`]
|
||||
/// - [`ServerMetaContext`](leptos_meta::ServerMetaContext)
|
||||
/// - [`RouterIntegrationContext`](leptos_router::RouterIntegrationContext)
|
||||
/// - [`ServerMetaContext`]
|
||||
#[cfg_attr(
|
||||
feature = "tracing",
|
||||
tracing::instrument(level = "trace", fields(error), skip_all)
|
||||
@@ -829,8 +817,7 @@ where
|
||||
/// This function always provides context values including the following types:
|
||||
/// - [`Parts`]
|
||||
/// - [`ResponseOptions`]
|
||||
/// - [`ServerMetaContext`](leptos_meta::ServerMetaContext)
|
||||
/// - [`RouterIntegrationContext`](leptos_router::RouterIntegrationContext)
|
||||
/// - [`ServerMetaContext`]
|
||||
#[cfg_attr(
|
||||
feature = "tracing",
|
||||
tracing::instrument(level = "trace", fields(error), skip_all)
|
||||
@@ -947,13 +934,7 @@ fn provide_contexts(
|
||||
|
||||
/// 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` [Resource](leptos::Resource)s have loaded.
|
||||
///
|
||||
/// The provides a [MetaContext] and a [RouterIntegrationContext] to app’s context before
|
||||
/// rendering it, and includes any meta tags injected using [leptos_meta].
|
||||
///
|
||||
/// The HTML stream is rendered using [render_to_string_async], and includes everything described in
|
||||
/// the documentation for that function.
|
||||
/// `async` resources have loaded.
|
||||
///
|
||||
/// This can then be set up at an appropriate route in your application:
|
||||
/// ```
|
||||
@@ -993,8 +974,7 @@ fn provide_contexts(
|
||||
/// This function always provides context values including the following types:
|
||||
/// - [`Parts`]
|
||||
/// - [`ResponseOptions`]
|
||||
/// - [`ServerMetaContext`](leptos_meta::ServerMetaContext)
|
||||
/// - [`RouterIntegrationContext`](leptos_router::RouterIntegrationContext)
|
||||
/// - [`ServerMetaContext`]
|
||||
#[cfg_attr(
|
||||
feature = "tracing",
|
||||
tracing::instrument(level = "trace", fields(error), skip_all)
|
||||
@@ -1015,7 +995,7 @@ where
|
||||
|
||||
/// 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` [Resource](leptos::Resource)s have loaded.
|
||||
/// `async` resources have loaded.
|
||||
///
|
||||
/// This version allows us to pass Axum State/Extension/Extractor or other infro from Axum or network
|
||||
/// layers above Leptos itself. To use it, you'll need to write your own handler function that provides
|
||||
@@ -1048,8 +1028,7 @@ where
|
||||
/// This function always provides context values including the following types:
|
||||
/// - [`Parts`]
|
||||
/// - [`ResponseOptions`]
|
||||
/// - [`ServerMetaContext`](leptos_meta::ServerMetaContext)
|
||||
/// - [`RouterIntegrationContext`](leptos_router::RouterIntegrationContext)
|
||||
/// - [`ServerMetaContext`]
|
||||
#[cfg_attr(
|
||||
feature = "tracing",
|
||||
tracing::instrument(level = "trace", fields(error), skip_all)
|
||||
@@ -1083,7 +1062,7 @@ where
|
||||
|
||||
/// 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` [Resource](leptos::Resource)s have loaded.
|
||||
/// `async` resources have loaded.
|
||||
///
|
||||
/// This version allows us to pass Axum State/Extension/Extractor or other infro from Axum or network
|
||||
/// layers above Leptos itself. To use it, you'll need to write your own handler function that provides
|
||||
@@ -1116,8 +1095,7 @@ where
|
||||
/// This function always provides context values including the following types:
|
||||
/// - [`Parts`]
|
||||
/// - [`ResponseOptions`]
|
||||
/// - [`ServerMetaContext`](leptos_meta::ServerMetaContext)
|
||||
/// - [`RouterIntegrationContext`](leptos_router::RouterIntegrationContext)
|
||||
/// - [`ServerMetaContext`]
|
||||
#[cfg_attr(
|
||||
feature = "tracing",
|
||||
tracing::instrument(level = "trace", fields(error), skip_all)
|
||||
@@ -1656,6 +1634,9 @@ where
|
||||
S: Clone + Send + Sync + 'static,
|
||||
LeptosOptions: FromRef<S>,
|
||||
{
|
||||
/// Adds routes to the Axum router that have either
|
||||
/// 1) been generated by `leptos_router`, or
|
||||
/// 2) handle a server function.
|
||||
fn leptos_routes<IV>(
|
||||
self,
|
||||
options: &S,
|
||||
@@ -1665,6 +1646,12 @@ where
|
||||
where
|
||||
IV: IntoView + 'static;
|
||||
|
||||
/// Adds routes to the Axum router that have either
|
||||
/// 1) been generated by `leptos_router`, or
|
||||
/// 2) handle a server function.
|
||||
///
|
||||
/// Runs `additional_context` to provide additional data to the reactive system via context,
|
||||
/// when handling a route.
|
||||
fn leptos_routes_with_context<IV>(
|
||||
self,
|
||||
options: &S,
|
||||
@@ -1675,6 +1662,8 @@ where
|
||||
where
|
||||
IV: IntoView + 'static;
|
||||
|
||||
/// Extends the Axum router with the given paths, and handles the requests with the given
|
||||
/// handler.
|
||||
fn leptos_routes_with_handler<H, T>(
|
||||
self,
|
||||
paths: Vec<AxumRouteListing>,
|
||||
@@ -1987,6 +1976,71 @@ where
|
||||
.map_err(|e| ServerFnError::ServerError(format!("{e:?}")))
|
||||
}
|
||||
|
||||
/// A reasonable handler for serving static files (like JS/WASM/CSS) and 404 errors.
|
||||
///
|
||||
/// This is provided as a convenience, but is a fairly simple function. If you need to adapt it,
|
||||
/// simply reuse the source code of this function in your own application.
|
||||
#[cfg(feature = "default")]
|
||||
pub fn file_and_error_handler_with_context<S, IV>(
|
||||
additional_context: impl Fn() + 'static + Clone + Send,
|
||||
shell: fn(LeptosOptions) -> IV,
|
||||
) -> impl Fn(
|
||||
Uri,
|
||||
State<S>,
|
||||
Request<Body>,
|
||||
) -> Pin<Box<dyn Future<Output = Response<Body>> + Send + 'static>>
|
||||
+ Clone
|
||||
+ Send
|
||||
+ 'static
|
||||
where
|
||||
IV: IntoView + 'static,
|
||||
S: Send + Sync + Clone + 'static,
|
||||
LeptosOptions: FromRef<S>,
|
||||
{
|
||||
move |uri: Uri, State(state): State<S>, req: Request<Body>| {
|
||||
Box::pin({
|
||||
let additional_context = additional_context.clone();
|
||||
async move {
|
||||
let options = LeptosOptions::from_ref(&state);
|
||||
let res =
|
||||
get_static_file(uri, &options.site_root, req.headers());
|
||||
let res = res.await.unwrap();
|
||||
|
||||
if res.status() == StatusCode::OK {
|
||||
res.into_response()
|
||||
} else {
|
||||
let mut res = handle_response_inner(
|
||||
move || {
|
||||
additional_context();
|
||||
provide_context(state.clone());
|
||||
},
|
||||
move || shell(options),
|
||||
req,
|
||||
|app, chunks| {
|
||||
Box::pin(async move {
|
||||
let app = app
|
||||
.to_html_stream_in_order()
|
||||
.collect::<String>()
|
||||
.await;
|
||||
let chunks = chunks();
|
||||
Box::pin(once(async move { app }).chain(chunks))
|
||||
as PinnedStream<String>
|
||||
})
|
||||
},
|
||||
)
|
||||
.await;
|
||||
*res.status_mut() = StatusCode::NOT_FOUND;
|
||||
res
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// A reasonable handler for serving static files (like JS/WASM/CSS) and 404 errors.
|
||||
///
|
||||
/// This is provided as a convenience, but is a fairly simple function. If you need to adapt it,
|
||||
/// simply reuse the source code of this function in your own application.
|
||||
#[cfg(feature = "default")]
|
||||
pub fn file_and_error_handler<S, IV>(
|
||||
shell: fn(LeptosOptions) -> IV,
|
||||
@@ -2000,40 +2054,10 @@ pub fn file_and_error_handler<S, IV>(
|
||||
+ 'static
|
||||
where
|
||||
IV: IntoView + 'static,
|
||||
S: Send + 'static,
|
||||
S: Send + Sync + Clone + 'static,
|
||||
LeptosOptions: FromRef<S>,
|
||||
{
|
||||
move |uri: Uri, State(options): State<S>, req: Request<Body>| {
|
||||
Box::pin(async move {
|
||||
let options = LeptosOptions::from_ref(&options);
|
||||
let res = get_static_file(uri, &options.site_root, req.headers());
|
||||
let res = res.await.unwrap();
|
||||
|
||||
if res.status() == StatusCode::OK {
|
||||
res.into_response()
|
||||
} else {
|
||||
let mut res = handle_response_inner(
|
||||
|| {},
|
||||
move || shell(options),
|
||||
req,
|
||||
|app, chunks| {
|
||||
Box::pin(async move {
|
||||
let app = app
|
||||
.to_html_stream_in_order()
|
||||
.collect::<String>()
|
||||
.await;
|
||||
let chunks = chunks();
|
||||
Box::pin(once(async move { app }).chain(chunks))
|
||||
as PinnedStream<String>
|
||||
})
|
||||
},
|
||||
)
|
||||
.await;
|
||||
*res.status_mut() = StatusCode::NOT_FOUND;
|
||||
res
|
||||
}
|
||||
})
|
||||
}
|
||||
file_and_error_handler_with_context(move || (), shell)
|
||||
}
|
||||
|
||||
#[cfg(feature = "default")]
|
||||
|
||||
@@ -40,15 +40,28 @@ pub trait ExtendResponse: Sized {
|
||||
let (owner, stream) =
|
||||
build_response(app_fn, additional_context, stream_builder);
|
||||
|
||||
let sc = owner.shared_context().unwrap();
|
||||
|
||||
let stream = stream.await.ready_chunks(32).map(|n| n.join(""));
|
||||
|
||||
let sc = owner.shared_context().unwrap();
|
||||
while let Some(pending) = sc.await_deferred() {
|
||||
pending.await;
|
||||
}
|
||||
|
||||
let mut stream =
|
||||
Box::pin(meta_context.inject_meta_context(stream).await);
|
||||
let mut stream = Box::pin(
|
||||
meta_context.inject_meta_context(stream).await.then({
|
||||
let sc = Arc::clone(&sc);
|
||||
move |chunk| {
|
||||
let sc = Arc::clone(&sc);
|
||||
async move {
|
||||
while let Some(pending) = sc.await_deferred() {
|
||||
pending.await;
|
||||
}
|
||||
chunk
|
||||
}
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
// wait for the first chunk of the stream, then set the status and headers
|
||||
let first_chunk = stream.next().await.unwrap_or_default();
|
||||
|
||||
@@ -11,7 +11,10 @@ edition.workspace = true
|
||||
|
||||
[dependencies]
|
||||
throw_error = { workspace = true }
|
||||
any_spawner = { workspace = true, features = ["wasm-bindgen", "futures-executor"] }
|
||||
any_spawner = { workspace = true, features = [
|
||||
"wasm-bindgen",
|
||||
"futures-executor",
|
||||
] }
|
||||
base64 = { version = "0.22.1", optional = true }
|
||||
cfg-if = "1.0"
|
||||
hydration_context = { workspace = true }
|
||||
@@ -28,9 +31,13 @@ paste = "1.0"
|
||||
rand = { version = "0.8.5", optional = true }
|
||||
reactive_graph = { workspace = true, features = ["serde"] }
|
||||
rustc-hash = "2.0"
|
||||
tachys = { workspace = true, features = ["reactive_graph", "reactive_stores", "oco"] }
|
||||
tachys = { workspace = true, features = [
|
||||
"reactive_graph",
|
||||
"reactive_stores",
|
||||
"oco",
|
||||
] }
|
||||
thiserror = "2.0"
|
||||
tracing = { version = "0.1.40", optional = true }
|
||||
tracing = { version = "0.1.41", optional = true }
|
||||
typed-builder = "0.20.0"
|
||||
typed-builder-macro = "0.20.0"
|
||||
serde = "1.0"
|
||||
@@ -45,25 +52,27 @@ web-sys = { version = "0.3.72", features = [
|
||||
"ShadowRootInit",
|
||||
"ShadowRootMode",
|
||||
] }
|
||||
wasm-bindgen = "0.2.95"
|
||||
wasm-bindgen = "0.2.97"
|
||||
serde_qs = "0.13.0"
|
||||
slotmap = "1.0"
|
||||
futures = "0.3.31"
|
||||
send_wrapper = "0.6.0"
|
||||
getrandom = { version = "0.2", features = ["js"], optional = true }
|
||||
|
||||
[features]
|
||||
hydration = [
|
||||
"reactive_graph/hydration",
|
||||
"leptos_server/hydration",
|
||||
"hydration_context/browser",
|
||||
"leptos_dom/hydration"
|
||||
"leptos_dom/hydration",
|
||||
]
|
||||
csr = ["leptos_macro/csr", "reactive_graph/effects"]
|
||||
csr = ["leptos_macro/csr", "reactive_graph/effects", "dep:getrandom"]
|
||||
hydrate = [
|
||||
"leptos_macro/hydrate",
|
||||
"hydration",
|
||||
"tachys/hydrate",
|
||||
"reactive_graph/effects",
|
||||
"dep:getrandom",
|
||||
]
|
||||
default-tls = ["server_fn/default-tls"]
|
||||
rustls = ["server_fn/rustls"]
|
||||
@@ -75,7 +84,10 @@ ssr = [
|
||||
"tachys/ssr",
|
||||
]
|
||||
nightly = ["leptos_macro/nightly", "reactive_graph/nightly", "tachys/nightly"]
|
||||
rkyv = ["server_fn/rkyv"]
|
||||
rkyv = [
|
||||
"server_fn/rkyv",
|
||||
"leptos_server/rkyv"
|
||||
]
|
||||
tracing = [
|
||||
"dep:tracing",
|
||||
"reactive_graph/tracing",
|
||||
@@ -86,10 +98,10 @@ tracing = [
|
||||
]
|
||||
nonce = ["base64", "rand"]
|
||||
spin = ["leptos-spin-macro"]
|
||||
experimental-islands = ["leptos_macro/experimental-islands", "dep:serde_json"]
|
||||
islands = ["leptos_macro/islands", "dep:serde_json"]
|
||||
trace-component-props = [
|
||||
"leptos_macro/trace-component-props",
|
||||
"leptos_dom/trace-component-props"
|
||||
"leptos_dom/trace-component-props",
|
||||
]
|
||||
delegation = ["tachys/delegation"]
|
||||
|
||||
@@ -101,23 +113,56 @@ denylist = [
|
||||
"rustls",
|
||||
"default-tls",
|
||||
"wasm-bindgen",
|
||||
"rkyv", # was causing clippy issues on nightly
|
||||
"rkyv", # was causing clippy issues on nightly
|
||||
"trace-component-props",
|
||||
"spin",
|
||||
"experimental-islands",
|
||||
"islands",
|
||||
]
|
||||
skip_feature_sets = [
|
||||
["csr", "ssr"],
|
||||
["csr", "hydrate"],
|
||||
["ssr", "hydrate"],
|
||||
["serde", "serde-lite"],
|
||||
["serde-lite", "miniserde"],
|
||||
["serde", "miniserde"],
|
||||
["serde", "rkyv"],
|
||||
["miniserde", "rkyv"],
|
||||
["serde-lite", "rkyv"],
|
||||
["default-tls", "rustls"],
|
||||
[
|
||||
"csr",
|
||||
"ssr",
|
||||
],
|
||||
[
|
||||
"csr",
|
||||
"hydrate",
|
||||
],
|
||||
[
|
||||
"ssr",
|
||||
"hydrate",
|
||||
],
|
||||
[
|
||||
"serde",
|
||||
"serde-lite",
|
||||
],
|
||||
[
|
||||
"serde-lite",
|
||||
"miniserde",
|
||||
],
|
||||
[
|
||||
"serde",
|
||||
"miniserde",
|
||||
],
|
||||
[
|
||||
"serde",
|
||||
"rkyv",
|
||||
],
|
||||
[
|
||||
"miniserde",
|
||||
"rkyv",
|
||||
],
|
||||
[
|
||||
"serde-lite",
|
||||
"rkyv",
|
||||
],
|
||||
[
|
||||
"default-tls",
|
||||
"rustls",
|
||||
],
|
||||
]
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
rustdoc-args = ["--generate-link-to-definition"]
|
||||
|
||||
[lints.rust]
|
||||
unexpected_cfgs = { level = "warn", check-cfg = ['cfg(leptos_debuginfo)'] }
|
||||
|
||||
150
leptos/src/attribute_interceptor.rs
Normal file
150
leptos/src/attribute_interceptor.rs
Normal file
@@ -0,0 +1,150 @@
|
||||
use crate::attr::{
|
||||
any_attribute::{AnyAttribute, IntoAnyAttribute},
|
||||
Attribute, NextAttribute,
|
||||
};
|
||||
use leptos::prelude::*;
|
||||
|
||||
/// Function stored to build/rebuild the wrapped children when attributes are added.
|
||||
type ChildBuilder<T> = dyn Fn(AnyAttribute) -> T + Send + Sync + 'static;
|
||||
|
||||
/// Intercepts attributes passed to your component, allowing passing them to any element.
|
||||
///
|
||||
/// By default, Leptos passes any attributes passed to your component (e.g. `<MyComponent
|
||||
/// attr:class="some-class"/>`) to the top-level element in the view returned by your component.
|
||||
/// [`AttributeInterceptor`] allows you to intercept this behavior and pass it onto any element in
|
||||
/// your component instead.
|
||||
///
|
||||
/// Must be the top level element in your component's view.
|
||||
///
|
||||
/// ## Example
|
||||
///
|
||||
/// Any attributes passed to MyComponent will be passed to the #inner element.
|
||||
///
|
||||
/// ```
|
||||
/// # use leptos::prelude::*;
|
||||
/// use leptos::attribute_interceptor::AttributeInterceptor;
|
||||
///
|
||||
/// #[component]
|
||||
/// pub fn MyComponent() -> impl IntoView {
|
||||
/// view! {
|
||||
/// <AttributeInterceptor let:attrs>
|
||||
/// <div id="wrapper">
|
||||
/// <div id="inner" {..attrs} />
|
||||
/// </div>
|
||||
/// </AttributeInterceptor>
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
#[component(transparent)]
|
||||
pub fn AttributeInterceptor<Chil, T>(
|
||||
/// The elements that will be rendered, with the attributes this component received as a
|
||||
/// parameter.
|
||||
children: Chil,
|
||||
) -> impl IntoView
|
||||
where
|
||||
Chil: Fn(AnyAttribute) -> T + Send + Sync + 'static,
|
||||
T: IntoView,
|
||||
{
|
||||
AttributeInterceptorInner::new(children)
|
||||
}
|
||||
|
||||
/// Wrapper to intercept attributes passed to a component so you can apply them to a different
|
||||
/// element.
|
||||
struct AttributeInterceptorInner<T: IntoView, A> {
|
||||
children_builder: Box<ChildBuilder<T>>,
|
||||
children: T,
|
||||
attributes: A,
|
||||
}
|
||||
|
||||
impl<T: IntoView> AttributeInterceptorInner<T, ()> {
|
||||
/// Use this as the returned view from your component to collect the attributes that are passed
|
||||
/// to your component so you can manually handle them.
|
||||
pub fn new<F>(children: F) -> Self
|
||||
where
|
||||
F: Fn(AnyAttribute) -> T + Send + Sync + 'static,
|
||||
{
|
||||
let children_builder = Box::new(children);
|
||||
let children = children_builder(().into_any_attr());
|
||||
|
||||
Self {
|
||||
children_builder,
|
||||
children,
|
||||
attributes: (),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: IntoView, A: Attribute> Render for AttributeInterceptorInner<T, A> {
|
||||
type State = <T as Render>::State;
|
||||
|
||||
fn build(self) -> Self::State {
|
||||
self.children.build()
|
||||
}
|
||||
|
||||
fn rebuild(self, state: &mut Self::State) {
|
||||
self.children.rebuild(state);
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: IntoView, A> AddAnyAttr for AttributeInterceptorInner<T, A>
|
||||
where
|
||||
A: Attribute,
|
||||
{
|
||||
type Output<SomeNewAttr: leptos::attr::Attribute> =
|
||||
AttributeInterceptorInner<T, <<A as NextAttribute>::Output<SomeNewAttr> as Attribute>::CloneableOwned>;
|
||||
|
||||
fn add_any_attr<NewAttr: leptos::attr::Attribute>(
|
||||
self,
|
||||
attr: NewAttr,
|
||||
) -> Self::Output<NewAttr>
|
||||
where
|
||||
Self::Output<NewAttr>: RenderHtml,
|
||||
{
|
||||
let attributes =
|
||||
self.attributes.add_any_attr(attr).into_cloneable_owned();
|
||||
|
||||
let children =
|
||||
(self.children_builder)(attributes.clone().into_any_attr());
|
||||
|
||||
AttributeInterceptorInner {
|
||||
children_builder: self.children_builder,
|
||||
children,
|
||||
attributes,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: IntoView, A: Attribute> RenderHtml for AttributeInterceptorInner<T, A> {
|
||||
type AsyncOutput = T::AsyncOutput;
|
||||
|
||||
const MIN_LENGTH: usize = T::MIN_LENGTH;
|
||||
|
||||
fn dry_resolve(&mut self) {
|
||||
self.children.dry_resolve()
|
||||
}
|
||||
|
||||
fn resolve(
|
||||
self,
|
||||
) -> impl std::future::Future<Output = Self::AsyncOutput> + Send {
|
||||
self.children.resolve()
|
||||
}
|
||||
|
||||
fn to_html_with_buf(
|
||||
self,
|
||||
buf: &mut String,
|
||||
position: &mut leptos::tachys::view::Position,
|
||||
escape: bool,
|
||||
mark_branches: bool,
|
||||
) {
|
||||
self.children
|
||||
.to_html_with_buf(buf, position, escape, mark_branches)
|
||||
}
|
||||
|
||||
fn hydrate<const FROM_SERVER: bool>(
|
||||
self,
|
||||
cursor: &leptos::tachys::hydration::Cursor,
|
||||
position: &leptos::tachys::view::PositionState,
|
||||
) -> Self::State {
|
||||
self.children.hydrate::<FROM_SERVER>(cursor, position)
|
||||
}
|
||||
}
|
||||
@@ -31,13 +31,13 @@
|
||||
//! *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`] trait, and can be invoked with `my_callback.run(input)`.
|
||||
//! - 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`]
|
||||
//! - [`UnsyncCallback`]
|
||||
//! - [`Callback`](leptos::callback::Callback)
|
||||
//! - [`UnsyncCallback`](leptos::callback::UnsyncCallback)
|
||||
//!
|
||||
//! Use `SyncCallback` if the function is not `Sync` and `Send`.
|
||||
|
||||
@@ -80,6 +80,16 @@ impl<In, Out> UnsyncCallback<In, Out> {
|
||||
{
|
||||
Self(StoredValue::new_local(Rc::new(f)))
|
||||
}
|
||||
|
||||
/// Returns `true` if both callbacks wrap the same underlying function pointer.
|
||||
#[inline]
|
||||
pub fn matches(&self, other: &Self) -> bool {
|
||||
self.0.with_value(|self_value| {
|
||||
other
|
||||
.0
|
||||
.with_value(|other_value| Rc::ptr_eq(self_value, other_value))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<In: 'static, Out: 'static> Callable<In, Out> for UnsyncCallback<In, Out> {
|
||||
@@ -212,6 +222,19 @@ impl<In: 'static, Out: 'static> Callback<In, Out> {
|
||||
{
|
||||
Self(StoredValue::new(Arc::new(fun)))
|
||||
}
|
||||
|
||||
/// Returns `true` if both callbacks wrap the same underlying function pointer.
|
||||
#[inline]
|
||||
pub fn matches(&self, other: &Self) -> bool {
|
||||
self.0
|
||||
.try_with_value(|self_value| {
|
||||
other.0.try_with_value(|other_value| {
|
||||
Arc::ptr_eq(self_value, other_value)
|
||||
})
|
||||
})
|
||||
.flatten()
|
||||
.unwrap_or(false)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -223,14 +246,14 @@ mod tests {
|
||||
#[test]
|
||||
fn clone_callback() {
|
||||
let callback = Callback::new(move |_no_clone: NoClone| NoClone {});
|
||||
let _cloned = callback.clone();
|
||||
let _cloned = callback;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clone_unsync_callback() {
|
||||
let callback =
|
||||
UnsyncCallback::new(move |_no_clone: NoClone| NoClone {});
|
||||
let _cloned = callback.clone();
|
||||
let _cloned = callback;
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -246,4 +269,32 @@ mod tests {
|
||||
let _callback: UnsyncCallback<(i32, String), String> =
|
||||
(|num, s| format!("{num} {s}")).into();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn callback_matches_same() {
|
||||
let callback1 = Callback::new(|x: i32| x * 2);
|
||||
let callback2 = callback1.clone();
|
||||
assert!(callback1.matches(&callback2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn callback_matches_different() {
|
||||
let callback1 = Callback::new(|x: i32| x * 2);
|
||||
let callback2 = Callback::new(|x: i32| x + 1);
|
||||
assert!(!callback1.matches(&callback2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsync_callback_matches_same() {
|
||||
let callback1 = UnsyncCallback::new(|x: i32| x * 2);
|
||||
let callback2 = callback1.clone();
|
||||
assert!(callback1.matches(&callback2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsync_callback_matches_different() {
|
||||
let callback1 = UnsyncCallback::new(|x: i32| x * 2);
|
||||
let callback2 = UnsyncCallback::new(|x: i32| x + 1);
|
||||
assert!(!callback1.matches(&callback2));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -85,7 +85,7 @@ type BoxedChildrenFn = Box<dyn Fn() -> AnyView + Send>;
|
||||
/// )
|
||||
/// }
|
||||
pub trait ToChildren<F> {
|
||||
/// Convert the provided type to (generally a closure) to Self (generally a "children" type,
|
||||
/// Convert the provided type (generally a closure) to Self (generally a "children" type,
|
||||
/// e.g., [Children]). See the implementations to see exactly which input types are supported
|
||||
/// and which "children" type they are converted to.
|
||||
fn to_children(f: F) -> Self;
|
||||
@@ -228,6 +228,7 @@ impl ViewFnOnce {
|
||||
pub struct TypedChildren<T>(Box<dyn FnOnce() -> View<T> + Send>);
|
||||
|
||||
impl<T> TypedChildren<T> {
|
||||
/// Extracts the inner `children` function.
|
||||
pub fn into_inner(self) -> impl FnOnce() -> View<T> + Send {
|
||||
self.0
|
||||
}
|
||||
@@ -245,7 +246,7 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
/// A typed equivalent to [`ChildrenMut`], which takes a generic but preserves type information to
|
||||
/// A typed equivalent to [`ChildrenFnMut`], which takes a generic but preserves type information to
|
||||
/// allow the compiler to optimize the view more effectively.
|
||||
pub struct TypedChildrenMut<T>(Box<dyn FnMut() -> View<T> + Send>);
|
||||
|
||||
@@ -256,6 +257,7 @@ impl<T> Debug for TypedChildrenMut<T> {
|
||||
}
|
||||
|
||||
impl<T> TypedChildrenMut<T> {
|
||||
/// Extracts the inner `children` function.
|
||||
pub fn into_inner(self) -> impl FnMut() -> View<T> + Send {
|
||||
self.0
|
||||
}
|
||||
@@ -283,7 +285,15 @@ impl<T> Debug for TypedChildrenFn<T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Clone for TypedChildrenFn<T> {
|
||||
// Manual implementation to avoid the `T: Clone` bound.
|
||||
fn clone(&self) -> Self {
|
||||
Self(self.0.clone())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> TypedChildrenFn<T> {
|
||||
/// Extracts the inner `children` function.
|
||||
pub fn into_inner(self) -> Arc<dyn Fn() -> View<T> + Send + Sync> {
|
||||
self.0
|
||||
}
|
||||
|
||||
@@ -44,6 +44,67 @@ use tachys::{reactive_graph::OwnedView, view::keyed::keyed};
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// For convenience, you can also choose to write template code directly in the `<For>`
|
||||
/// component, using the `let` syntax:
|
||||
///
|
||||
/// ```
|
||||
/// # use leptos::prelude::*;
|
||||
///
|
||||
/// # #[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
/// # struct Counter {
|
||||
/// # id: usize,
|
||||
/// # count: RwSignal<i32>
|
||||
/// # }
|
||||
/// #
|
||||
/// # #[component]
|
||||
/// # fn Counters() -> impl IntoView {
|
||||
/// # let (counters, set_counters) = create_signal::<Vec<Counter>>(vec![]);
|
||||
/// #
|
||||
/// view! {
|
||||
/// <div>
|
||||
/// <For
|
||||
/// each=move || counters.get()
|
||||
/// key=|counter| counter.id
|
||||
/// let(counter)
|
||||
/// >
|
||||
/// <button>"Value: " {move || counter.count.get()}</button>
|
||||
/// </For>
|
||||
/// </div>
|
||||
/// }
|
||||
/// # }
|
||||
/// ```
|
||||
///
|
||||
/// The `let` syntax also supports destructuring the pattern of your data.
|
||||
/// `let((one, two))` in the case of tuples, and `let(Struct { field_one, field_two })`
|
||||
/// in the case of structs.
|
||||
///
|
||||
/// ```
|
||||
/// # use leptos::prelude::*;
|
||||
///
|
||||
/// # #[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
/// # struct Counter {
|
||||
/// # id: usize,
|
||||
/// # count: RwSignal<i32>
|
||||
/// # }
|
||||
/// #
|
||||
/// # #[component]
|
||||
/// # fn Counters() -> impl IntoView {
|
||||
/// # let (counters, set_counters) = create_signal::<Vec<Counter>>(vec![]);
|
||||
/// #
|
||||
/// view! {
|
||||
/// <div>
|
||||
/// <For
|
||||
/// each=move || counters.get()
|
||||
/// key=|counter| counter.id
|
||||
/// let(Counter { id, count })
|
||||
/// >
|
||||
/// <button>"Value: " {move || count.get()}</button>
|
||||
/// </For>
|
||||
/// </div>
|
||||
/// }
|
||||
/// # }
|
||||
/// ```
|
||||
#[cfg_attr(feature = "tracing", tracing::instrument(level = "trace", skip_all))]
|
||||
#[component]
|
||||
pub fn For<IF, I, T, EF, N, KF, K>(
|
||||
|
||||
@@ -72,9 +72,7 @@ use web_sys::{
|
||||
#[cfg_attr(feature = "tracing", tracing::instrument(level = "trace", skip_all))]
|
||||
#[component]
|
||||
pub fn ActionForm<ServFn>(
|
||||
/// The action from which to build the form. This should include a URL, which can be generated
|
||||
/// by default using [`create_server_action`](leptos_server::create_server_action) or added
|
||||
/// manually using [`using_server_fn`](leptos_server::Action::using_server_fn).
|
||||
/// The action from which to build the form.
|
||||
action: ServerAction<ServFn>,
|
||||
/// A [`NodeRef`] in which the `<form>` element should be stored.
|
||||
#[prop(optional)]
|
||||
@@ -149,9 +147,7 @@ where
|
||||
/// progressively enhanced to use client-side routing.
|
||||
#[component]
|
||||
pub fn MultiActionForm<ServFn>(
|
||||
/// The action from which to build the form. This should include a URL, which can be generated
|
||||
/// by default using [create_server_action](leptos_server::create_server_action) or added
|
||||
/// manually using [leptos_server::Action::using_server_fn].
|
||||
/// The action from which to build the form.
|
||||
action: ServerMultiAction<ServFn>,
|
||||
/// A [`NodeRef`] in which the `<form>` element should be stored.
|
||||
#[prop(optional)]
|
||||
@@ -251,12 +247,16 @@ where
|
||||
) -> Result<Self, serde_qs::Error>;
|
||||
}
|
||||
|
||||
/// Errors that can arise when coverting from an HTML event or form into a Rust data type.
|
||||
#[derive(Error, Debug)]
|
||||
pub enum FromFormDataError {
|
||||
/// Could not find a `<form>` connected to the event.
|
||||
#[error("Could not find <form> connected to event.")]
|
||||
MissingForm(Event),
|
||||
/// Could not create `FormData` from the form.
|
||||
#[error("Could not create FormData from <form>: {0:?}")]
|
||||
FormData(JsValue),
|
||||
/// Failed to deserialize this Rust type from the form data.
|
||||
#[error("Deserialization error: {0:?}")]
|
||||
Deserialization(serde_qs::Error),
|
||||
}
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
((root, pkg_path, output_name, wasm_output_name) => {
|
||||
let MOST_RECENT_CHILDREN_CB;
|
||||
|
||||
function idle(c) {
|
||||
if ("requestIdleCallback" in window) {
|
||||
window.requestIdleCallback(c);
|
||||
@@ -6,55 +8,49 @@
|
||||
c();
|
||||
}
|
||||
}
|
||||
function islandTree(rootNode) {
|
||||
const tree = [];
|
||||
|
||||
function traverse(node, parent) {
|
||||
function hydrateIslands(rootNode, mod) {
|
||||
function traverse(node) {
|
||||
if (node.nodeType === Node.ELEMENT_NODE) {
|
||||
if(node.tagName.toLowerCase() === 'leptos-island') {
|
||||
const tag = node.tagName.toLowerCase();
|
||||
if(tag === 'leptos-island') {
|
||||
const children = [];
|
||||
const id = node.dataset.component || null;
|
||||
const data = { id, node, children };
|
||||
|
||||
hydrateIsland(node, id, mod);
|
||||
|
||||
for(const child of node.children) {
|
||||
traverse(child, children);
|
||||
}
|
||||
|
||||
(parent || tree).push(data);
|
||||
} else {
|
||||
if(tag === 'leptos-children') {
|
||||
MOST_RECENT_CHILDREN_CB = node.$$on_hydrate;
|
||||
}
|
||||
for(const child of node.children) {
|
||||
traverse(child, parent);
|
||||
traverse(child);
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
traverse(rootNode, null);
|
||||
|
||||
return { el: null, id: null, children: tree };
|
||||
traverse(rootNode);
|
||||
}
|
||||
function hydrateIsland(el, id, mod) {
|
||||
const islandFn = mod[id];
|
||||
if (islandFn) {
|
||||
if (MOST_RECENT_CHILDREN_CB) {
|
||||
MOST_RECENT_CHILDREN_CB();
|
||||
}
|
||||
islandFn(el);
|
||||
} else {
|
||||
console.warn(`Could not find WASM function for the island ${id}.`);
|
||||
}
|
||||
}
|
||||
function hydrateIslands(entry, mod) {
|
||||
if(entry.node) {
|
||||
hydrateIsland(entry.node, entry.id, mod);
|
||||
}
|
||||
for (const island of entry.children) {
|
||||
hydrateIslands(island, mod);
|
||||
}
|
||||
}
|
||||
idle(() => {
|
||||
import(`${root}/${pkg_path}/${output_name}.js`)
|
||||
.then(mod => {
|
||||
mod.default(`${root}/${pkg_path}/${wasm_output_name}.wasm`).then(() => {
|
||||
mod.hydrate();
|
||||
hydrateIslands(islandTree(document.body, null), mod);
|
||||
hydrateIslands(document.body, mod);
|
||||
});
|
||||
})
|
||||
});
|
||||
|
||||
@@ -4,9 +4,15 @@ use crate::prelude::*;
|
||||
use leptos_config::LeptosOptions;
|
||||
use leptos_macro::{component, view};
|
||||
|
||||
/// Inserts auto-reloading code used in `cargo-leptos`.
|
||||
///
|
||||
/// This should be included in the `<head>` of your application shell during development.
|
||||
#[component]
|
||||
pub fn AutoReload(
|
||||
#[prop(optional)] disable_watch: bool,
|
||||
/// Whether the file-watching feature should be disabled.
|
||||
#[prop(optional)]
|
||||
disable_watch: bool,
|
||||
/// Configuration options for this project.
|
||||
options: LeptosOptions,
|
||||
) -> impl IntoView {
|
||||
(!disable_watch && std::env::var("LEPTOS_WATCH").is_ok()).then(|| {
|
||||
@@ -34,10 +40,16 @@ pub fn AutoReload(
|
||||
})
|
||||
}
|
||||
|
||||
/// Inserts hydration scripts that add interactivity to your server-rendered HTML.
|
||||
///
|
||||
/// This should be included in the `<head>` of your application shell.
|
||||
#[component]
|
||||
pub fn HydrationScripts(
|
||||
/// Configuration options for this project.
|
||||
options: LeptosOptions,
|
||||
#[prop(optional)] islands: bool,
|
||||
/// Should be `true` to hydrate in `islands` mode.
|
||||
#[prop(optional)]
|
||||
islands: bool,
|
||||
/// A base url, not including a trailing slash
|
||||
#[prop(optional, into)]
|
||||
root: Option<String>,
|
||||
|
||||
@@ -9,6 +9,7 @@ use tachys::{
|
||||
},
|
||||
};
|
||||
|
||||
/// A wrapper for any kind of view.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||
pub struct View<T>
|
||||
where
|
||||
@@ -20,6 +21,7 @@ where
|
||||
}
|
||||
|
||||
impl<T> View<T> {
|
||||
/// Wraps the view.
|
||||
pub fn new(inner: T) -> Self {
|
||||
Self {
|
||||
inner,
|
||||
@@ -28,10 +30,12 @@ impl<T> View<T> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Unwraps the view, returning the inner type.
|
||||
pub fn into_inner(self) -> T {
|
||||
self.inner
|
||||
}
|
||||
|
||||
/// Adds a view marker, which is used for hot-reloading and debug purposes.
|
||||
#[inline(always)]
|
||||
pub fn with_view_marker(
|
||||
#[allow(unused_mut)] // used in debug
|
||||
@@ -47,10 +51,12 @@ impl<T> View<T> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A trait that is implemented for types that can be rendered.
|
||||
pub trait IntoView
|
||||
where
|
||||
Self: Sized + Render + RenderHtml + Send,
|
||||
{
|
||||
/// Wraps the inner type.
|
||||
fn into_view(self) -> View<Self>;
|
||||
}
|
||||
|
||||
@@ -188,9 +194,15 @@ impl<T: AddAnyAttr> AddAnyAttr for View<T> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Collects some iterator of views into a list, so they can be rendered.
|
||||
///
|
||||
/// This is a shorthand for `.collect::<Vec<_>>()`, and allows any iterator of renderable
|
||||
/// items to be collected into a renderable collection.
|
||||
pub trait CollectView {
|
||||
/// The inner view type.
|
||||
type View: IntoView;
|
||||
|
||||
/// Collects the iterator into a list of views.
|
||||
fn collect_view(self) -> Vec<Self::View>;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#!rdeny(missing_docs)]
|
||||
#![deny(missing_docs)]
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
//! # About Leptos
|
||||
//!
|
||||
//! Leptos is a full-stack framework for building web applications in Rust. You can use it to build
|
||||
@@ -38,7 +39,7 @@
|
||||
//! server actions, forms, and server-sent events (SSE).
|
||||
//! - **[`todomvc`]** shows the basics of building an isomorphic web app. Both the server and the client import the same app code.
|
||||
//! The server renders the app directly to an HTML string, and the client hydrates that HTML to make it interactive.
|
||||
//! You might also want to see how we use [`Effect::new`](leptos::prelude::Effect::new) to
|
||||
//! You might also want to see how we use [`Effect::new`](leptos::prelude::Effect) to
|
||||
//! [serialize JSON to `localStorage`](https://github.com/leptos-rs/leptos/blob/20af4928b2fffe017408d3f4e7330db22cf68277/examples/todomvc/src/lib.rs#L191-L209)
|
||||
//! and [reactively call DOM methods](https://github.com/leptos-rs/leptos/blob/16f084a71268ac325fbc4a5e50c260df185eadb6/examples/todomvc/src/lib.rs#L292-L296)
|
||||
//! on [references to elements](https://github.com/leptos-rs/leptos/blob/20af4928b2fffe017408d3f4e7330db22cf68277/examples/todomvc/src/lib.rs#L228).
|
||||
@@ -77,7 +78,7 @@
|
||||
//! + `async` interop: [`Resource`](leptos::prelude::Resource) for loading data using `async` functions
|
||||
//! and [`Action`](leptos::prelude::Action) to mutate data or imperatively call `async` functions.
|
||||
//! + reactions: [`Effect`](leptos::prelude::Effect) and [`RenderEffect`](leptos::prelude::RenderEffect).
|
||||
//! - **Templating/Views**: the [`view`] macro and [`IntoView`](leptos::IntoView) trait.
|
||||
//! - **Templating/Views**: the [`view`] macro and [`IntoView`] trait.
|
||||
//! - **Routing**: the [`leptos_router`](https://docs.rs/leptos_router/latest/leptos_router/) crate
|
||||
//! - **Server Functions**: the [`server`](macro@leptos::prelude::server) macro and [`ServerAction`](leptos::prelude::ServerAction).
|
||||
//!
|
||||
@@ -191,6 +192,9 @@ pub mod callback;
|
||||
/// Types that can be passed as the `children` prop of a component.
|
||||
pub mod children;
|
||||
|
||||
/// Wrapper for intercepting component attributes.
|
||||
pub mod attribute_interceptor;
|
||||
|
||||
#[doc(hidden)]
|
||||
/// Traits used to implement component constructors.
|
||||
pub mod component;
|
||||
@@ -287,8 +291,9 @@ pub mod logging {
|
||||
pub use leptos_dom::{debug_warn, error, log, warn};
|
||||
}
|
||||
|
||||
/// Utilities for working with asynchronous tasks.
|
||||
pub mod task {
|
||||
pub use any_spawner::Executor;
|
||||
pub use any_spawner::{self, CustomExecutor, Executor};
|
||||
use std::future::Future;
|
||||
|
||||
/// Spawns a thread-safe [`Future`].
|
||||
@@ -316,10 +321,10 @@ pub mod task {
|
||||
}
|
||||
|
||||
// these reexports are used in islands
|
||||
#[cfg(feature = "experimental-islands")]
|
||||
#[cfg(feature = "islands")]
|
||||
#[doc(hidden)]
|
||||
pub use serde;
|
||||
#[cfg(feature = "experimental-islands")]
|
||||
#[cfg(feature = "islands")]
|
||||
#[doc(hidden)]
|
||||
pub use serde_json;
|
||||
#[cfg(feature = "tracing")]
|
||||
|
||||
@@ -51,6 +51,13 @@ use tachys::html::attribute::AttributeValue;
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct Nonce(pub(crate) Arc<str>);
|
||||
|
||||
impl Nonce {
|
||||
/// Returns a reference to the inner reference-counted string slice representing the nonce.
|
||||
pub fn as_inner(&self) -> &Arc<str> {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Deref for Nonce {
|
||||
type Target = str;
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ use reactive_graph::{
|
||||
traits::{Dispose, Get, Read, Track, With},
|
||||
};
|
||||
use slotmap::{DefaultKey, SlotMap};
|
||||
use std::sync::Arc;
|
||||
use tachys::{
|
||||
either::Either,
|
||||
html::attribute::Attribute,
|
||||
@@ -87,7 +88,12 @@ use throw_error::ErrorHookFuture;
|
||||
/// ```
|
||||
#[component]
|
||||
pub fn Suspense<Chil>(
|
||||
#[prop(optional, into)] fallback: ViewFnOnce,
|
||||
/// A function that returns a fallback that will be shown while resources are still loading.
|
||||
/// By default this is an empty view.
|
||||
#[prop(optional, into)]
|
||||
fallback: ViewFnOnce,
|
||||
/// Children will be rendered once initially to catch any resource reads, then hidden until all
|
||||
/// data have loaded.
|
||||
children: TypedChildren<Chil>,
|
||||
) -> impl IntoView
|
||||
where
|
||||
@@ -127,6 +133,18 @@ where
|
||||
})
|
||||
}
|
||||
|
||||
fn nonce_or_not() -> Option<Arc<str>> {
|
||||
#[cfg(feature = "nonce")]
|
||||
{
|
||||
use crate::nonce::Nonce;
|
||||
use_context::<Nonce>().map(|n| n.0)
|
||||
}
|
||||
#[cfg(not(feature = "nonce"))]
|
||||
{
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct SuspenseBoundary<const TRANSITION: bool, Fal, Chil> {
|
||||
pub id: SerializedDataId,
|
||||
pub none_pending: ArcMemo<bool>,
|
||||
@@ -374,7 +392,12 @@ where
|
||||
&mut fallback_position,
|
||||
mark_branches,
|
||||
);
|
||||
buf.push_async_out_of_order(fut, position, mark_branches);
|
||||
buf.push_async_out_of_order_with_nonce(
|
||||
fut,
|
||||
position,
|
||||
mark_branches,
|
||||
nonce_or_not(),
|
||||
);
|
||||
} else {
|
||||
buf.push_async({
|
||||
let mut position = *position;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use oco_ref::Oco;
|
||||
use std::sync::Arc;
|
||||
use tachys::prelude::IntoAttributeValue;
|
||||
|
||||
/// Describes a value that is either a static or a reactive string, i.e.,
|
||||
/// a [`String`], a [`&str`], or a reactive `Fn() -> String`.
|
||||
@@ -73,3 +74,11 @@ impl Default for TextProp {
|
||||
Self(Arc::new(|| Oco::Borrowed("")))
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoAttributeValue for TextProp {
|
||||
type Output = Oco<'static, str>;
|
||||
|
||||
fn into_attribute_value(self) -> Self::Output {
|
||||
self.get()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -85,41 +85,44 @@ pub fn Transition<Chil>(
|
||||
where
|
||||
Chil: IntoView + Send + 'static,
|
||||
{
|
||||
let (starts_local, id) = {
|
||||
Owner::current_shared_context()
|
||||
.map(|sc| {
|
||||
let id = sc.next_id();
|
||||
(sc.get_incomplete_chunk(&id), id)
|
||||
})
|
||||
.unwrap_or_else(|| (false, Default::default()))
|
||||
};
|
||||
let fallback = fallback.run();
|
||||
let children = children.into_inner()();
|
||||
let tasks = ArcRwSignal::new(SlotMap::<DefaultKey, ()>::new());
|
||||
provide_context(SuspenseContext {
|
||||
tasks: tasks.clone(),
|
||||
});
|
||||
let none_pending = ArcMemo::new(move |prev: Option<&bool>| {
|
||||
tasks.track();
|
||||
if prev.is_none() && starts_local {
|
||||
false
|
||||
} else {
|
||||
tasks.with(SlotMap::is_empty)
|
||||
}
|
||||
});
|
||||
if let Some(set_pending) = set_pending {
|
||||
Effect::new_isomorphic({
|
||||
let none_pending = none_pending.clone();
|
||||
move |_| {
|
||||
set_pending.set(!none_pending.get());
|
||||
let owner = Owner::new();
|
||||
owner.with(|| {
|
||||
let (starts_local, id) = {
|
||||
Owner::current_shared_context()
|
||||
.map(|sc| {
|
||||
let id = sc.next_id();
|
||||
(sc.get_incomplete_chunk(&id), id)
|
||||
})
|
||||
.unwrap_or_else(|| (false, Default::default()))
|
||||
};
|
||||
let fallback = fallback.run();
|
||||
let children = children.into_inner()();
|
||||
let tasks = ArcRwSignal::new(SlotMap::<DefaultKey, ()>::new());
|
||||
provide_context(SuspenseContext {
|
||||
tasks: tasks.clone(),
|
||||
});
|
||||
let none_pending = ArcMemo::new(move |prev: Option<&bool>| {
|
||||
tasks.track();
|
||||
if prev.is_none() && starts_local {
|
||||
false
|
||||
} else {
|
||||
tasks.with(SlotMap::is_empty)
|
||||
}
|
||||
});
|
||||
}
|
||||
if let Some(set_pending) = set_pending {
|
||||
Effect::new_isomorphic({
|
||||
let none_pending = none_pending.clone();
|
||||
move |_| {
|
||||
set_pending.set(!none_pending.get());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
OwnedView::new(SuspenseBoundary::<true, _, _> {
|
||||
id,
|
||||
none_pending,
|
||||
fallback,
|
||||
children,
|
||||
OwnedView::new(SuspenseBoundary::<true, _, _> {
|
||||
id,
|
||||
none_pending,
|
||||
fallback,
|
||||
children,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
2851
leptos/tests/test_examples/suspense-tests/Cargo.lock
generated
Normal file
2851
leptos/tests/test_examples/suspense-tests/Cargo.lock
generated
Normal file
File diff suppressed because it is too large
Load Diff
@@ -26,3 +26,6 @@ temp-env = { version = "0.3.6", features = ["async_closure"] }
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
rustdoc-args = ["--generate-link-to-definition"]
|
||||
|
||||
[lints.rust]
|
||||
unexpected_cfgs = { level = "warn", check-cfg = ['cfg(leptos_debuginfo)'] }
|
||||
@@ -30,14 +30,14 @@ fn ws_from_str_test() {
|
||||
|
||||
#[test]
|
||||
fn env_w_default_test() {
|
||||
_ = temp_env::with_var("LEPTOS_CONFIG_ENV_TEST", Some("custom"), || {
|
||||
temp_env::with_var("LEPTOS_CONFIG_ENV_TEST", Some("custom"), || {
|
||||
assert_eq!(
|
||||
env_w_default("LEPTOS_CONFIG_ENV_TEST", "default").unwrap(),
|
||||
String::from("custom")
|
||||
);
|
||||
});
|
||||
|
||||
_ = temp_env::with_var_unset("LEPTOS_CONFIG_ENV_TEST", || {
|
||||
temp_env::with_var_unset("LEPTOS_CONFIG_ENV_TEST", || {
|
||||
assert_eq!(
|
||||
env_w_default("LEPTOS_CONFIG_ENV_TEST", "default").unwrap(),
|
||||
String::from("default")
|
||||
@@ -47,14 +47,14 @@ fn env_w_default_test() {
|
||||
|
||||
#[test]
|
||||
fn env_wo_default_test() {
|
||||
_ = temp_env::with_var("LEPTOS_CONFIG_ENV_TEST", Some("custom"), || {
|
||||
temp_env::with_var("LEPTOS_CONFIG_ENV_TEST", Some("custom"), || {
|
||||
assert_eq!(
|
||||
env_wo_default("LEPTOS_CONFIG_ENV_TEST").unwrap(),
|
||||
Some(String::from("custom"))
|
||||
);
|
||||
});
|
||||
|
||||
_ = temp_env::with_var_unset("LEPTOS_CONFIG_ENV_TEST", || {
|
||||
temp_env::with_var_unset("LEPTOS_CONFIG_ENV_TEST", || {
|
||||
assert_eq!(env_wo_default("LEPTOS_CONFIG_ENV_TEST").unwrap(), None);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -12,10 +12,10 @@ edition.workspace = true
|
||||
tachys = { workspace = true }
|
||||
reactive_graph = { workspace = true }
|
||||
or_poisoned = { workspace = true }
|
||||
js-sys = "0.3.72"
|
||||
js-sys = "0.3.74"
|
||||
send_wrapper = "0.6.0"
|
||||
tracing = { version = "0.1.40", optional = true }
|
||||
wasm-bindgen = "0.2.95"
|
||||
tracing = { version = "0.1.41", optional = true }
|
||||
wasm-bindgen = "0.2.97"
|
||||
serde_json = { version = "1.0", optional = true }
|
||||
serde = { version = "1.0", optional = true }
|
||||
|
||||
@@ -37,3 +37,6 @@ rustdoc-args = ["--generate-link-to-definition"]
|
||||
|
||||
[package.metadata.cargo-all-features]
|
||||
denylist = ["tracing"]
|
||||
|
||||
[lints.rust]
|
||||
unexpected_cfgs = { level = "warn", check-cfg = ['cfg(leptos_debuginfo)'] }
|
||||
@@ -131,6 +131,10 @@ 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) {
|
||||
@@ -159,6 +163,10 @@ fn closure_once(cb: impl FnOnce() + 'static) -> JsValue {
|
||||
/// Runs the given function between the next repaint using
|
||||
/// [`Window.requestAnimationFrame`](https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame),
|
||||
/// returning a cancelable handle.
|
||||
///
|
||||
/// ### 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_with_handle(
|
||||
@@ -197,6 +205,10 @@ 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) {
|
||||
@@ -206,6 +218,10 @@ pub fn request_idle_callback(cb: impl Fn() + 'static) {
|
||||
/// 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.
|
||||
///
|
||||
/// ### 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_with_handle(
|
||||
@@ -239,6 +255,8 @@ pub fn request_idle_callback_with_handle(
|
||||
/// to perform final cleanup or other just-before-rendering tasks.
|
||||
///
|
||||
/// [MDN queueMicrotask](https://developer.mozilla.org/en-US/docs/Web/API/queueMicrotask)
|
||||
///
|
||||
/// <div class="warning">The task is called outside of the ownership tree, this means that if you want to access for example the context you need to reestablish the owner.</div>
|
||||
pub fn queue_microtask(task: impl FnOnce() + 'static) {
|
||||
use js_sys::{Function, Reflect};
|
||||
|
||||
@@ -265,6 +283,10 @@ 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))
|
||||
@@ -275,6 +297,10 @@ pub fn set_timeout(cb: impl FnOnce() + 'static, duration: Duration) {
|
||||
|
||||
/// Executes the given function after the given duration of time has passed, returning a cancelable handle.
|
||||
/// [`setTimeout()`](https://developer.mozilla.org/en-US/docs/Web/API/setTimeout).
|
||||
///
|
||||
/// ### 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))
|
||||
@@ -331,6 +357,10 @@ pub fn set_timeout_with_handle(
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// ### 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).
|
||||
pub fn debounce<T: 'static>(
|
||||
delay: Duration,
|
||||
mut cb: impl FnMut(T) + 'static,
|
||||
@@ -398,6 +428,10 @@ 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))
|
||||
@@ -409,6 +443,10 @@ pub fn set_interval(cb: impl Fn() + 'static, duration: 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).
|
||||
///
|
||||
/// ### 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))
|
||||
@@ -451,6 +489,10 @@ pub fn set_interval_with_handle(
|
||||
|
||||
/// Adds an event listener to the `Window`, typed as a generic `Event`,
|
||||
/// returning a cancelable handle.
|
||||
///
|
||||
/// ### 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(event_name = %event_name))
|
||||
@@ -519,6 +561,10 @@ pub fn window_event_listener_untyped(
|
||||
/// on_cleanup(move || handle.remove());
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// ### 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).
|
||||
pub fn window_event_listener<E: EventDescriptor + 'static>(
|
||||
event: E,
|
||||
cb: impl Fn(E::EventType) + 'static,
|
||||
|
||||
@@ -29,14 +29,9 @@ macro_rules! error {
|
||||
macro_rules! debug_warn {
|
||||
($($x:tt)*) => {
|
||||
{
|
||||
#[cfg(debug_assertions)]
|
||||
{
|
||||
if cfg!(debug_assertions) {
|
||||
$crate::warn!($($x)*)
|
||||
}
|
||||
#[cfg(not(debug_assertions))]
|
||||
{
|
||||
($($x)*)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "leptos_macro"
|
||||
version = "0.7.0-rc1"
|
||||
version = "0.7.5"
|
||||
authors = ["Greg Johnston"]
|
||||
license = "MIT"
|
||||
repository = "https://github.com/leptos-rs/leptos"
|
||||
@@ -13,7 +13,7 @@ edition.workspace = true
|
||||
proc-macro = true
|
||||
|
||||
[dependencies]
|
||||
attribute-derive = { version = "0.10.2", features = ["syn-full"] }
|
||||
attribute-derive = { version = "0.10.3", features = ["syn-full"] }
|
||||
cfg-if = "1.0"
|
||||
html-escape = "0.2.13"
|
||||
itertools = "0.13.0"
|
||||
@@ -27,13 +27,14 @@ leptos_hot_reload = { workspace = true }
|
||||
server_fn_macro = { workspace = true }
|
||||
convert_case = "0.6.0"
|
||||
uuid = { version = "1.11", features = ["v4"] }
|
||||
tracing = { version = "0.1.40", optional = true }
|
||||
tracing = { version = "0.1.41", optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
log = "0.4.22"
|
||||
typed-builder = "0.20.0"
|
||||
trybuild = "1.0"
|
||||
leptos = { path = "../leptos" }
|
||||
leptos_router = { path = "../router", features= ["ssr"] }
|
||||
server_fn = { path = "../server_fn", features = ["cbor"] }
|
||||
insta = "1.41"
|
||||
serde = "1.0"
|
||||
@@ -44,7 +45,8 @@ hydrate = []
|
||||
ssr = ["server_fn_macro/ssr", "leptos/ssr"]
|
||||
nightly = ["server_fn_macro/nightly"]
|
||||
tracing = ["dep:tracing"]
|
||||
experimental-islands = []
|
||||
islands = []
|
||||
trace-components = []
|
||||
trace-component-props = []
|
||||
actix = ["server_fn_macro/actix"]
|
||||
axum = ["server_fn_macro/axum"]
|
||||
@@ -83,4 +85,7 @@ skip_feature_sets = [
|
||||
rustdoc-args = ["--generate-link-to-definition"]
|
||||
|
||||
[lints.rust]
|
||||
unexpected_cfgs = { level = "warn", check-cfg = ['cfg(erase_components)'] }
|
||||
unexpected_cfgs = { level = "warn", check-cfg = [
|
||||
'cfg(leptos_debuginfo)',
|
||||
'cfg(erase_components)',
|
||||
] }
|
||||
|
||||
@@ -201,13 +201,35 @@ impl ToTokens for Model {
|
||||
) = {
|
||||
#[cfg(feature = "tracing")]
|
||||
{
|
||||
/* TODO for 0.8: fix this
|
||||
*
|
||||
* The problem is that cargo now warns about an expected "tracing" cfg if
|
||||
* you don't have a "tracing" feature in your actual crate
|
||||
*
|
||||
* However, until https://github.com/tokio-rs/tracing/pull/1819 is merged
|
||||
* (?), you can't provide an alternate path for `tracing` (for example,
|
||||
* ::leptos::tracing), which means that if you're going to use the macro
|
||||
* you *must* have `tracing` in your Cargo.toml.
|
||||
*
|
||||
* Including the feature-check here causes cargo warnings on
|
||||
* previously-working projects.
|
||||
*
|
||||
* Removing the feature-check here breaks any project that uses leptos with
|
||||
* the tracing feature turned on, but without a tracing dependency in its
|
||||
* Cargo.toml.
|
||||
* /
|
||||
*/
|
||||
let instrument = cfg!(feature = "trace-components").then(|| quote! {
|
||||
#[cfg_attr(
|
||||
feature = "tracing",
|
||||
::leptos::tracing::instrument(level = "info", name = #trace_name, skip_all)
|
||||
)]
|
||||
});
|
||||
|
||||
(
|
||||
quote! {
|
||||
#[allow(clippy::let_with_type_underscore)]
|
||||
#[cfg_attr(
|
||||
feature = "tracing",
|
||||
::leptos::tracing::instrument(level = "info", name = #trace_name, skip_all)
|
||||
)]
|
||||
#instrument
|
||||
},
|
||||
quote! {
|
||||
let __span = ::leptos::tracing::Span::current();
|
||||
@@ -260,8 +282,12 @@ impl ToTokens for Model {
|
||||
let body_name = unmodified_fn_name_from_fn_name(&body_name);
|
||||
let body_expr = if is_island {
|
||||
quote! {
|
||||
::leptos::reactive::owner::Owner::with_hydration(move || {
|
||||
#body_name(#prop_names)
|
||||
::leptos::reactive::owner::Owner::new().with(|| {
|
||||
::leptos::reactive::owner::Owner::with_hydration(move || {
|
||||
::leptos::tachys::reactive_graph::OwnedView::new({
|
||||
#body_name(#prop_names)
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
} else {
|
||||
@@ -275,7 +301,7 @@ impl ToTokens for Model {
|
||||
} else if cfg!(erase_components) {
|
||||
quote! {
|
||||
::leptos::prelude::IntoAny::into_any(
|
||||
::leptos::prelude::untrack(
|
||||
::leptos::reactive::graph::untrack_with_diagnostics(
|
||||
move || {
|
||||
#tracing_guard_expr
|
||||
#tracing_props_expr
|
||||
@@ -286,7 +312,7 @@ impl ToTokens for Model {
|
||||
}
|
||||
} else {
|
||||
quote! {
|
||||
::leptos::prelude::untrack(
|
||||
::leptos::reactive::graph::untrack_with_diagnostics(
|
||||
move || {
|
||||
#tracing_guard_expr
|
||||
#tracing_props_expr
|
||||
@@ -301,8 +327,8 @@ impl ToTokens for Model {
|
||||
let hydrate_fn_name = hydrate_fn_name.as_ref().unwrap();
|
||||
quote! {
|
||||
{
|
||||
if ::leptos::reactive::owner::Owner::current_shared_context()
|
||||
.map(|sc| sc.get_is_hydrating())
|
||||
if ::leptos::context::use_context::<::leptos::reactive::owner::IsHydrating>()
|
||||
.map(|h| h.0)
|
||||
.unwrap_or(false) {
|
||||
::leptos::either::Either::Left(
|
||||
#component
|
||||
@@ -339,9 +365,23 @@ impl ToTokens for Model {
|
||||
let children = Box::new(|| {
|
||||
let sc = ::leptos::reactive::owner::Owner::current_shared_context().unwrap();
|
||||
let prev = sc.get_is_hydrating();
|
||||
let value = ::leptos::reactive::owner::Owner::with_no_hydration(||
|
||||
::leptos::tachys::html::islands::IslandChildren::new(children()).into_any()
|
||||
);
|
||||
let owner = ::leptos::reactive::owner::Owner::new();
|
||||
let value = owner.clone().with(|| {
|
||||
::leptos::reactive::owner::Owner::with_no_hydration(move || {
|
||||
::leptos::tachys::reactive_graph::OwnedView::new({
|
||||
::leptos::tachys::html::islands::IslandChildren::new_with_on_hydrate(
|
||||
children(),
|
||||
{
|
||||
let owner = owner.clone();
|
||||
move || {
|
||||
owner.set()
|
||||
}
|
||||
}
|
||||
|
||||
)
|
||||
}).into_any()
|
||||
})
|
||||
});
|
||||
sc.set_is_hydrating(prev);
|
||||
value
|
||||
});
|
||||
@@ -424,20 +464,21 @@ impl ToTokens for Model {
|
||||
};
|
||||
let children = if is_island_with_children {
|
||||
quote! {
|
||||
.children({Box::new(|| {
|
||||
.children({
|
||||
let owner = leptos::reactive::owner::Owner::current();
|
||||
Box::new(move || {
|
||||
use leptos::tachys::view::any_view::IntoAny;
|
||||
::leptos::tachys::html::islands::IslandChildren::new(
|
||||
// TODO owner restoration for context
|
||||
()
|
||||
::leptos::tachys::html::islands::IslandChildren::new_with_on_hydrate(
|
||||
(),
|
||||
{
|
||||
let owner = owner.clone();
|
||||
move || {
|
||||
if let Some(owner) = &owner {
|
||||
owner.set()
|
||||
}
|
||||
}
|
||||
}
|
||||
).into_any()})})
|
||||
//.children(children)
|
||||
/*.children(Box::new(|| {
|
||||
use leptos::tachys::view::any_view::IntoAny;
|
||||
::leptos::tachys::html::islands::IslandChildren::new(
|
||||
// TODO owner restoration for context
|
||||
()
|
||||
).into_any()
|
||||
}))*/
|
||||
}
|
||||
} else {
|
||||
quote! {}
|
||||
@@ -655,14 +696,44 @@ impl Prop {
|
||||
abort!(e.span(), e.to_string());
|
||||
});
|
||||
|
||||
let name = if let Pat::Ident(i) = *typed.pat {
|
||||
i
|
||||
} else {
|
||||
abort!(
|
||||
typed.pat,
|
||||
"only `prop: bool` style types are allowed within the \
|
||||
`#[component]` macro"
|
||||
);
|
||||
let name = match *typed.pat {
|
||||
Pat::Ident(i) => {
|
||||
if let Some(name) = &prop_opts.name {
|
||||
PatIdent {
|
||||
attrs: vec![],
|
||||
by_ref: None,
|
||||
mutability: None,
|
||||
ident: Ident::new(name, i.span()),
|
||||
subpat: None,
|
||||
}
|
||||
} else {
|
||||
i
|
||||
}
|
||||
}
|
||||
Pat::Struct(_) | Pat::Tuple(_) | Pat::TupleStruct(_) => {
|
||||
if let Some(name) = &prop_opts.name {
|
||||
PatIdent {
|
||||
attrs: vec![],
|
||||
by_ref: None,
|
||||
mutability: None,
|
||||
ident: Ident::new(name, typed.pat.span()),
|
||||
subpat: None,
|
||||
}
|
||||
} else {
|
||||
abort!(
|
||||
typed.pat,
|
||||
"destructured props must be given a name e.g. \
|
||||
#[prop(name = \"data\")]"
|
||||
);
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
abort!(
|
||||
typed.pat,
|
||||
"only `prop: bool` style types are allowed within the \
|
||||
`#[component]` macro"
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
Self {
|
||||
@@ -865,6 +936,7 @@ struct PropOpt {
|
||||
default: Option<syn::Expr>,
|
||||
into: bool,
|
||||
attrs: bool,
|
||||
name: Option<String>,
|
||||
}
|
||||
|
||||
struct TypedBuilderOpts {
|
||||
|
||||
32
leptos_macro/src/lazy.rs
Normal file
32
leptos_macro/src/lazy.rs
Normal file
@@ -0,0 +1,32 @@
|
||||
use convert_case::{Case, Casing};
|
||||
use proc_macro::TokenStream;
|
||||
use proc_macro2::Ident;
|
||||
use proc_macro_error2::abort;
|
||||
use quote::quote;
|
||||
use syn::{spanned::Spanned, ItemFn};
|
||||
|
||||
pub fn lazy_impl(
|
||||
_args: proc_macro::TokenStream,
|
||||
s: TokenStream,
|
||||
) -> TokenStream {
|
||||
let fun = syn::parse::<ItemFn>(s).unwrap_or_else(|e| {
|
||||
abort!(e.span(), "`lazy` can only be used on a function")
|
||||
});
|
||||
if fun.sig.asyncness.is_none() {
|
||||
abort!(
|
||||
fun.sig.asyncness.span(),
|
||||
"`lazy` can only be used on an async function"
|
||||
)
|
||||
}
|
||||
|
||||
let converted_name = Ident::new(
|
||||
&fun.sig.ident.to_string().to_case(Case::Snake),
|
||||
fun.sig.ident.span(),
|
||||
);
|
||||
|
||||
quote! {
|
||||
#[cfg_attr(feature = "split", wasm_split::wasm_split(#converted_name))]
|
||||
#fun
|
||||
}
|
||||
.into()
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
//! Macros for use with the Leptos framework.
|
||||
|
||||
#![cfg_attr(feature = "nightly", feature(proc_macro_span))]
|
||||
#![forbid(unsafe_code)]
|
||||
// to prevent warnings from popping up when a nightly feature is stabilized
|
||||
@@ -5,6 +7,7 @@
|
||||
// FIXME? every use of quote! {} is warning here -- false positive?
|
||||
#![allow(unknown_lints)]
|
||||
#![allow(private_macro_use)]
|
||||
#![deny(missing_docs)]
|
||||
|
||||
#[macro_use]
|
||||
extern crate proc_macro_error2;
|
||||
@@ -20,6 +23,7 @@ mod params;
|
||||
mod view;
|
||||
use crate::component::unmodified_fn_name_from_fn_name;
|
||||
mod component;
|
||||
mod lazy;
|
||||
mod memo;
|
||||
mod slice;
|
||||
mod slot;
|
||||
@@ -269,8 +273,8 @@ pub fn view(tokens: TokenStream) -> TokenStream {
|
||||
view_macro_impl(tokens, false)
|
||||
}
|
||||
|
||||
/// The `template` macro behaves like [`view`], except that it wraps the entire tree in a
|
||||
/// [`ViewTemplate`](leptos::prelude::ViewTemplate). This optimizes creation speed by rendering
|
||||
/// The `template` macro behaves like [`view`](view!), except that it wraps the entire tree in a
|
||||
/// [`ViewTemplate`](https://docs.rs/leptos/0.7.0-gamma3/leptos/prelude/struct.ViewTemplate.html). This optimizes creation speed by rendering
|
||||
/// most of the view into a `<template>` tag with HTML rendered at compile time, then hydrating it.
|
||||
/// In exchange, there is a small binary size overhead.
|
||||
#[proc_macro_error2::proc_macro_error]
|
||||
@@ -363,7 +367,7 @@ fn normalized_call_site(site: proc_macro::Span) -> Option<String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// This behaves like the [`view`] macro, but loads the view from an external file instead of
|
||||
/// This behaves like the [`view`](view!) macro, but loads the view from an external file instead of
|
||||
/// parsing it inline.
|
||||
///
|
||||
/// This is designed to allow editing views in a separate file, if this improves a user's workflow.
|
||||
@@ -556,10 +560,10 @@ pub fn component(args: proc_macro::TokenStream, s: TokenStream) -> TokenStream {
|
||||
}
|
||||
|
||||
/// Defines a component as an interactive island when you are using the
|
||||
/// `experimental-islands` feature of Leptos. Apart from the macro name,
|
||||
/// `islands` feature of Leptos. Apart from the macro name,
|
||||
/// the API is the same as the [`component`](macro@component) macro.
|
||||
///
|
||||
/// When you activate the `experimental-islands` feature, every `#[component]`
|
||||
/// When you activate the `islands` feature, every `#[component]`
|
||||
/// is server-only by default. This "default to server" behavior is important:
|
||||
/// you opt into shipping code to the client, rather than opting out. You can
|
||||
/// opt into client-side interactivity for any given component by changing from
|
||||
@@ -636,7 +640,7 @@ pub fn island(args: proc_macro::TokenStream, s: TokenStream) -> TokenStream {
|
||||
abort!(
|
||||
transparent,
|
||||
"only `transparent` is supported";
|
||||
help = "try `#[component(transparent)]` or `#[component]`"
|
||||
help = "try `#[island(transparent)]` or `#[island]`"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -999,3 +1003,17 @@ pub fn slice(input: TokenStream) -> TokenStream {
|
||||
pub fn memo(input: TokenStream) -> TokenStream {
|
||||
memo::memo_impl(input)
|
||||
}
|
||||
|
||||
/// The `#[lazy]` macro marks an `async` function as a function that can be lazy-loaded from a
|
||||
/// separate (WebAssembly) binary.
|
||||
///
|
||||
/// The first time the function is called, calling the function will first load that other binary,
|
||||
/// then call the function. On subsequent call it will be called immediately, but still return
|
||||
/// asynchronously to maintain the same API.
|
||||
///
|
||||
/// All parameters and output types should be concrete types, with no generics.
|
||||
#[proc_macro_attribute]
|
||||
#[proc_macro_error]
|
||||
pub fn lazy(args: proc_macro::TokenStream, s: TokenStream) -> TokenStream {
|
||||
lazy::lazy_impl(args, s)
|
||||
}
|
||||
|
||||
@@ -13,7 +13,13 @@ pub fn params_impl(ast: &syn::DeriveInput) -> proc_macro::TokenStream {
|
||||
.named
|
||||
.iter()
|
||||
.map(|field| {
|
||||
let field_name_string = &field.ident.as_ref().expect("expected named struct fields").to_string();
|
||||
let field_name_string = &field
|
||||
.ident
|
||||
.as_ref()
|
||||
.expect("expected named struct fields")
|
||||
.to_string()
|
||||
.trim_start_matches("r#")
|
||||
.to_owned();
|
||||
let ident = &field.ident;
|
||||
let ty = &field.ty;
|
||||
let span = field.span();
|
||||
|
||||
@@ -108,9 +108,12 @@ pub(crate) fn component_to_tokens(
|
||||
let KeyedAttributeValue::Binding(binding) = &attr.possible_value
|
||||
else {
|
||||
if let Some(ident) = attr.key.to_string().strip_prefix("let:") {
|
||||
let ident1 =
|
||||
format_ident!("{ident}", span = attr.key.span());
|
||||
return Some(quote! { #ident1 });
|
||||
let span = match &attr.key {
|
||||
NodeName::Punctuated(path) => path[1].span(),
|
||||
_ => unreachable!(),
|
||||
};
|
||||
let ident1 = format_ident!("{ident}", span = span);
|
||||
return Some(quote_spanned! { span => #ident1 });
|
||||
} else {
|
||||
return None;
|
||||
}
|
||||
@@ -168,7 +171,7 @@ pub(crate) fn component_to_tokens(
|
||||
|
||||
let spreads = (!(spreads.is_empty())).then(|| {
|
||||
quote! {
|
||||
.add_any_attr((#(#spreads,)*))
|
||||
.add_any_attr((#(#spreads,)*).into_attr())
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -197,7 +197,7 @@ enum InertElementBuilder<'a> {
|
||||
},
|
||||
}
|
||||
|
||||
impl<'a> ToTokens for InertElementBuilder<'a> {
|
||||
impl ToTokens for InertElementBuilder<'_> {
|
||||
fn to_tokens(&self, tokens: &mut TokenStream) {
|
||||
match self {
|
||||
InertElementBuilder::GlobalClass { strs, .. } => {
|
||||
@@ -219,7 +219,7 @@ enum GlobalClassItem<'a> {
|
||||
String(String),
|
||||
}
|
||||
|
||||
impl<'a> ToTokens for GlobalClassItem<'a> {
|
||||
impl ToTokens for GlobalClassItem<'_> {
|
||||
fn to_tokens(&self, tokens: &mut TokenStream) {
|
||||
let addl_tokens = match self {
|
||||
GlobalClassItem::Global(v) => v.to_token_stream(),
|
||||
@@ -652,6 +652,18 @@ pub(crate) fn element_to_tokens(
|
||||
},
|
||||
_ => None,
|
||||
};
|
||||
|
||||
if let NodeAttribute::Attribute(a) = a {
|
||||
if let Some(Tuple(_)) = a.value() {
|
||||
return Ordering::Greater;
|
||||
}
|
||||
}
|
||||
if let NodeAttribute::Attribute(b) = b {
|
||||
if let Some(Tuple(_)) = b.value() {
|
||||
return Ordering::Less;
|
||||
}
|
||||
}
|
||||
|
||||
match (key_a.as_deref(), key_b.as_deref()) {
|
||||
(Some("class"), Some("class")) | (Some("style"), Some("style")) => {
|
||||
Ordering::Equal
|
||||
@@ -755,7 +767,7 @@ pub(crate) fn element_to_tokens(
|
||||
let name = node.name().to_string();
|
||||
// link custom ident to name span for IDE docs
|
||||
let custom = Ident::new("custom", name.span());
|
||||
quote! { ::leptos::tachys::html::element::#custom(#name) }
|
||||
quote_spanned! { node.name().span() => ::leptos::tachys::html::element::#custom(#name) }
|
||||
} else if is_svg_element(&tag) {
|
||||
parent_type = TagType::Svg;
|
||||
let name = if tag == "use" || tag == "use_" {
|
||||
@@ -763,33 +775,33 @@ pub(crate) fn element_to_tokens(
|
||||
} else {
|
||||
name.to_token_stream()
|
||||
};
|
||||
quote! { ::leptos::tachys::svg::#name() }
|
||||
quote_spanned! { node.name().span() => ::leptos::tachys::svg::#name() }
|
||||
} else if is_math_ml_element(&tag) {
|
||||
parent_type = TagType::Math;
|
||||
quote! { ::leptos::tachys::mathml::#name() }
|
||||
quote_spanned! { node.name().span() => ::leptos::tachys::mathml::#name() }
|
||||
} else if is_ambiguous_element(&tag) {
|
||||
match parent_type {
|
||||
TagType::Unknown => {
|
||||
// We decided this warning was too aggressive, but I'll leave it here in case we want it later
|
||||
/* proc_macro_error2::emit_warning!(name.span(), "The view macro is assuming this is an HTML element, \
|
||||
but it is ambiguous; if it is an SVG or MathML element, prefix with svg:: or math::"); */
|
||||
quote! {
|
||||
quote_spanned! { node.name().span() =>
|
||||
::leptos::tachys::html::element::#name()
|
||||
}
|
||||
}
|
||||
TagType::Html => {
|
||||
quote! { ::leptos::tachys::html::element::#name() }
|
||||
quote_spanned! { node.name().span() => ::leptos::tachys::html::element::#name() }
|
||||
}
|
||||
TagType::Svg => {
|
||||
quote! { ::leptos::tachys::svg::#name() }
|
||||
quote_spanned! { node.name().span() => ::leptos::tachys::svg::#name() }
|
||||
}
|
||||
TagType::Math => {
|
||||
quote! { ::leptos::tachys::math::#name() }
|
||||
quote_spanned! { node.name().span() => ::leptos::tachys::math::#name() }
|
||||
}
|
||||
}
|
||||
} else {
|
||||
parent_type = TagType::Html;
|
||||
quote! { ::leptos::tachys::html::element::#name() }
|
||||
quote_spanned! { name.span() => ::leptos::tachys::html::element::#name() }
|
||||
};
|
||||
|
||||
/* TODO restore this
|
||||
@@ -1117,6 +1129,11 @@ pub(crate) fn attribute_absolute(
|
||||
::leptos::tachys::html::attribute::custom::custom_attribute(#name, #value)
|
||||
}
|
||||
}
|
||||
else if name == "node_ref" {
|
||||
quote! {
|
||||
::leptos::tachys::html::node_ref::#key(#value)
|
||||
}
|
||||
}
|
||||
else {
|
||||
quote! {
|
||||
::leptos::tachys::html::attribute::#key(#value)
|
||||
@@ -1639,7 +1656,7 @@ pub(crate) fn ident_from_tag_name(tag_name: &NodeName) -> Ident {
|
||||
.path
|
||||
.segments
|
||||
.iter()
|
||||
.last()
|
||||
.next_back()
|
||||
.map(|segment| segment.ident.clone())
|
||||
.expect("element needs to have a name"),
|
||||
NodeName::Block(_) => {
|
||||
@@ -1710,7 +1727,7 @@ fn tuple_name(name: &str, node: &KeyedAttribute) -> TupleName {
|
||||
TupleName::None
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
enum TupleName {
|
||||
None,
|
||||
Str(String),
|
||||
|
||||
@@ -1,6 +1,15 @@
|
||||
use core::num::NonZeroUsize;
|
||||
use leptos::prelude::*;
|
||||
|
||||
#[derive(PartialEq, Debug)]
|
||||
struct UserInfo {
|
||||
user_id: String,
|
||||
email: String,
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Debug)]
|
||||
struct Admin(bool);
|
||||
|
||||
#[component]
|
||||
fn Component(
|
||||
#[prop(optional)] optional: bool,
|
||||
@@ -10,6 +19,10 @@ fn Component(
|
||||
#[prop(default = NonZeroUsize::new(10).unwrap())] default: NonZeroUsize,
|
||||
#[prop(into)] into: String,
|
||||
impl_trait: impl Fn() -> i32 + 'static,
|
||||
#[prop(name = "data")] UserInfo { email, user_id }: UserInfo,
|
||||
#[prop(name = "tuple")] (name, id): (String, i32),
|
||||
#[prop(name = "tuple_struct")] Admin(is_admin): Admin,
|
||||
#[prop(name = "outside_name")] inside_name: i32,
|
||||
) -> impl IntoView {
|
||||
_ = optional;
|
||||
_ = optional_into;
|
||||
@@ -18,6 +31,12 @@ fn Component(
|
||||
_ = default;
|
||||
_ = into;
|
||||
_ = impl_trait;
|
||||
_ = email;
|
||||
_ = user_id;
|
||||
_ = id;
|
||||
_ = name;
|
||||
_ = is_admin;
|
||||
_ = inside_name;
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -26,6 +45,13 @@ fn component() {
|
||||
.into("")
|
||||
.strip_option(9)
|
||||
.impl_trait(|| 42)
|
||||
.data(UserInfo {
|
||||
email: "em@il".into(),
|
||||
user_id: "1".into(),
|
||||
})
|
||||
.tuple(("Joe".into(), 12))
|
||||
.tuple_struct(Admin(true))
|
||||
.outside_name(1)
|
||||
.build();
|
||||
assert!(!cp.optional);
|
||||
assert_eq!(cp.optional_into, None);
|
||||
@@ -34,6 +60,16 @@ fn component() {
|
||||
assert_eq!(cp.default, NonZeroUsize::new(10).unwrap());
|
||||
assert_eq!(cp.into, "");
|
||||
assert_eq!((cp.impl_trait)(), 42);
|
||||
assert_eq!(
|
||||
cp.data,
|
||||
UserInfo {
|
||||
email: "em@il".into(),
|
||||
user_id: "1".into(),
|
||||
}
|
||||
);
|
||||
assert_eq!(cp.tuple, ("Joe".into(), 12));
|
||||
assert_eq!(cp.tuple_struct, Admin(true));
|
||||
assert_eq!(cp.outside_name, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -45,12 +81,26 @@ fn component_nostrip() {
|
||||
strip_option=9
|
||||
into=""
|
||||
impl_trait=|| 42
|
||||
data=UserInfo {
|
||||
email: "em@il".into(),
|
||||
user_id: "1".into(),
|
||||
}
|
||||
tuple=("Joe".into(), 12)
|
||||
tuple_struct=Admin(true)
|
||||
outside_name=1
|
||||
/>
|
||||
<Component
|
||||
nostrip:optional_into=Some("foo")
|
||||
strip_option=9
|
||||
into=""
|
||||
impl_trait=|| 42
|
||||
data=UserInfo {
|
||||
email: "em@il".into(),
|
||||
user_id: "1".into(),
|
||||
}
|
||||
tuple=("Joe".into(), 12)
|
||||
tuple_struct=Admin(true)
|
||||
outside_name=1
|
||||
/>
|
||||
};
|
||||
}
|
||||
|
||||
28
leptos_macro/tests/params.rs
Normal file
28
leptos_macro/tests/params.rs
Normal file
@@ -0,0 +1,28 @@
|
||||
use leptos::prelude::*;
|
||||
use leptos_router::params::Params;
|
||||
|
||||
#[derive(PartialEq, Debug, Params)]
|
||||
struct UserInfo {
|
||||
user_id: Option<String>,
|
||||
email: Option<String>,
|
||||
r#type: Option<i32>,
|
||||
not_found: Option<i32>,
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn params_test() {
|
||||
let mut map = leptos_router::params::ParamsMap::new();
|
||||
map.insert("user_id", "12".to_owned());
|
||||
map.insert("email", "em@il".to_owned());
|
||||
map.insert("type", "12".to_owned());
|
||||
let user_info = UserInfo::from_map(&map).unwrap();
|
||||
assert_eq!(
|
||||
UserInfo {
|
||||
email: Some("em@il".to_owned()),
|
||||
user_id: Some("12".to_owned()),
|
||||
r#type: Some(12),
|
||||
not_found: None,
|
||||
},
|
||||
user_info
|
||||
);
|
||||
}
|
||||
@@ -44,4 +44,10 @@ fn default_with_invalid_value(
|
||||
_ = default;
|
||||
}
|
||||
|
||||
#[component]
|
||||
fn destructure_without_name((default, value): (bool, i32)) -> impl IntoView {
|
||||
_ = default;
|
||||
_ = value;
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
error: supported fields are `optional`, `optional_no_strip`, `strip_option`, `default`, `into` and `attrs`
|
||||
error: supported fields are `optional`, `optional_no_strip`, `strip_option`, `default`, `into`, `attrs` and `name`
|
||||
--> tests/ui/component.rs:10:31
|
||||
|
|
||||
10 | fn unknown_prop_option(#[prop(hello)] test: bool) -> impl IntoView {
|
||||
@@ -41,3 +41,9 @@ error: unexpected end of input, expected one of: identifier, `::`, `<`, `_`, lit
|
||||
| ^^^^^^^^^^^^
|
||||
|
|
||||
= note: this error originates in the attribute macro `component` (in Nightly builds, run with -Z macro-backtrace for more info)
|
||||
|
||||
error: destructured props must be given a name e.g. #[prop(name = "data")]
|
||||
--> tests/ui/component.rs:48:29
|
||||
|
|
||||
48 | fn destructure_without_name((default, value): (bool, i32)) -> impl IntoView {
|
||||
| ^^^^^^^^^^^^^^^^
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
error: supported fields are `optional`, `optional_no_strip`, `strip_option`, `default`, `into` and `attrs`
|
||||
error: supported fields are `optional`, `optional_no_strip`, `strip_option`, `default`, `into`, `attrs` and `name`
|
||||
--> tests/ui/component_absolute.rs:5:31
|
||||
|
|
||||
5 | fn unknown_prop_option(#[prop(hello)] test: bool) -> impl ::leptos::IntoView {
|
||||
|
||||
@@ -11,11 +11,11 @@ edition.workspace = true
|
||||
|
||||
[dependencies]
|
||||
base64 = "0.22.1"
|
||||
codee = { version = "0.2.0", features = ["json_serde"] }
|
||||
codee = { version = "0.3.0", features = ["json_serde"] }
|
||||
hydration_context = { workspace = true }
|
||||
reactive_graph = { workspace = true, features = ["hydration"] }
|
||||
server_fn = { workspace = true }
|
||||
tracing = { version = "0.1.40", optional = true }
|
||||
tracing = { version = "0.1.41", optional = true }
|
||||
futures = "0.3.31"
|
||||
|
||||
any_spawner = { workspace = true }
|
||||
@@ -25,8 +25,8 @@ send_wrapper = "0.6"
|
||||
|
||||
# serialization formats
|
||||
serde = { version = "1.0" }
|
||||
js-sys = { version = "0.3.72", optional = true }
|
||||
wasm-bindgen = { version = "0.2.95", optional = true }
|
||||
js-sys = { version = "0.3.74", optional = true }
|
||||
wasm-bindgen = { version = "0.2.97", optional = true }
|
||||
serde_json = { version = "1.0" }
|
||||
|
||||
[features]
|
||||
@@ -44,3 +44,6 @@ denylist = ["tracing"]
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
rustdoc-args = ["--generate-link-to-definition"]
|
||||
|
||||
[lints.rust]
|
||||
unexpected_cfgs = { level = "warn", check-cfg = ['cfg(leptos_debuginfo)'] }
|
||||
@@ -6,6 +6,10 @@ use reactive_graph::{
|
||||
use server_fn::{error::ServerFnErrorSerde, ServerFn, ServerFnError};
|
||||
use std::{ops::Deref, panic::Location, sync::Arc};
|
||||
|
||||
/// An error that can be caused by a server action.
|
||||
///
|
||||
/// This is used for propagating errors from the server to the client when JS/WASM are not
|
||||
/// supported.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ServerActionError {
|
||||
path: Arc<str>,
|
||||
@@ -13,6 +17,7 @@ pub struct ServerActionError {
|
||||
}
|
||||
|
||||
impl ServerActionError {
|
||||
/// Creates a new error associated with the given path.
|
||||
pub fn new(path: &str, err: &str) -> Self {
|
||||
Self {
|
||||
path: path.into(),
|
||||
@@ -20,22 +25,25 @@ impl ServerActionError {
|
||||
}
|
||||
}
|
||||
|
||||
/// The path with which this error is associated.
|
||||
pub fn path(&self) -> &str {
|
||||
&self.path
|
||||
}
|
||||
|
||||
/// The error message.
|
||||
pub fn err(&self) -> &str {
|
||||
&self.err
|
||||
}
|
||||
}
|
||||
|
||||
/// An [`ArcAction`] that can be used to call a server function.
|
||||
pub struct ArcServerAction<S>
|
||||
where
|
||||
S: ServerFn + 'static,
|
||||
S::Output: 'static,
|
||||
{
|
||||
inner: ArcAction<S, Result<S::Output, ServerFnError<S::Error>>>,
|
||||
#[cfg(debug_assertions)]
|
||||
#[cfg(any(debug_assertions, leptos_debuginfo))]
|
||||
defined_at: &'static Location<'static>,
|
||||
}
|
||||
|
||||
@@ -45,6 +53,7 @@ where
|
||||
S::Output: Send + Sync + 'static,
|
||||
S::Error: Send + Sync + 'static,
|
||||
{
|
||||
/// Creates a new [`ArcAction`] that will call the server function `S` when dispatched.
|
||||
#[track_caller]
|
||||
pub fn new() -> Self {
|
||||
let err = use_context::<ServerActionError>().and_then(|error| {
|
||||
@@ -56,7 +65,7 @@ where
|
||||
inner: ArcAction::new_with_value(err, |input: &S| {
|
||||
S::run_on_client(input.clone())
|
||||
}),
|
||||
#[cfg(debug_assertions)]
|
||||
#[cfg(any(debug_assertions, leptos_debuginfo))]
|
||||
defined_at: Location::caller(),
|
||||
}
|
||||
}
|
||||
@@ -82,7 +91,7 @@ where
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
inner: self.inner.clone(),
|
||||
#[cfg(debug_assertions)]
|
||||
#[cfg(any(debug_assertions, leptos_debuginfo))]
|
||||
defined_at: self.defined_at,
|
||||
}
|
||||
}
|
||||
@@ -105,24 +114,25 @@ where
|
||||
S::Output: 'static,
|
||||
{
|
||||
fn defined_at(&self) -> Option<&'static Location<'static>> {
|
||||
#[cfg(debug_assertions)]
|
||||
#[cfg(any(debug_assertions, leptos_debuginfo))]
|
||||
{
|
||||
Some(self.defined_at)
|
||||
}
|
||||
#[cfg(not(debug_assertions))]
|
||||
#[cfg(not(any(debug_assertions, leptos_debuginfo)))]
|
||||
{
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An [`Action`] that can be used to call a server function.
|
||||
pub struct ServerAction<S>
|
||||
where
|
||||
S: ServerFn + 'static,
|
||||
S::Output: 'static,
|
||||
{
|
||||
inner: Action<S, Result<S::Output, ServerFnError<S::Error>>>,
|
||||
#[cfg(debug_assertions)]
|
||||
#[cfg(any(debug_assertions, leptos_debuginfo))]
|
||||
defined_at: &'static Location<'static>,
|
||||
}
|
||||
|
||||
@@ -132,6 +142,7 @@ where
|
||||
S::Output: Send + Sync + 'static,
|
||||
S::Error: Send + Sync + 'static,
|
||||
{
|
||||
/// Creates a new [`Action`] that will call the server function `S` when dispatched.
|
||||
pub fn new() -> Self {
|
||||
let err = use_context::<ServerActionError>().and_then(|error| {
|
||||
(error.path() == S::PATH)
|
||||
@@ -142,7 +153,7 @@ where
|
||||
inner: Action::new_with_value(err, |input: &S| {
|
||||
S::run_on_client(input.clone())
|
||||
}),
|
||||
#[cfg(debug_assertions)]
|
||||
#[cfg(any(debug_assertions, leptos_debuginfo))]
|
||||
defined_at: Location::caller(),
|
||||
}
|
||||
}
|
||||
@@ -206,11 +217,11 @@ where
|
||||
S::Output: 'static,
|
||||
{
|
||||
fn defined_at(&self) -> Option<&'static Location<'static>> {
|
||||
#[cfg(debug_assertions)]
|
||||
#[cfg(any(debug_assertions, leptos_debuginfo))]
|
||||
{
|
||||
Some(self.defined_at)
|
||||
}
|
||||
#[cfg(not(debug_assertions))]
|
||||
#[cfg(not(any(debug_assertions, leptos_debuginfo)))]
|
||||
{
|
||||
None
|
||||
}
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
//#![deny(missing_docs)]
|
||||
//! Utilities for communicating between the server and the client with Leptos.
|
||||
|
||||
#![deny(missing_docs)]
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
mod action;
|
||||
@@ -13,135 +15,25 @@ pub use once_resource::*;
|
||||
mod resource;
|
||||
pub use resource::*;
|
||||
mod shared;
|
||||
////! # Leptos Server Functions
|
||||
////!
|
||||
////! This package is based on a simple idea: sometimes it’s useful to write functions
|
||||
////! that will only run on the server, and call them from the client.
|
||||
////!
|
||||
////! If you’re creating anything beyond a toy app, you’ll need to do this all the time:
|
||||
////! reading from or writing to a database that only runs on the server, running expensive
|
||||
////! computations using libraries you don’t want to ship down to the client, accessing
|
||||
////! APIs that need to be called from the server rather than the client for CORS reasons
|
||||
////! or because you need a secret API key that’s stored on the server and definitely
|
||||
////! shouldn’t be shipped down to a user’s browser.
|
||||
////!
|
||||
////! Traditionally, this is done by separating your server and client code, and by setting
|
||||
////! up something like a REST API or GraphQL API to allow your client to fetch and mutate
|
||||
////! data on the server. This is fine, but it requires you to write and maintain your code
|
||||
////! in multiple separate places (client-side code for fetching, server-side functions to run),
|
||||
////! as well as creating a third thing to manage, which is the API contract between the two.
|
||||
////!
|
||||
////! This package provides two simple primitives that allow you instead to write co-located,
|
||||
////! isomorphic server functions. (*Co-located* means you can write them in your app code so
|
||||
////! that they are “located alongside” the client code that calls them, rather than separating
|
||||
////! the client and server sides. *Isomorphic* means you can call them from the client as if
|
||||
////! you were simply calling a function; the function call has the “same shape” on the client
|
||||
////! as it does on the server.)
|
||||
////!
|
||||
////! ### `#[server]`
|
||||
////!
|
||||
////! The [`#[server]`](https://docs.rs/leptos/latest/leptos/attr.server.html) macro allows you to annotate a function to
|
||||
////! indicate that it should only run on the server (i.e., when you have an `ssr` feature in your
|
||||
////! crate that is enabled).
|
||||
////!
|
||||
////! ```rust,ignore
|
||||
////! use leptos::prelude::*;
|
||||
////! #[server(ReadFromDB)]
|
||||
////! async fn read_posts(how_many: usize, query: String) -> Result<Vec<Posts>, ServerFnError> {
|
||||
////! // do some server-only work here to access the database
|
||||
////! let posts = todo!();;
|
||||
////! Ok(posts)
|
||||
////! }
|
||||
////!
|
||||
////! // call the function
|
||||
////! spawn_local(async {
|
||||
////! let posts = read_posts(3, "my search".to_string()).await;
|
||||
////! log::debug!("posts = {posts:#?}");
|
||||
////! });
|
||||
////! ```
|
||||
////!
|
||||
////! If you call this function from the client, it will serialize the function arguments and `POST`
|
||||
////! them to the server as if they were the inputs in `<form method="POST">`.
|
||||
////!
|
||||
////! Here’s what you need to remember:
|
||||
////! - **Server functions must be `async`.** Even if the work being done inside the function body
|
||||
////! can run synchronously on the server, from the client’s perspective it involves an asynchronous
|
||||
////! function call.
|
||||
////! - **Server functions must return `Result<T, ServerFnError>`.** Even if the work being done
|
||||
////! inside the function body can’t fail, the processes of serialization/deserialization and the
|
||||
////! network call are fallible.
|
||||
////! - **Return types must be [Serializable](leptos_reactive::Serializable).**
|
||||
////! This should be fairly obvious: we have to serialize arguments to send them to the server, and we
|
||||
////! need to deserialize the result to return it to the client.
|
||||
////! - **Arguments must be implement [serde::Serialize].** They are serialized as an `application/x-www-form-urlencoded`
|
||||
////! form data using [`serde_qs`](https://docs.rs/serde_qs/latest/serde_qs/) or as `application/cbor`
|
||||
////! using [`cbor`](https://docs.rs/cbor/latest/cbor/). **Note**: You should explicitly include `serde` with the
|
||||
////! `derive` feature enabled in your `Cargo.toml`. You can do this by running `cargo add serde --features=derive`.
|
||||
////! - Context comes from the server. [`use_context`](leptos_reactive::use_context) can be used to access specific
|
||||
////! server-related data, as documented in the server integrations. This allows accessing things like HTTP request
|
||||
////! headers as needed. However, server functions *not* have access to reactive state that exists in the client.
|
||||
////!
|
||||
////! ## Server Function Encodings
|
||||
////!
|
||||
////! By default, the server function call is a `POST` request that serializes the arguments as URL-encoded form data in the body
|
||||
////! of the request. But there are a few other methods supported. Optionally, we can provide another argument to the `#[server]`
|
||||
////! macro to specify an alternate encoding:
|
||||
////!
|
||||
////! ```rust,ignore
|
||||
////! #[server(AddTodo, "/api", "Url")]
|
||||
////! #[server(AddTodo, "/api", "GetJson")]
|
||||
////! #[server(AddTodo, "/api", "Cbor")]
|
||||
////! #[server(AddTodo, "/api", "GetCbor")]
|
||||
////! ```
|
||||
////!
|
||||
////! The four options use different combinations of HTTP verbs and encoding methods:
|
||||
////!
|
||||
////! | Name | Method | Request | Response |
|
||||
////! | ----------------- | ------ | ----------- | -------- |
|
||||
////! | **Url** (default) | POST | URL encoded | JSON |
|
||||
////! | **GetJson** | GET | URL encoded | JSON |
|
||||
////! | **Cbor** | POST | CBOR | CBOR |
|
||||
////! | **GetCbor** | GET | URL encoded | CBOR |
|
||||
////!
|
||||
////! In other words, you have two choices:
|
||||
////!
|
||||
////! - `GET` or `POST`? This has implications for things like browser or CDN caching; while `POST` requests should not be cached,
|
||||
////! `GET` requests can be.
|
||||
////! - Plain text (arguments sent with URL/form encoding, results sent as JSON) or a binary format (CBOR, encoded as a base64
|
||||
////! string)?
|
||||
////!
|
||||
////! ## Why not `PUT` or `DELETE`? Why URL/form encoding, and not JSON?**
|
||||
////!
|
||||
////! These are reasonable questions. Much of the web is built on REST API patterns that encourage the use of semantic HTTP
|
||||
////! methods like `DELETE` to delete an item from a database, and many devs are accustomed to sending data to APIs in the
|
||||
////! JSON format.
|
||||
////!
|
||||
////! The reason we use `POST` or `GET` with URL-encoded data by default is the `<form>` support. For better or for worse,
|
||||
////! HTML forms don’t support `PUT` or `DELETE`, and they don’t support sending JSON. This means that if you use anything
|
||||
////! but a `GET` or `POST` request with URL-encoded data, it can only work once WASM has loaded.
|
||||
////!
|
||||
////! The CBOR encoding is supported for historical reasons; an earlier version of server functions used a URL encoding that
|
||||
////! didn’t support nested objects like structs or vectors as server function arguments, which CBOR did. But note that the
|
||||
////! CBOR forms encounter the same issue as `PUT`, `DELETE`, or JSON: they do not degrade gracefully if the WASM version of
|
||||
////! your app is not available.
|
||||
|
||||
//pub use server_fn::{error::ServerFnErrorErr, ServerFnError};
|
||||
|
||||
//mod action;
|
||||
//mod multi_action;
|
||||
//pub use action::*;
|
||||
//pub use multi_action::*;
|
||||
//extern crate tracing;
|
||||
use base64::{engine::general_purpose::STANDARD_NO_PAD, DecodeError, Engine};
|
||||
pub use shared::*;
|
||||
|
||||
/// Encodes data into a string.
|
||||
pub trait IntoEncodedString {
|
||||
/// Encodes the data.
|
||||
fn into_encoded_string(self) -> String;
|
||||
}
|
||||
|
||||
/// Decodes data from a string.
|
||||
pub trait FromEncodedStr {
|
||||
/// The decoded data.
|
||||
type DecodedType<'a>: Borrow<Self>;
|
||||
|
||||
/// The type of an error encountered during decoding.
|
||||
type DecodingError;
|
||||
|
||||
/// Decodes the string.
|
||||
fn from_encoded_str(
|
||||
data: &str,
|
||||
) -> Result<Self::DecodedType<'_>, Self::DecodingError>;
|
||||
|
||||
@@ -8,8 +8,11 @@ use reactive_graph::{
|
||||
ToAnySource, ToAnySubscriber,
|
||||
},
|
||||
owner::use_context,
|
||||
signal::guards::{AsyncPlain, ReadGuard},
|
||||
traits::{DefinedAt, IsDisposed, ReadUntracked},
|
||||
signal::{
|
||||
guards::{AsyncPlain, ReadGuard},
|
||||
ArcRwSignal, RwSignal,
|
||||
},
|
||||
traits::{DefinedAt, IsDisposed, ReadUntracked, Track, Update, Write},
|
||||
};
|
||||
use send_wrapper::SendWrapper;
|
||||
use std::{
|
||||
@@ -17,9 +20,11 @@ use std::{
|
||||
panic::Location,
|
||||
};
|
||||
|
||||
/// A reference-counted resource that only loads its data locally on the client.
|
||||
pub struct ArcLocalResource<T> {
|
||||
data: ArcAsyncDerived<SendWrapper<T>>,
|
||||
#[cfg(debug_assertions)]
|
||||
refetch: ArcRwSignal<usize>,
|
||||
#[cfg(any(debug_assertions, leptos_debuginfo))]
|
||||
defined_at: &'static Location<'static>,
|
||||
}
|
||||
|
||||
@@ -27,13 +32,18 @@ impl<T> Clone for ArcLocalResource<T> {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
data: self.data.clone(),
|
||||
#[cfg(debug_assertions)]
|
||||
refetch: self.refetch.clone(),
|
||||
#[cfg(any(debug_assertions, leptos_debuginfo))]
|
||||
defined_at: self.defined_at,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> ArcLocalResource<T> {
|
||||
/// Creates the resource.
|
||||
///
|
||||
/// This will only begin loading data if you are on the client (i.e., if you do not have the
|
||||
/// `ssr` feature activated).
|
||||
#[track_caller]
|
||||
pub fn new<Fut>(fetcher: impl Fn() -> Fut + 'static) -> Self
|
||||
where
|
||||
@@ -60,15 +70,27 @@ impl<T> ArcLocalResource<T> {
|
||||
}
|
||||
};
|
||||
let fetcher = SendWrapper::new(fetcher);
|
||||
Self {
|
||||
data: ArcAsyncDerived::new(move || {
|
||||
let refetch = ArcRwSignal::new(0);
|
||||
let data = {
|
||||
let refetch = refetch.clone();
|
||||
ArcAsyncDerived::new(move || {
|
||||
refetch.track();
|
||||
let fut = fetcher();
|
||||
SendWrapper::new(async move { SendWrapper::new(fut.await) })
|
||||
}),
|
||||
#[cfg(debug_assertions)]
|
||||
})
|
||||
};
|
||||
Self {
|
||||
data,
|
||||
refetch,
|
||||
#[cfg(any(debug_assertions, leptos_debuginfo))]
|
||||
defined_at: Location::caller(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Re-runs the async function.
|
||||
pub fn refetch(&self) {
|
||||
*self.refetch.write() += 1;
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> IntoFuture for ArcLocalResource<T>
|
||||
@@ -99,11 +121,11 @@ where
|
||||
|
||||
impl<T> DefinedAt for ArcLocalResource<T> {
|
||||
fn defined_at(&self) -> Option<&'static Location<'static>> {
|
||||
#[cfg(debug_assertions)]
|
||||
#[cfg(any(debug_assertions, leptos_debuginfo))]
|
||||
{
|
||||
Some(self.defined_at)
|
||||
}
|
||||
#[cfg(not(debug_assertions))]
|
||||
#[cfg(not(any(debug_assertions, leptos_debuginfo)))]
|
||||
{
|
||||
None
|
||||
}
|
||||
@@ -192,9 +214,11 @@ impl<T> Subscriber for ArcLocalResource<T> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A resource that only loads its data locally on the client.
|
||||
pub struct LocalResource<T> {
|
||||
data: AsyncDerived<SendWrapper<T>>,
|
||||
#[cfg(debug_assertions)]
|
||||
refetch: RwSignal<usize>,
|
||||
#[cfg(any(debug_assertions, leptos_debuginfo))]
|
||||
defined_at: &'static Location<'static>,
|
||||
}
|
||||
|
||||
@@ -207,6 +231,10 @@ impl<T> Clone for LocalResource<T> {
|
||||
impl<T> Copy for LocalResource<T> {}
|
||||
|
||||
impl<T> LocalResource<T> {
|
||||
/// Creates the resource.
|
||||
///
|
||||
/// This will only begin loading data if you are on the client (i.e., if you do not have the
|
||||
/// `ssr` feature activated).
|
||||
#[track_caller]
|
||||
pub fn new<Fut>(fetcher: impl Fn() -> Fut + 'static) -> Self
|
||||
where
|
||||
@@ -232,6 +260,7 @@ impl<T> LocalResource<T> {
|
||||
}
|
||||
}
|
||||
};
|
||||
let refetch = RwSignal::new(0);
|
||||
|
||||
Self {
|
||||
data: if cfg!(feature = "ssr") {
|
||||
@@ -239,14 +268,21 @@ impl<T> LocalResource<T> {
|
||||
} else {
|
||||
let fetcher = SendWrapper::new(fetcher);
|
||||
AsyncDerived::new(move || {
|
||||
refetch.track();
|
||||
let fut = fetcher();
|
||||
SendWrapper::new(async move { SendWrapper::new(fut.await) })
|
||||
})
|
||||
},
|
||||
#[cfg(debug_assertions)]
|
||||
refetch,
|
||||
#[cfg(any(debug_assertions, leptos_debuginfo))]
|
||||
defined_at: Location::caller(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Re-runs the async function.
|
||||
pub fn refetch(&self) {
|
||||
self.refetch.try_update(|n| *n += 1);
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> IntoFuture for LocalResource<T>
|
||||
@@ -277,11 +313,11 @@ where
|
||||
|
||||
impl<T> DefinedAt for LocalResource<T> {
|
||||
fn defined_at(&self) -> Option<&'static Location<'static>> {
|
||||
#[cfg(debug_assertions)]
|
||||
#[cfg(any(debug_assertions, leptos_debuginfo))]
|
||||
{
|
||||
Some(self.defined_at)
|
||||
}
|
||||
#[cfg(not(debug_assertions))]
|
||||
#[cfg(not(any(debug_assertions, leptos_debuginfo)))]
|
||||
{
|
||||
None
|
||||
}
|
||||
@@ -388,7 +424,8 @@ impl<T: 'static> From<ArcLocalResource<T>> for LocalResource<T> {
|
||||
fn from(arc: ArcLocalResource<T>) -> Self {
|
||||
Self {
|
||||
data: arc.data.into(),
|
||||
#[cfg(debug_assertions)]
|
||||
refetch: arc.refetch.into(),
|
||||
#[cfg(any(debug_assertions, leptos_debuginfo))]
|
||||
defined_at: arc.defined_at,
|
||||
}
|
||||
}
|
||||
@@ -398,7 +435,8 @@ impl<T: 'static> From<LocalResource<T>> for ArcLocalResource<T> {
|
||||
fn from(local: LocalResource<T>) -> Self {
|
||||
Self {
|
||||
data: local.data.into(),
|
||||
#[cfg(debug_assertions)]
|
||||
refetch: local.refetch.into(),
|
||||
#[cfg(any(debug_assertions, leptos_debuginfo))]
|
||||
defined_at: local.defined_at,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,13 +5,14 @@ use reactive_graph::{
|
||||
use server_fn::{ServerFn, ServerFnError};
|
||||
use std::{ops::Deref, panic::Location};
|
||||
|
||||
/// An [`ArcMultiAction`] that can be used to call a server function.
|
||||
pub struct ArcServerMultiAction<S>
|
||||
where
|
||||
S: ServerFn + 'static,
|
||||
S::Output: 'static,
|
||||
{
|
||||
inner: ArcMultiAction<S, Result<S::Output, ServerFnError<S::Error>>>,
|
||||
#[cfg(debug_assertions)]
|
||||
#[cfg(any(debug_assertions, leptos_debuginfo))]
|
||||
defined_at: &'static Location<'static>,
|
||||
}
|
||||
|
||||
@@ -21,13 +22,14 @@ where
|
||||
S::Output: Send + Sync + 'static,
|
||||
S::Error: Send + Sync + 'static,
|
||||
{
|
||||
/// Creates a new [`ArcMultiAction`] which, when dispatched, will call the server function `S`.
|
||||
#[track_caller]
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
inner: ArcMultiAction::new(|input: &S| {
|
||||
S::run_on_client(input.clone())
|
||||
}),
|
||||
#[cfg(debug_assertions)]
|
||||
#[cfg(any(debug_assertions, leptos_debuginfo))]
|
||||
defined_at: Location::caller(),
|
||||
}
|
||||
}
|
||||
@@ -53,7 +55,7 @@ where
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
inner: self.inner.clone(),
|
||||
#[cfg(debug_assertions)]
|
||||
#[cfg(any(debug_assertions, leptos_debuginfo))]
|
||||
defined_at: self.defined_at,
|
||||
}
|
||||
}
|
||||
@@ -76,24 +78,25 @@ where
|
||||
S::Output: 'static,
|
||||
{
|
||||
fn defined_at(&self) -> Option<&'static Location<'static>> {
|
||||
#[cfg(debug_assertions)]
|
||||
#[cfg(any(debug_assertions, leptos_debuginfo))]
|
||||
{
|
||||
Some(self.defined_at)
|
||||
}
|
||||
#[cfg(not(debug_assertions))]
|
||||
#[cfg(not(any(debug_assertions, leptos_debuginfo)))]
|
||||
{
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A [`MultiAction`] that can be used to call a server function.
|
||||
pub struct ServerMultiAction<S>
|
||||
where
|
||||
S: ServerFn + 'static,
|
||||
S::Output: 'static,
|
||||
{
|
||||
inner: MultiAction<S, Result<S::Output, ServerFnError<S::Error>>>,
|
||||
#[cfg(debug_assertions)]
|
||||
#[cfg(any(debug_assertions, leptos_debuginfo))]
|
||||
defined_at: &'static Location<'static>,
|
||||
}
|
||||
|
||||
@@ -114,12 +117,13 @@ where
|
||||
S::Output: Send + Sync + 'static,
|
||||
S::Error: Send + Sync + 'static,
|
||||
{
|
||||
/// Creates a new [`MultiAction`] which, when dispatched, will call the server function `S`.
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
inner: MultiAction::new(|input: &S| {
|
||||
S::run_on_client(input.clone())
|
||||
}),
|
||||
#[cfg(debug_assertions)]
|
||||
#[cfg(any(debug_assertions, leptos_debuginfo))]
|
||||
defined_at: Location::caller(),
|
||||
}
|
||||
}
|
||||
@@ -172,11 +176,11 @@ where
|
||||
S::Output: 'static,
|
||||
{
|
||||
fn defined_at(&self) -> Option<&'static Location<'static>> {
|
||||
#[cfg(debug_assertions)]
|
||||
#[cfg(any(debug_assertions, leptos_debuginfo))]
|
||||
{
|
||||
Some(self.defined_at)
|
||||
}
|
||||
#[cfg(not(debug_assertions))]
|
||||
#[cfg(not(any(debug_assertions, leptos_debuginfo)))]
|
||||
{
|
||||
None
|
||||
}
|
||||
|
||||
@@ -1,344 +0,0 @@
|
||||
use leptos_reactive::{
|
||||
is_suppressing_resource_load, signal_prelude::*, spawn_local, store_value,
|
||||
untrack, StoredValue,
|
||||
};
|
||||
use server_fn::{ServerFn, ServerFnError};
|
||||
use std::{future::Future, pin::Pin, rc::Rc};
|
||||
|
||||
/// An action that synchronizes multiple imperative `async` calls to the reactive system,
|
||||
/// tracking the progress of each one.
|
||||
///
|
||||
/// Where an [Action](crate::Action) fires a single call, a `MultiAction` allows you to
|
||||
/// keep track of multiple in-flight actions.
|
||||
///
|
||||
/// If you’re trying to load data by running an `async` function reactively, you probably
|
||||
/// want to use a [Resource](leptos_reactive::Resource) instead. If you’re trying to occasionally
|
||||
/// run an `async` function in response to something like a user adding a task to a todo list,
|
||||
/// you’re in the right place.
|
||||
///
|
||||
/// ```rust
|
||||
/// # use leptos::*;
|
||||
/// # let runtime = create_runtime();
|
||||
/// async fn send_new_todo_to_api(task: String) -> usize {
|
||||
/// // do something...
|
||||
/// // return a task id
|
||||
/// 42
|
||||
/// }
|
||||
/// let add_todo = create_multi_action(|task: &String| {
|
||||
/// // `task` is given as `&String` because its value is available in `input`
|
||||
/// send_new_todo_to_api(task.clone())
|
||||
/// });
|
||||
///
|
||||
/// # if false {
|
||||
/// add_todo.dispatch("Buy milk".to_string());
|
||||
/// add_todo.dispatch("???".to_string());
|
||||
/// add_todo.dispatch("Profit!!!".to_string());
|
||||
/// # }
|
||||
///
|
||||
/// # runtime.dispose();
|
||||
/// ```
|
||||
///
|
||||
/// The input to the `async` function should always be a single value,
|
||||
/// but it can be of any type. The argument is always passed by reference to the
|
||||
/// function, because it is stored in [Submission::input] as well.
|
||||
///
|
||||
/// ```rust
|
||||
/// # use leptos::*;
|
||||
/// # let runtime = create_runtime();
|
||||
/// // if there's a single argument, just use that
|
||||
/// let action1 = create_multi_action(|input: &String| {
|
||||
/// let input = input.clone();
|
||||
/// async move { todo!() }
|
||||
/// });
|
||||
///
|
||||
/// // if there are no arguments, use the unit type `()`
|
||||
/// let action2 = create_multi_action(|input: &()| async { todo!() });
|
||||
///
|
||||
/// // if there are multiple arguments, use a tuple
|
||||
/// let action3 =
|
||||
/// create_multi_action(|input: &(usize, String)| async { todo!() });
|
||||
/// # runtime.dispose();
|
||||
/// ```
|
||||
pub struct MultiAction<I, O>(StoredValue<MultiActionState<I, O>>)
|
||||
where
|
||||
I: 'static,
|
||||
O: 'static;
|
||||
|
||||
impl<I, O> MultiAction<I, O>
|
||||
where
|
||||
I: 'static,
|
||||
O: 'static,
|
||||
{
|
||||
}
|
||||
|
||||
impl<I, O> Clone for MultiAction<I, O>
|
||||
where
|
||||
I: 'static,
|
||||
O: 'static,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
*self
|
||||
}
|
||||
}
|
||||
|
||||
impl<I, O> Copy for MultiAction<I, O>
|
||||
where
|
||||
I: 'static,
|
||||
O: 'static,
|
||||
{
|
||||
}
|
||||
|
||||
impl<I, O> MultiAction<I, O>
|
||||
where
|
||||
I: 'static,
|
||||
O: 'static,
|
||||
{
|
||||
/// Calls the `async` function with a reference to the input type as its argument.
|
||||
#[cfg_attr(
|
||||
feature = "tracing",
|
||||
tracing::instrument(level = "trace", skip_all)
|
||||
)]
|
||||
pub fn dispatch(&self, input: I) {
|
||||
self.0.with_value(|a| a.dispatch(input))
|
||||
}
|
||||
|
||||
/// The set of all submissions to this multi-action.
|
||||
#[cfg_attr(
|
||||
feature = "tracing",
|
||||
tracing::instrument(level = "trace", skip_all)
|
||||
)]
|
||||
pub fn submissions(&self) -> ReadSignal<Vec<Submission<I, O>>> {
|
||||
self.0.with_value(|a| a.submissions())
|
||||
}
|
||||
|
||||
/// The URL associated with the action (typically as part of a server function.)
|
||||
/// This enables integration with the `MultiActionForm` component in `leptos_router`.
|
||||
pub fn url(&self) -> Option<String> {
|
||||
self.0.with_value(|a| a.url.as_ref().cloned())
|
||||
}
|
||||
|
||||
/// How many times an action has successfully resolved.
|
||||
#[cfg_attr(
|
||||
feature = "tracing",
|
||||
tracing::instrument(level = "trace", skip_all)
|
||||
)]
|
||||
pub fn version(&self) -> RwSignal<usize> {
|
||||
self.0.with_value(|a| a.version)
|
||||
}
|
||||
|
||||
/// Associates the URL of the given server function with this action.
|
||||
/// This enables integration with the `MultiActionForm` component in `leptos_router`.
|
||||
#[cfg_attr(
|
||||
feature = "tracing",
|
||||
tracing::instrument(level = "trace", skip_all)
|
||||
)]
|
||||
pub fn using_server_fn<T: ServerFn>(self) -> Self {
|
||||
self.0.update_value(|a| {
|
||||
a.url = Some(T::url().to_string());
|
||||
});
|
||||
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
struct MultiActionState<I, O>
|
||||
where
|
||||
I: 'static,
|
||||
O: 'static,
|
||||
{
|
||||
/// How many times an action has successfully resolved.
|
||||
pub version: RwSignal<usize>,
|
||||
submissions: RwSignal<Vec<Submission<I, O>>>,
|
||||
url: Option<String>,
|
||||
#[allow(clippy::complexity)]
|
||||
action_fn: Rc<dyn Fn(&I) -> Pin<Box<dyn Future<Output = O>>>>,
|
||||
}
|
||||
|
||||
/// An action that has been submitted by dispatching it to a [MultiAction](crate::MultiAction).
|
||||
pub struct Submission<I, O>
|
||||
where
|
||||
I: 'static,
|
||||
O: 'static,
|
||||
{
|
||||
/// The current argument that was dispatched to the `async` function.
|
||||
/// `Some` while we are waiting for it to resolve, `None` if it has resolved.
|
||||
pub input: RwSignal<Option<I>>,
|
||||
/// The most recent return value of the `async` function.
|
||||
pub value: RwSignal<Option<O>>,
|
||||
pub(crate) pending: RwSignal<bool>,
|
||||
/// Controls this submission has been canceled.
|
||||
pub canceled: RwSignal<bool>,
|
||||
}
|
||||
|
||||
impl<I, O> Clone for Submission<I, O> {
|
||||
fn clone(&self) -> Self {
|
||||
*self
|
||||
}
|
||||
}
|
||||
|
||||
impl<I, O> Copy for Submission<I, O> {}
|
||||
|
||||
impl<I, O> Submission<I, O>
|
||||
where
|
||||
I: 'static,
|
||||
O: 'static,
|
||||
{
|
||||
/// Whether this submission is currently waiting to resolve.
|
||||
pub fn pending(&self) -> ReadSignal<bool> {
|
||||
self.pending.read_only()
|
||||
}
|
||||
|
||||
/// Cancels the submission, preventing it from resolving.
|
||||
pub fn cancel(&self) {
|
||||
self.canceled.set(true);
|
||||
}
|
||||
}
|
||||
|
||||
impl<I, O> MultiActionState<I, O>
|
||||
where
|
||||
I: 'static,
|
||||
O: 'static,
|
||||
{
|
||||
/// Calls the `async` function with a reference to the input type as its argument.
|
||||
#[cfg_attr(
|
||||
feature = "tracing",
|
||||
tracing::instrument(level = "trace", skip_all)
|
||||
)]
|
||||
pub fn dispatch(&self, input: I) {
|
||||
if !is_suppressing_resource_load() {
|
||||
let fut = (self.action_fn)(&input);
|
||||
|
||||
let submission = Submission {
|
||||
input: create_rw_signal(Some(input)),
|
||||
value: create_rw_signal(None),
|
||||
pending: create_rw_signal(true),
|
||||
canceled: create_rw_signal(false),
|
||||
};
|
||||
|
||||
self.submissions.update(|subs| subs.push(submission));
|
||||
|
||||
let canceled = submission.canceled;
|
||||
let input = submission.input;
|
||||
let pending = submission.pending;
|
||||
let value = submission.value;
|
||||
let version = self.version;
|
||||
|
||||
spawn_local(async move {
|
||||
let new_value = fut.await;
|
||||
let canceled = untrack(move || canceled.get());
|
||||
if !canceled {
|
||||
value.set(Some(new_value));
|
||||
}
|
||||
input.set(None);
|
||||
pending.set(false);
|
||||
version.update(|n| *n += 1);
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The set of all submissions to this multi-action.
|
||||
pub fn submissions(&self) -> ReadSignal<Vec<Submission<I, O>>> {
|
||||
self.submissions.read_only()
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates an [MultiAction] to synchronize an imperative `async` call to the synchronous reactive system.
|
||||
///
|
||||
/// If you’re trying to load data by running an `async` function reactively, you probably
|
||||
/// want to use a [create_resource](leptos_reactive::create_resource) instead. If you’re trying
|
||||
/// to occasionally run an `async` function in response to something like a user clicking a button,
|
||||
/// you're in the right place.
|
||||
///
|
||||
/// ```rust
|
||||
/// # use leptos::*;
|
||||
/// # let runtime = create_runtime();
|
||||
/// async fn send_new_todo_to_api(task: String) -> usize {
|
||||
/// // do something...
|
||||
/// // return a task id
|
||||
/// 42
|
||||
/// }
|
||||
/// let add_todo = create_multi_action(|task: &String| {
|
||||
/// // `task` is given as `&String` because its value is available in `input`
|
||||
/// send_new_todo_to_api(task.clone())
|
||||
/// });
|
||||
/// # if false {
|
||||
///
|
||||
/// add_todo.dispatch("Buy milk".to_string());
|
||||
/// add_todo.dispatch("???".to_string());
|
||||
/// add_todo.dispatch("Profit!!!".to_string());
|
||||
///
|
||||
/// assert_eq!(add_todo.submissions().get().len(), 3);
|
||||
/// # }
|
||||
/// # runtime.dispose();
|
||||
/// ```
|
||||
///
|
||||
/// The input to the `async` function should always be a single value,
|
||||
/// but it can be of any type. The argument is always passed by reference to the
|
||||
/// function, because it is stored in [Submission::input] as well.
|
||||
///
|
||||
/// ```rust
|
||||
/// # use leptos::*;
|
||||
/// # let runtime = create_runtime();
|
||||
/// // if there's a single argument, just use that
|
||||
/// let action1 = create_multi_action(|input: &String| {
|
||||
/// let input = input.clone();
|
||||
/// async move { todo!() }
|
||||
/// });
|
||||
///
|
||||
/// // if there are no arguments, use the unit type `()`
|
||||
/// let action2 = create_multi_action(|input: &()| async { todo!() });
|
||||
///
|
||||
/// // if there are multiple arguments, use a tuple
|
||||
/// let action3 =
|
||||
/// create_multi_action(|input: &(usize, String)| async { todo!() });
|
||||
/// # runtime.dispose();
|
||||
/// ```
|
||||
#[cfg_attr(feature = "tracing", tracing::instrument(level = "trace", skip_all))]
|
||||
pub fn create_multi_action<I, O, F, Fu>(action_fn: F) -> MultiAction<I, O>
|
||||
where
|
||||
I: 'static,
|
||||
O: 'static,
|
||||
F: Fn(&I) -> Fu + 'static,
|
||||
Fu: Future<Output = O> + 'static,
|
||||
{
|
||||
let version = create_rw_signal(0);
|
||||
let submissions = create_rw_signal(Vec::new());
|
||||
let action_fn = Rc::new(move |input: &I| {
|
||||
let fut = action_fn(input);
|
||||
Box::pin(fut) as Pin<Box<dyn Future<Output = O>>>
|
||||
});
|
||||
|
||||
MultiAction(store_value(MultiActionState {
|
||||
version,
|
||||
submissions,
|
||||
url: None,
|
||||
action_fn,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Creates an [MultiAction] that can be used to call a server function.
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// # use leptos::*;
|
||||
///
|
||||
/// #[server(MyServerFn)]
|
||||
/// async fn my_server_fn() -> Result<(), ServerFnError> {
|
||||
/// todo!()
|
||||
/// }
|
||||
///
|
||||
/// # let runtime = create_runtime();
|
||||
/// let my_server_multi_action = create_server_multi_action::<MyServerFn>();
|
||||
/// # runtime.dispose();
|
||||
/// ```
|
||||
#[cfg_attr(feature = "tracing", tracing::instrument(level = "trace", skip_all))]
|
||||
pub fn create_server_multi_action<S>(
|
||||
) -> MultiAction<S, Result<S::Output, ServerFnError<S::Error>>>
|
||||
where
|
||||
S: Clone + ServerFn,
|
||||
{
|
||||
#[cfg(feature = "ssr")]
|
||||
let c = move |args: &S| S::run_body(args.clone());
|
||||
#[cfg(not(feature = "ssr"))]
|
||||
let c = move |args: &S| S::run_on_client(args.clone());
|
||||
create_multi_action(c).using_server_fn::<S>()
|
||||
}
|
||||
@@ -43,6 +43,15 @@ use std::{
|
||||
task::{Context, Poll, Waker},
|
||||
};
|
||||
|
||||
/// A reference-counted resource that only loads once.
|
||||
///
|
||||
/// Resources allow asynchronously loading data and serializing it from the server to the client,
|
||||
/// so that it loads on the server, and is then deserialized on the client. This improves
|
||||
/// performance by beginning data loading on the server when the request is made, rather than
|
||||
/// beginning it on the client after WASM has been loaded.
|
||||
///
|
||||
/// You can access the value of the resource either synchronously using `.get()` or asynchronously
|
||||
/// using `.await`.
|
||||
#[derive(Debug)]
|
||||
pub struct ArcOnceResource<T, Ser = JsonSerdeCodec> {
|
||||
trigger: ArcTrigger,
|
||||
@@ -51,7 +60,7 @@ pub struct ArcOnceResource<T, Ser = JsonSerdeCodec> {
|
||||
suspenses: Arc<RwLock<Vec<SuspenseContext>>>,
|
||||
loading: Arc<AtomicBool>,
|
||||
ser: PhantomData<fn() -> Ser>,
|
||||
#[cfg(debug_assertions)]
|
||||
#[cfg(any(debug_assertions, leptos_debuginfo))]
|
||||
defined_at: &'static Location<'static>,
|
||||
}
|
||||
|
||||
@@ -64,7 +73,7 @@ impl<T, Ser> Clone for ArcOnceResource<T, Ser> {
|
||||
suspenses: self.suspenses.clone(),
|
||||
loading: self.loading.clone(),
|
||||
ser: self.ser,
|
||||
#[cfg(debug_assertions)]
|
||||
#[cfg(any(debug_assertions, leptos_debuginfo))]
|
||||
defined_at: self.defined_at,
|
||||
}
|
||||
}
|
||||
@@ -80,6 +89,12 @@ where
|
||||
<Ser as Encoder<T>>::Encoded: IntoEncodedString,
|
||||
<Ser as Decoder<T>>::Encoded: FromEncodedStr,
|
||||
{
|
||||
/// Creates a new resource with the encoding `Ser`. If `blocking` is `true`, this is a blocking
|
||||
/// resource.
|
||||
///
|
||||
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
|
||||
/// This is useful if you need their data to set HTML document metadata or information that
|
||||
/// needs to appear in HTTP headers.
|
||||
#[track_caller]
|
||||
pub fn new_with_options(
|
||||
fut: impl Future<Output = T> + Send + 'static,
|
||||
@@ -125,7 +140,7 @@ where
|
||||
wakers,
|
||||
suspenses,
|
||||
ser: PhantomData,
|
||||
#[cfg(debug_assertions)]
|
||||
#[cfg(any(debug_assertions, leptos_debuginfo))]
|
||||
defined_at: Location::caller(),
|
||||
};
|
||||
|
||||
@@ -168,11 +183,11 @@ impl<T, Ser> ArcOnceResource<T, Ser> {
|
||||
|
||||
impl<T, Ser> DefinedAt for ArcOnceResource<T, Ser> {
|
||||
fn defined_at(&self) -> Option<&'static Location<'static>> {
|
||||
#[cfg(not(debug_assertions))]
|
||||
#[cfg(not(any(debug_assertions, leptos_debuginfo)))]
|
||||
{
|
||||
None
|
||||
}
|
||||
#[cfg(debug_assertions)]
|
||||
#[cfg(any(debug_assertions, leptos_debuginfo))]
|
||||
{
|
||||
Some(self.defined_at)
|
||||
}
|
||||
@@ -238,7 +253,8 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
/// A [`Future`] that is ready when an [`ArcAsyncDerived`] is finished loading or reloading,
|
||||
/// A [`Future`] that is ready when an
|
||||
/// [`ArcAsyncDerived`](reactive_graph::computed::ArcAsyncDerived) is finished loading or reloading,
|
||||
/// and contains its value. `.await`ing this clones the value `T`.
|
||||
pub struct OnceResourceFuture<T> {
|
||||
source: AnySource,
|
||||
@@ -256,7 +272,7 @@ where
|
||||
|
||||
#[track_caller]
|
||||
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
||||
#[cfg(debug_assertions)]
|
||||
#[cfg(any(debug_assertions, leptos_debuginfo))]
|
||||
let _guard = SpecialNonReactiveZone::enter();
|
||||
let waker = cx.waker();
|
||||
self.source.track();
|
||||
@@ -287,11 +303,17 @@ where
|
||||
<JsonSerdeCodec as Encoder<T>>::Encoded: IntoEncodedString,
|
||||
<JsonSerdeCodec as Decoder<T>>::Encoded: FromEncodedStr,
|
||||
{
|
||||
/// Creates a resource using [`JsonSerdeCodec`] for encoding/decoding the value.
|
||||
#[track_caller]
|
||||
pub fn new(fut: impl Future<Output = T> + Send + 'static) -> Self {
|
||||
ArcOnceResource::new_with_options(fut, false)
|
||||
}
|
||||
|
||||
/// Creates a blocking resource using [`JsonSerdeCodec`] for encoding/decoding the value.
|
||||
///
|
||||
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
|
||||
/// This is useful if you need their data to set HTML document metadata or information that
|
||||
/// needs to appear in HTTP headers.
|
||||
#[track_caller]
|
||||
pub fn new_blocking(fut: impl Future<Output = T> + Send + 'static) -> Self {
|
||||
ArcOnceResource::new_with_options(fut, true)
|
||||
@@ -307,6 +329,7 @@ T: Send + Sync + 'static,
|
||||
<FromToStringCodec as Encoder<T>>::Encoded: IntoEncodedString,
|
||||
<FromToStringCodec as Decoder<T>>::Encoded: FromEncodedStr,
|
||||
{
|
||||
/// Creates a resource using [`FromToStringCodec`] for encoding/decoding the value.
|
||||
pub fn new_str(
|
||||
fut: impl Future<Output = T> + Send + 'static
|
||||
) -> Self
|
||||
@@ -314,6 +337,11 @@ T: Send + Sync + 'static,
|
||||
ArcOnceResource::new_with_options(fut, false)
|
||||
}
|
||||
|
||||
/// Creates a blocking resource using [`FromToStringCodec`] for encoding/decoding the value.
|
||||
///
|
||||
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
|
||||
/// This is useful if you need their data to set HTML document metadata or information that
|
||||
/// needs to appear in HTTP headers.
|
||||
pub fn new_str_blocking(
|
||||
fut: impl Future<Output = T> + Send + 'static
|
||||
) -> Self
|
||||
@@ -332,6 +360,7 @@ T: Send + Sync + 'static,
|
||||
<JsonSerdeWasmCodec as Encoder<T>>::Encoded: IntoEncodedString,
|
||||
<JsonSerdeWasmCodec as Decoder<T>>::Encoded: FromEncodedStr,
|
||||
{
|
||||
/// Creates a resource using [`JsonSerdeWasmCodec`] for encoding/decoding the value.
|
||||
#[track_caller]
|
||||
pub fn new_serde_wb(
|
||||
fut: impl Future<Output = T> + Send + 'static
|
||||
@@ -340,6 +369,11 @@ fut: impl Future<Output = T> + Send + 'static
|
||||
ArcOnceResource::new_with_options(fut, false)
|
||||
}
|
||||
|
||||
/// Creates a blocking resource using [`JsonSerdeWasmCodec`] for encoding/decoding the value.
|
||||
///
|
||||
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
|
||||
/// This is useful if you need their data to set HTML document metadata or information that
|
||||
/// needs to appear in HTTP headers.
|
||||
#[track_caller]
|
||||
pub fn new_serde_wb_blocking(
|
||||
fut: impl Future<Output = T> + Send + 'static
|
||||
@@ -360,6 +394,7 @@ where
|
||||
<MiniserdeCodec as Encoder<T>>::Encoded: IntoEncodedString,
|
||||
<MiniserdeCodec as Decoder<T>>::Encoded: FromEncodedStr,
|
||||
{
|
||||
/// Creates a resource using [`MiniserdeCodec`] for encoding/decoding the value.
|
||||
#[track_caller]
|
||||
pub fn new_miniserde(
|
||||
fut: impl Future<Output = T> + Send + 'static,
|
||||
@@ -367,6 +402,11 @@ where
|
||||
ArcOnceResource::new_with_options(fut, false)
|
||||
}
|
||||
|
||||
/// Creates a blocking resource using [`MiniserdeCodec`] for encoding/decoding the value.
|
||||
///
|
||||
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
|
||||
/// This is useful if you need their data to set HTML document metadata or information that
|
||||
/// needs to appear in HTTP headers.
|
||||
#[track_caller]
|
||||
pub fn new_miniserde_blocking(
|
||||
fut: impl Future<Output = T> + Send + 'static,
|
||||
@@ -385,6 +425,7 @@ T: Send + Sync + 'static,
|
||||
<SerdeLite<JsonSerdeCodec> as Encoder<T>>::Encoded: IntoEncodedString,
|
||||
<SerdeLite<JsonSerdeCodec> as Decoder<T>>::Encoded: FromEncodedStr,
|
||||
{
|
||||
/// Creates a resource using [`SerdeLite`] for encoding/decoding the value.
|
||||
#[track_caller]
|
||||
pub fn new_serde_lite(
|
||||
fut: impl Future<Output = T> + Send + 'static
|
||||
@@ -393,6 +434,11 @@ fut: impl Future<Output = T> + Send + 'static
|
||||
ArcOnceResource::new_with_options(fut, false)
|
||||
}
|
||||
|
||||
/// Creates a blocking resource using [`SerdeLite`] for encoding/decoding the value.
|
||||
///
|
||||
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
|
||||
/// This is useful if you need their data to set HTML document metadata or information that
|
||||
/// needs to appear in HTTP headers.
|
||||
#[track_caller]
|
||||
pub fn new_serde_lite_blocking(
|
||||
fut: impl Future<Output = T> + Send + 'static
|
||||
@@ -414,11 +460,17 @@ where
|
||||
<RkyvCodec as Encoder<T>>::Encoded: IntoEncodedString,
|
||||
<RkyvCodec as Decoder<T>>::Encoded: FromEncodedStr,
|
||||
{
|
||||
/// Creates a resource using [`RkyvCodec`] for encoding/decoding the value.
|
||||
#[track_caller]
|
||||
pub fn new_rkyv(fut: impl Future<Output = T> + Send + 'static) -> Self {
|
||||
ArcOnceResource::new_with_options(fut, false)
|
||||
}
|
||||
|
||||
/// Creates a blocking resource using [`RkyvCodec`] for encoding/decoding the value.
|
||||
///
|
||||
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
|
||||
/// This is useful if you need their data to set HTML document metadata or information that
|
||||
/// needs to appear in HTTP headers.
|
||||
#[track_caller]
|
||||
pub fn new_rkyv_blocking(
|
||||
fut: impl Future<Output = T> + Send + 'static,
|
||||
@@ -427,10 +479,19 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
/// A resource that only loads once.
|
||||
///
|
||||
/// Resources allow asynchronously loading data and serializing it from the server to the client,
|
||||
/// so that it loads on the server, and is then deserialized on the client. This improves
|
||||
/// performance by beginning data loading on the server when the request is made, rather than
|
||||
/// beginning it on the client after WASM has been loaded.
|
||||
///
|
||||
/// You can access the value of the resource either synchronously using `.get()` or asynchronously
|
||||
/// using `.await`.
|
||||
#[derive(Debug)]
|
||||
pub struct OnceResource<T, Ser = JsonSerdeCodec> {
|
||||
inner: ArenaItem<ArcOnceResource<T, Ser>>,
|
||||
#[cfg(debug_assertions)]
|
||||
#[cfg(any(debug_assertions, leptos_debuginfo))]
|
||||
defined_at: &'static Location<'static>,
|
||||
}
|
||||
|
||||
@@ -452,18 +513,24 @@ where
|
||||
<Ser as Encoder<T>>::Encoded: IntoEncodedString,
|
||||
<Ser as Decoder<T>>::Encoded: FromEncodedStr,
|
||||
{
|
||||
/// Creates a new resource with the encoding `Ser`. If `blocking` is `true`, this is a blocking
|
||||
/// resource.
|
||||
///
|
||||
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
|
||||
/// This is useful if you need their data to set HTML document metadata or information that
|
||||
/// needs to appear in HTTP headers.
|
||||
#[track_caller]
|
||||
pub fn new_with_options(
|
||||
fut: impl Future<Output = T> + Send + 'static,
|
||||
blocking: bool,
|
||||
) -> Self {
|
||||
#[cfg(debug_assertions)]
|
||||
#[cfg(any(debug_assertions, leptos_debuginfo))]
|
||||
let defined_at = Location::caller();
|
||||
Self {
|
||||
inner: ArenaItem::new(ArcOnceResource::new_with_options(
|
||||
fut, blocking,
|
||||
)),
|
||||
#[cfg(debug_assertions)]
|
||||
#[cfg(any(debug_assertions, leptos_debuginfo))]
|
||||
defined_at,
|
||||
}
|
||||
}
|
||||
@@ -484,11 +551,11 @@ where
|
||||
|
||||
impl<T, Ser> DefinedAt for OnceResource<T, Ser> {
|
||||
fn defined_at(&self) -> Option<&'static Location<'static>> {
|
||||
#[cfg(not(debug_assertions))]
|
||||
#[cfg(not(any(debug_assertions, leptos_debuginfo)))]
|
||||
{
|
||||
None
|
||||
}
|
||||
#[cfg(debug_assertions)]
|
||||
#[cfg(any(debug_assertions, leptos_debuginfo))]
|
||||
{
|
||||
Some(self.defined_at)
|
||||
}
|
||||
@@ -567,11 +634,17 @@ where
|
||||
<JsonSerdeCodec as Encoder<T>>::Encoded: IntoEncodedString,
|
||||
<JsonSerdeCodec as Decoder<T>>::Encoded: FromEncodedStr,
|
||||
{
|
||||
/// Creates a resource using [`JsonSerdeCodec`] for encoding/decoding the value.
|
||||
#[track_caller]
|
||||
pub fn new(fut: impl Future<Output = T> + Send + 'static) -> Self {
|
||||
OnceResource::new_with_options(fut, false)
|
||||
}
|
||||
|
||||
/// Creates a blocking resource using [`JsonSerdeCodec`] for encoding/decoding the value.
|
||||
///
|
||||
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
|
||||
/// This is useful if you need their data to set HTML document metadata or information that
|
||||
/// needs to appear in HTTP headers.
|
||||
#[track_caller]
|
||||
pub fn new_blocking(fut: impl Future<Output = T> + Send + 'static) -> Self {
|
||||
OnceResource::new_with_options(fut, true)
|
||||
@@ -587,6 +660,7 @@ T: Send + Sync + 'static,
|
||||
<FromToStringCodec as Encoder<T>>::Encoded: IntoEncodedString,
|
||||
<FromToStringCodec as Decoder<T>>::Encoded: FromEncodedStr,
|
||||
{
|
||||
/// Creates a resource using [`FromToStringCodec`] for encoding/decoding the value.
|
||||
pub fn new_str(
|
||||
fut: impl Future<Output = T> + Send + 'static
|
||||
) -> Self
|
||||
@@ -594,6 +668,11 @@ T: Send + Sync + 'static,
|
||||
OnceResource::new_with_options(fut, false)
|
||||
}
|
||||
|
||||
/// Creates a blocking resource using [`FromToStringCodec`] for encoding/decoding the value.
|
||||
///
|
||||
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
|
||||
/// This is useful if you need their data to set HTML document metadata or information that
|
||||
/// needs to appear in HTTP headers.
|
||||
pub fn new_str_blocking(
|
||||
fut: impl Future<Output = T> + Send + 'static
|
||||
) -> Self
|
||||
@@ -612,6 +691,7 @@ T: Send + Sync + 'static,
|
||||
<JsonSerdeWasmCodec as Encoder<T>>::Encoded: IntoEncodedString,
|
||||
<JsonSerdeWasmCodec as Decoder<T>>::Encoded: FromEncodedStr,
|
||||
{
|
||||
/// Creates a resource using [`JsonSerdeWasmCodec`] for encoding/decoding the value.
|
||||
#[track_caller]
|
||||
pub fn new_serde_wb(
|
||||
fut: impl Future<Output = T> + Send + 'static
|
||||
@@ -620,6 +700,11 @@ fut: impl Future<Output = T> + Send + 'static
|
||||
OnceResource::new_with_options(fut, false)
|
||||
}
|
||||
|
||||
/// Creates a blocking resource using [`JsonSerdeWasmCodec`] for encoding/decoding the value.
|
||||
///
|
||||
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
|
||||
/// This is useful if you need their data to set HTML document metadata or information that
|
||||
/// needs to appear in HTTP headers.
|
||||
#[track_caller]
|
||||
pub fn new_serde_wb_blocking(
|
||||
fut: impl Future<Output = T> + Send + 'static
|
||||
@@ -640,6 +725,7 @@ where
|
||||
<MiniserdeCodec as Encoder<T>>::Encoded: IntoEncodedString,
|
||||
<MiniserdeCodec as Decoder<T>>::Encoded: FromEncodedStr,
|
||||
{
|
||||
/// Creates a resource using [`MiniserdeCodec`] for encoding/decoding the value.
|
||||
#[track_caller]
|
||||
pub fn new_miniserde(
|
||||
fut: impl Future<Output = T> + Send + 'static,
|
||||
@@ -647,6 +733,11 @@ where
|
||||
OnceResource::new_with_options(fut, false)
|
||||
}
|
||||
|
||||
/// Creates a blocking resource using [`MiniserdeCodec`] for encoding/decoding the value.
|
||||
///
|
||||
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
|
||||
/// This is useful if you need their data to set HTML document metadata or information that
|
||||
/// needs to appear in HTTP headers.
|
||||
#[track_caller]
|
||||
pub fn new_miniserde_blocking(
|
||||
fut: impl Future<Output = T> + Send + 'static,
|
||||
@@ -665,6 +756,7 @@ T: Send + Sync + 'static,
|
||||
<SerdeLite<JsonSerdeCodec> as Encoder<T>>::Encoded: IntoEncodedString,
|
||||
<SerdeLite<JsonSerdeCodec> as Decoder<T>>::Encoded: FromEncodedStr,
|
||||
{
|
||||
/// Creates a resource using [`SerdeLite`] for encoding/decoding the value.
|
||||
#[track_caller]
|
||||
pub fn new_serde_lite(
|
||||
fut: impl Future<Output = T> + Send + 'static
|
||||
@@ -673,6 +765,11 @@ fut: impl Future<Output = T> + Send + 'static
|
||||
OnceResource::new_with_options(fut, false)
|
||||
}
|
||||
|
||||
/// Creates a blocking resource using [`SerdeLite`] for encoding/decoding the value.
|
||||
///
|
||||
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
|
||||
/// This is useful if you need their data to set HTML document metadata or information that
|
||||
/// needs to appear in HTTP headers.
|
||||
#[track_caller]
|
||||
pub fn new_serde_lite_blocking(
|
||||
fut: impl Future<Output = T> + Send + 'static
|
||||
@@ -694,11 +791,17 @@ where
|
||||
<RkyvCodec as Encoder<T>>::Encoded: IntoEncodedString,
|
||||
<RkyvCodec as Decoder<T>>::Encoded: FromEncodedStr,
|
||||
{
|
||||
/// Creates a resource using [`RkyvCodec`] for encoding/decoding the value.
|
||||
#[track_caller]
|
||||
pub fn new_rkyv(fut: impl Future<Output = T> + Send + 'static) -> Self {
|
||||
OnceResource::new_with_options(fut, false)
|
||||
}
|
||||
|
||||
/// Creates a blocking resource using [`RkyvCodec`] for encoding/decoding the value.
|
||||
///
|
||||
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
|
||||
/// This is useful if you need their data to set HTML document metadata or information that
|
||||
/// needs to appear in HTTP headers.
|
||||
#[track_caller]
|
||||
pub fn new_rkyv_blocking(
|
||||
fut: impl Future<Output = T> + Send + 'static,
|
||||
|
||||
@@ -37,9 +37,12 @@ use std::{
|
||||
pub(crate) static IS_SUPPRESSING_RESOURCE_LOAD: AtomicBool =
|
||||
AtomicBool::new(false);
|
||||
|
||||
/// Used to prevent resources from actually loading, in environments (like server route generation)
|
||||
/// where they are not needed.
|
||||
pub struct SuppressResourceLoad;
|
||||
|
||||
impl SuppressResourceLoad {
|
||||
/// Prevents resources from loading until this is dropped.
|
||||
pub fn new() -> Self {
|
||||
IS_SUPPRESSING_RESOURCE_LOAD.store(true, Ordering::Relaxed);
|
||||
Self
|
||||
@@ -58,11 +61,20 @@ impl Drop for SuppressResourceLoad {
|
||||
}
|
||||
}
|
||||
|
||||
/// A reference-counted asynchronous resource.
|
||||
///
|
||||
/// Resources allow asynchronously loading data and serializing it from the server to the client,
|
||||
/// so that it loads on the server, and is then deserialized on the client. This improves
|
||||
/// performance by beginning data loading on the server when the request is made, rather than
|
||||
/// beginning it on the client after WASM has been loaded.
|
||||
///
|
||||
/// You can access the value of the resource either synchronously using `.get()` or asynchronously
|
||||
/// using `.await`.
|
||||
pub struct ArcResource<T, Ser = JsonSerdeCodec> {
|
||||
ser: PhantomData<Ser>,
|
||||
refetch: ArcRwSignal<usize>,
|
||||
data: ArcAsyncDerived<T>,
|
||||
#[cfg(debug_assertions)]
|
||||
#[cfg(any(debug_assertions, leptos_debuginfo))]
|
||||
defined_at: &'static Location<'static>,
|
||||
}
|
||||
|
||||
@@ -70,7 +82,7 @@ impl<T, Ser> Debug for ArcResource<T, Ser> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
let mut d = f.debug_struct("ArcResource");
|
||||
d.field("ser", &self.ser).field("data", &self.data);
|
||||
#[cfg(debug_assertions)]
|
||||
#[cfg(any(debug_assertions, leptos_debuginfo))]
|
||||
d.field("defined_at", self.defined_at);
|
||||
d.finish_non_exhaustive()
|
||||
}
|
||||
@@ -86,7 +98,7 @@ where
|
||||
ser: PhantomData,
|
||||
data: arc_resource.data.into(),
|
||||
refetch: arc_resource.refetch.into(),
|
||||
#[cfg(debug_assertions)]
|
||||
#[cfg(any(debug_assertions, leptos_debuginfo))]
|
||||
defined_at: Location::caller(),
|
||||
}
|
||||
}
|
||||
@@ -102,7 +114,7 @@ where
|
||||
ser: PhantomData,
|
||||
data: resource.data.into(),
|
||||
refetch: resource.refetch.into(),
|
||||
#[cfg(debug_assertions)]
|
||||
#[cfg(any(debug_assertions, leptos_debuginfo))]
|
||||
defined_at: Location::caller(),
|
||||
}
|
||||
}
|
||||
@@ -110,11 +122,11 @@ where
|
||||
|
||||
impl<T, Ser> DefinedAt for ArcResource<T, Ser> {
|
||||
fn defined_at(&self) -> Option<&'static Location<'static>> {
|
||||
#[cfg(debug_assertions)]
|
||||
#[cfg(any(debug_assertions, leptos_debuginfo))]
|
||||
{
|
||||
Some(self.defined_at)
|
||||
}
|
||||
#[cfg(not(debug_assertions))]
|
||||
#[cfg(not(any(debug_assertions, leptos_debuginfo)))]
|
||||
{
|
||||
None
|
||||
}
|
||||
@@ -127,7 +139,7 @@ impl<T, Ser> Clone for ArcResource<T, Ser> {
|
||||
ser: self.ser,
|
||||
refetch: self.refetch.clone(),
|
||||
data: self.data.clone(),
|
||||
#[cfg(debug_assertions)]
|
||||
#[cfg(any(debug_assertions, leptos_debuginfo))]
|
||||
defined_at: self.defined_at,
|
||||
}
|
||||
}
|
||||
@@ -194,6 +206,21 @@ where
|
||||
<Ser as Encoder<T>>::Encoded: IntoEncodedString,
|
||||
<Ser as Decoder<T>>::Encoded: FromEncodedStr,
|
||||
{
|
||||
/// Creates a new resource with the encoding `Ser`.
|
||||
///
|
||||
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
|
||||
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
|
||||
/// generate a new [`Future`] to load data.
|
||||
///
|
||||
/// On creation, if you are on the server, this will run the `fetcher` once to generate
|
||||
/// a `Future` whose value will be serialized from the server to the client. If you are on
|
||||
/// the client, the initial value will be deserialized without re-running that async task.
|
||||
///
|
||||
/// If `blocking` is `true`, this is a blocking resource.
|
||||
///
|
||||
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
|
||||
/// This is useful if you need their data to set HTML document metadata or information that
|
||||
/// needs to appear in HTTP headers.
|
||||
#[track_caller]
|
||||
pub fn new_with_options<S, Fut>(
|
||||
source: impl Fn() -> S + Send + Sync + 'static,
|
||||
@@ -273,11 +300,13 @@ where
|
||||
ser: PhantomData,
|
||||
data,
|
||||
refetch,
|
||||
#[cfg(debug_assertions)]
|
||||
#[cfg(any(debug_assertions, leptos_debuginfo))]
|
||||
defined_at: Location::caller(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Synchronously, reactively reads the current value of the resource and applies the function
|
||||
/// `f` to its value if it is `Some(_)`.
|
||||
#[track_caller]
|
||||
pub fn map<U>(&self, f: impl FnOnce(&T) -> U) -> Option<U>
|
||||
where
|
||||
@@ -351,6 +380,13 @@ where
|
||||
T: Send + Sync + 'static,
|
||||
E: Send + Sync + Clone + 'static,
|
||||
{
|
||||
/// Applies the given function when a resource that returns `Result<T, E>`
|
||||
/// has resolved and loaded an `Ok(_)`, rather than requiring nested `.map()`
|
||||
/// calls over the `Option<Result<_, _>>` returned by the resource.
|
||||
///
|
||||
/// This is useful when used with features like server functions, in conjunction
|
||||
/// with `<ErrorBoundary/>` and `<Suspense/>`, when these other components are
|
||||
/// left to handle the `None` and `Err(_)` states.
|
||||
#[track_caller]
|
||||
pub fn and_then<U>(&self, f: impl FnOnce(&T) -> U) -> Option<Result<U, E>> {
|
||||
self.map(|data| data.as_ref().map(f).map_err(|e| e.clone()))
|
||||
@@ -367,6 +403,15 @@ where
|
||||
<JsonSerdeCodec as Encoder<T>>::Encoded: IntoEncodedString,
|
||||
<JsonSerdeCodec as Decoder<T>>::Encoded: FromEncodedStr,
|
||||
{
|
||||
/// Creates a new resource with the encoding [`JsonSerdeCodec`].
|
||||
///
|
||||
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
|
||||
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
|
||||
/// generate a new [`Future`] to load data.
|
||||
///
|
||||
/// On creation, if you are on the server, this will run the `fetcher` once to generate
|
||||
/// a `Future` whose value will be serialized from the server to the client. If you are on
|
||||
/// the client, the initial value will be deserialized without re-running that async task.
|
||||
#[track_caller]
|
||||
pub fn new<S, Fut>(
|
||||
source: impl Fn() -> S + Send + Sync + 'static,
|
||||
@@ -380,6 +425,19 @@ where
|
||||
ArcResource::new_with_options(source, fetcher, false)
|
||||
}
|
||||
|
||||
/// Creates a new blocking resource with the encoding [`JsonSerdeCodec`].
|
||||
///
|
||||
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
|
||||
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
|
||||
/// generate a new [`Future`] to load data.
|
||||
///
|
||||
/// On creation, if you are on the server, this will run the `fetcher` once to generate
|
||||
/// a `Future` whose value will be serialized from the server to the client. If you are on
|
||||
/// the client, the initial value will be deserialized without re-running that async task.
|
||||
///
|
||||
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
|
||||
/// This is useful if you need their data to set HTML document metadata or information that
|
||||
/// needs to appear in HTTP headers.
|
||||
#[track_caller]
|
||||
pub fn new_blocking<S, Fut>(
|
||||
source: impl Fn() -> S + Send + Sync + 'static,
|
||||
@@ -402,6 +460,15 @@ where
|
||||
<FromToStringCodec as Encoder<T>>::Encoded: IntoEncodedString,
|
||||
<FromToStringCodec as Decoder<T>>::Encoded: FromEncodedStr,
|
||||
{
|
||||
/// Creates a new resource with the encoding [`FromToStringCodec`].
|
||||
///
|
||||
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
|
||||
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
|
||||
/// generate a new [`Future`] to load data.
|
||||
///
|
||||
/// On creation, if you are on the server, this will run the `fetcher` once to generate
|
||||
/// a `Future` whose value will be serialized from the server to the client. If you are on
|
||||
/// the client, the initial value will be deserialized without re-running that async task.
|
||||
pub fn new_str<S, Fut>(
|
||||
source: impl Fn() -> S + Send + Sync + 'static,
|
||||
fetcher: impl Fn(S) -> Fut + Send + Sync + 'static,
|
||||
@@ -414,6 +481,19 @@ where
|
||||
ArcResource::new_with_options(source, fetcher, false)
|
||||
}
|
||||
|
||||
/// Creates a new blocking resource with the encoding [`FromToStringCodec`].
|
||||
///
|
||||
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
|
||||
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
|
||||
/// generate a new [`Future`] to load data.
|
||||
///
|
||||
/// On creation, if you are on the server, this will run the `fetcher` once to generate
|
||||
/// a `Future` whose value will be serialized from the server to the client. If you are on
|
||||
/// the client, the initial value will be deserialized without re-running that async task.
|
||||
///
|
||||
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
|
||||
/// This is useful if you need their data to set HTML document metadata or information that
|
||||
/// needs to appear in HTTP headers.
|
||||
pub fn new_str_blocking<S, Fut>(
|
||||
source: impl Fn() -> S + Send + Sync + 'static,
|
||||
fetcher: impl Fn(S) -> Fut + Send + Sync + 'static,
|
||||
@@ -436,6 +516,15 @@ where
|
||||
<JsonSerdeWasmCodec as Encoder<T>>::Encoded: IntoEncodedString,
|
||||
<JsonSerdeWasmCodec as Decoder<T>>::Encoded: FromEncodedStr,
|
||||
{
|
||||
/// Creates a new resource with the encoding [`JsonSerdeWasmCodec`].
|
||||
///
|
||||
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
|
||||
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
|
||||
/// generate a new [`Future`] to load data.
|
||||
///
|
||||
/// On creation, if you are on the server, this will run the `fetcher` once to generate
|
||||
/// a `Future` whose value will be serialized from the server to the client. If you are on
|
||||
/// the client, the initial value will be deserialized without re-running that async task.
|
||||
#[track_caller]
|
||||
pub fn new_serde_wb<S, Fut>(
|
||||
source: impl Fn() -> S + Send + Sync + 'static,
|
||||
@@ -449,6 +538,19 @@ where
|
||||
ArcResource::new_with_options(source, fetcher, false)
|
||||
}
|
||||
|
||||
/// Creates a new blocking resource with the encoding [`JsonSerdeWasmCodec`].
|
||||
///
|
||||
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
|
||||
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
|
||||
/// generate a new [`Future`] to load data.
|
||||
///
|
||||
/// On creation, if you are on the server, this will run the `fetcher` once to generate
|
||||
/// a `Future` whose value will be serialized from the server to the client. If you are on
|
||||
/// the client, the initial value will be deserialized without re-running that async task.
|
||||
///
|
||||
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
|
||||
/// This is useful if you need their data to set HTML document metadata or information that
|
||||
/// needs to appear in HTTP headers.
|
||||
#[track_caller]
|
||||
pub fn new_serde_wb_blocking<S, Fut>(
|
||||
source: impl Fn() -> S + Send + Sync + 'static,
|
||||
@@ -473,6 +575,15 @@ where
|
||||
<MiniserdeCodec as Encoder<T>>::Encoded: IntoEncodedString,
|
||||
<MiniserdeCodec as Decoder<T>>::Encoded: FromEncodedStr,
|
||||
{
|
||||
/// Creates a new resource with the encoding [`MiniserdeCodec`].
|
||||
///
|
||||
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
|
||||
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
|
||||
/// generate a new [`Future`] to load data.
|
||||
///
|
||||
/// On creation, if you are on the server, this will run the `fetcher` once to generate
|
||||
/// a `Future` whose value will be serialized from the server to the client. If you are on
|
||||
/// the client, the initial value will be deserialized without re-running that async task.
|
||||
#[track_caller]
|
||||
pub fn new_miniserde<S, Fut>(
|
||||
source: impl Fn() -> S + Send + Sync + 'static,
|
||||
@@ -486,6 +597,19 @@ where
|
||||
ArcResource::new_with_options(source, fetcher, false)
|
||||
}
|
||||
|
||||
/// Creates a new blocking resource with the encoding [`MiniserdeCodec`].
|
||||
///
|
||||
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
|
||||
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
|
||||
/// generate a new [`Future`] to load data.
|
||||
///
|
||||
/// On creation, if you are on the server, this will run the `fetcher` once to generate
|
||||
/// a `Future` whose value will be serialized from the server to the client. If you are on
|
||||
/// the client, the initial value will be deserialized without re-running that async task.
|
||||
///
|
||||
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
|
||||
/// This is useful if you need their data to set HTML document metadata or information that
|
||||
/// needs to appear in HTTP headers.
|
||||
#[track_caller]
|
||||
pub fn new_miniserde_blocking<S, Fut>(
|
||||
source: impl Fn() -> S + Send + Sync + 'static,
|
||||
@@ -509,6 +633,15 @@ where
|
||||
<SerdeLite<JsonSerdeCodec> as Encoder<T>>::Encoded: IntoEncodedString,
|
||||
<SerdeLite<JsonSerdeCodec> as Decoder<T>>::Encoded: FromEncodedStr,
|
||||
{
|
||||
/// Creates a new resource with the encoding [`SerdeLite`].
|
||||
///
|
||||
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
|
||||
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
|
||||
/// generate a new [`Future`] to load data.
|
||||
///
|
||||
/// On creation, if you are on the server, this will run the `fetcher` once to generate
|
||||
/// a `Future` whose value will be serialized from the server to the client. If you are on
|
||||
/// the client, the initial value will be deserialized without re-running that async task.
|
||||
#[track_caller]
|
||||
pub fn new_serde_lite<S, Fut>(
|
||||
source: impl Fn() -> S + Send + Sync + 'static,
|
||||
@@ -522,6 +655,19 @@ where
|
||||
ArcResource::new_with_options(source, fetcher, false)
|
||||
}
|
||||
|
||||
/// Creates a new blocking resource with the encoding [`SerdeLite`].
|
||||
///
|
||||
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
|
||||
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
|
||||
/// generate a new [`Future`] to load data.
|
||||
///
|
||||
/// On creation, if you are on the server, this will run the `fetcher` once to generate
|
||||
/// a `Future` whose value will be serialized from the server to the client. If you are on
|
||||
/// the client, the initial value will be deserialized without re-running that async task.
|
||||
///
|
||||
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
|
||||
/// This is useful if you need their data to set HTML document metadata or information that
|
||||
/// needs to appear in HTTP headers.
|
||||
#[track_caller]
|
||||
pub fn new_serde_lite_blocking<S, Fut>(
|
||||
source: impl Fn() -> S + Send + Sync + 'static,
|
||||
@@ -547,6 +693,15 @@ where
|
||||
<RkyvCodec as Encoder<T>>::Encoded: IntoEncodedString,
|
||||
<RkyvCodec as Decoder<T>>::Encoded: FromEncodedStr,
|
||||
{
|
||||
/// Creates a new resource with the encoding [`RkyvCodec`].
|
||||
///
|
||||
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
|
||||
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
|
||||
/// generate a new [`Future`] to load data.
|
||||
///
|
||||
/// On creation, if you are on the server, this will run the `fetcher` once to generate
|
||||
/// a `Future` whose value will be serialized from the server to the client. If you are on
|
||||
/// the client, the initial value will be deserialized without re-running that async task.
|
||||
#[track_caller]
|
||||
pub fn new_rkyv<S, Fut>(
|
||||
source: impl Fn() -> S + Send + Sync + 'static,
|
||||
@@ -560,6 +715,19 @@ where
|
||||
ArcResource::new_with_options(source, fetcher, false)
|
||||
}
|
||||
|
||||
/// Creates a new blocking resource with the encoding [`RkyvCodec`].
|
||||
///
|
||||
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
|
||||
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
|
||||
/// generate a new [`Future`] to load data.
|
||||
///
|
||||
/// On creation, if you are on the server, this will run the `fetcher` once to generate
|
||||
/// a `Future` whose value will be serialized from the server to the client. If you are on
|
||||
/// the client, the initial value will be deserialized without re-running that async task.
|
||||
///
|
||||
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
|
||||
/// This is useful if you need their data to set HTML document metadata or information that
|
||||
/// needs to appear in HTTP headers.
|
||||
#[track_caller]
|
||||
pub fn new_rkyv_blocking<S, Fut>(
|
||||
source: impl Fn() -> S + Send + Sync + 'static,
|
||||
@@ -590,11 +758,22 @@ impl<T, Ser> ArcResource<T, Ser>
|
||||
where
|
||||
T: 'static,
|
||||
{
|
||||
/// Returns a new [`Future`] that is ready when the resource has loaded, and accesses its inner
|
||||
/// value by reference.
|
||||
pub fn by_ref(&self) -> AsyncDerivedRefFuture<T> {
|
||||
self.data.by_ref()
|
||||
}
|
||||
}
|
||||
|
||||
/// An asynchronous resource.
|
||||
///
|
||||
/// Resources allow asynchronously loading data and serializing it from the server to the client,
|
||||
/// so that it loads on the server, and is then deserialized on the client. This improves
|
||||
/// performance by beginning data loading on the server when the request is made, rather than
|
||||
/// beginning it on the client after WASM has been loaded.
|
||||
///
|
||||
/// You can access the value of the resource either synchronously using `.get()` or asynchronously
|
||||
/// using `.await`.
|
||||
pub struct Resource<T, Ser = JsonSerdeCodec>
|
||||
where
|
||||
T: Send + Sync + 'static,
|
||||
@@ -602,7 +781,7 @@ where
|
||||
ser: PhantomData<Ser>,
|
||||
data: AsyncDerived<T>,
|
||||
refetch: RwSignal<usize>,
|
||||
#[cfg(debug_assertions)]
|
||||
#[cfg(any(debug_assertions, leptos_debuginfo))]
|
||||
defined_at: &'static Location<'static>,
|
||||
}
|
||||
|
||||
@@ -613,7 +792,7 @@ where
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
let mut d = f.debug_struct("ArcResource");
|
||||
d.field("ser", &self.ser).field("data", &self.data);
|
||||
#[cfg(debug_assertions)]
|
||||
#[cfg(any(debug_assertions, leptos_debuginfo))]
|
||||
d.field("defined_at", self.defined_at);
|
||||
d.finish_non_exhaustive()
|
||||
}
|
||||
@@ -624,11 +803,11 @@ where
|
||||
T: Send + Sync + 'static,
|
||||
{
|
||||
fn defined_at(&self) -> Option<&'static Location<'static>> {
|
||||
#[cfg(debug_assertions)]
|
||||
#[cfg(any(debug_assertions, leptos_debuginfo))]
|
||||
{
|
||||
Some(self.defined_at)
|
||||
}
|
||||
#[cfg(not(debug_assertions))]
|
||||
#[cfg(not(any(debug_assertions, leptos_debuginfo)))]
|
||||
{
|
||||
None
|
||||
}
|
||||
@@ -707,6 +886,15 @@ where
|
||||
<FromToStringCodec as Decoder<T>>::Encoded: FromEncodedStr,
|
||||
T: Send + Sync,
|
||||
{
|
||||
/// Creates a new resource with the encoding [`FromToStringCodec`].
|
||||
///
|
||||
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
|
||||
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
|
||||
/// generate a new [`Future`] to load data.
|
||||
///
|
||||
/// On creation, if you are on the server, this will run the `fetcher` once to generate
|
||||
/// a `Future` whose value will be serialized from the server to the client. If you are on
|
||||
/// the client, the initial value will be deserialized without re-running that async task.
|
||||
#[track_caller]
|
||||
pub fn new_str<S, Fut>(
|
||||
source: impl Fn() -> S + Send + Sync + 'static,
|
||||
@@ -720,6 +908,19 @@ where
|
||||
Resource::new_with_options(source, fetcher, false)
|
||||
}
|
||||
|
||||
/// Creates a new blocking resource with the encoding [`FromToStringCodec`].
|
||||
///
|
||||
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
|
||||
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
|
||||
/// generate a new [`Future`] to load data.
|
||||
///
|
||||
/// On creation, if you are on the server, this will run the `fetcher` once to generate
|
||||
/// a `Future` whose value will be serialized from the server to the client. If you are on
|
||||
/// the client, the initial value will be deserialized without re-running that async task.
|
||||
///
|
||||
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
|
||||
/// This is useful if you need their data to set HTML document metadata or information that
|
||||
/// needs to appear in HTTP headers.
|
||||
#[track_caller]
|
||||
pub fn new_str_blocking<S, Fut>(
|
||||
source: impl Fn() -> S + Send + Sync + 'static,
|
||||
@@ -745,6 +946,15 @@ where
|
||||
<JsonSerdeCodec as Decoder<T>>::Encoded: FromEncodedStr,
|
||||
T: Send + Sync,
|
||||
{
|
||||
/// Creates a new resource with the encoding [`JsonSerdeCodec`].
|
||||
///
|
||||
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
|
||||
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
|
||||
/// generate a new [`Future`] to load data.
|
||||
///
|
||||
/// On creation, if you are on the server, this will run the `fetcher` once to generate
|
||||
/// a `Future` whose value will be serialized from the server to the client. If you are on
|
||||
/// the client, the initial value will be deserialized without re-running that async task.
|
||||
#[track_caller]
|
||||
pub fn new<S, Fut>(
|
||||
source: impl Fn() -> S + Send + Sync + 'static,
|
||||
@@ -758,6 +968,19 @@ where
|
||||
Resource::new_with_options(source, fetcher, false)
|
||||
}
|
||||
|
||||
/// Creates a new blocking resource with the encoding [`JsonSerdeCodec`].
|
||||
///
|
||||
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
|
||||
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
|
||||
/// generate a new [`Future`] to load data.
|
||||
///
|
||||
/// On creation, if you are on the server, this will run the `fetcher` once to generate
|
||||
/// a `Future` whose value will be serialized from the server to the client. If you are on
|
||||
/// the client, the initial value will be deserialized without re-running that async task.
|
||||
///
|
||||
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
|
||||
/// This is useful if you need their data to set HTML document metadata or information that
|
||||
/// needs to appear in HTTP headers.
|
||||
#[track_caller]
|
||||
pub fn new_blocking<S, Fut>(
|
||||
source: impl Fn() -> S + Send + Sync + 'static,
|
||||
@@ -782,6 +1005,15 @@ where
|
||||
<JsonSerdeWasmCodec as Decoder<T>>::Encoded: FromEncodedStr,
|
||||
T: Send + Sync,
|
||||
{
|
||||
/// Creates a new resource with the encoding [`JsonSerdeWasmCodec`].
|
||||
///
|
||||
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
|
||||
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
|
||||
/// generate a new [`Future`] to load data.
|
||||
///
|
||||
/// On creation, if you are on the server, this will run the `fetcher` once to generate
|
||||
/// a `Future` whose value will be serialized from the server to the client. If you are on
|
||||
/// the client, the initial value will be deserialized without re-running that async task.
|
||||
pub fn new_serde_wb<S, Fut>(
|
||||
source: impl Fn() -> S + Send + Sync + 'static,
|
||||
fetcher: impl Fn(S) -> Fut + Send + Sync + 'static,
|
||||
@@ -794,6 +1026,19 @@ where
|
||||
Resource::new_with_options(source, fetcher, false)
|
||||
}
|
||||
|
||||
/// Creates a new blocking resource with the encoding [`JsonSerdeWasmCodec`].
|
||||
///
|
||||
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
|
||||
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
|
||||
/// generate a new [`Future`] to load data.
|
||||
///
|
||||
/// On creation, if you are on the server, this will run the `fetcher` once to generate
|
||||
/// a `Future` whose value will be serialized from the server to the client. If you are on
|
||||
/// the client, the initial value will be deserialized without re-running that async task.
|
||||
///
|
||||
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
|
||||
/// This is useful if you need their data to set HTML document metadata or information that
|
||||
/// needs to appear in HTTP headers.
|
||||
pub fn new_serde_wb_blocking<S, Fut>(
|
||||
source: impl Fn() -> S + Send + Sync + 'static,
|
||||
fetcher: impl Fn(S) -> Fut + Send + Sync + 'static,
|
||||
@@ -819,6 +1064,15 @@ where
|
||||
<MiniserdeCodec as Decoder<T>>::Encoded: FromEncodedStr,
|
||||
T: Send + Sync,
|
||||
{
|
||||
/// Creates a new resource with the encoding [`MiniserdeCodec`].
|
||||
///
|
||||
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
|
||||
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
|
||||
/// generate a new [`Future`] to load data.
|
||||
///
|
||||
/// On creation, if you are on the server, this will run the `fetcher` once to generate
|
||||
/// a `Future` whose value will be serialized from the server to the client. If you are on
|
||||
/// the client, the initial value will be deserialized without re-running that async task.
|
||||
pub fn new_miniserde<S, Fut>(
|
||||
source: impl Fn() -> S + Send + Sync + 'static,
|
||||
fetcher: impl Fn(S) -> Fut + Send + Sync + 'static,
|
||||
@@ -830,6 +1084,31 @@ where
|
||||
{
|
||||
Resource::new_with_options(source, fetcher, false)
|
||||
}
|
||||
|
||||
/// Creates a new blocking resource with the encoding [`MiniserdeCodec`].
|
||||
///
|
||||
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
|
||||
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
|
||||
/// generate a new [`Future`] to load data.
|
||||
///
|
||||
/// On creation, if you are on the server, this will run the `fetcher` once to generate
|
||||
/// a `Future` whose value will be serialized from the server to the client. If you are on
|
||||
/// the client, the initial value will be deserialized without re-running that async task.
|
||||
///
|
||||
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
|
||||
/// This is useful if you need their data to set HTML document metadata or information that
|
||||
/// needs to appear in HTTP headers.
|
||||
pub fn new_miniserde_blocking<S, Fut>(
|
||||
source: impl Fn() -> S + Send + Sync + 'static,
|
||||
fetcher: impl Fn(S) -> Fut + Send + Sync + 'static,
|
||||
) -> Self
|
||||
where
|
||||
S: PartialEq + Clone + Send + Sync + 'static,
|
||||
T: Send + Sync + 'static,
|
||||
Fut: Future<Output = T> + Send + 'static,
|
||||
{
|
||||
Resource::new_with_options(source, fetcher, true)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "serde-lite")]
|
||||
@@ -843,6 +1122,15 @@ where
|
||||
<SerdeLite<JsonSerdeCodec> as Decoder<T>>::Encoded: FromEncodedStr,
|
||||
T: Send + Sync,
|
||||
{
|
||||
/// Creates a new resource with the encoding [`SerdeLite`].
|
||||
///
|
||||
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
|
||||
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
|
||||
/// generate a new [`Future`] to load data.
|
||||
///
|
||||
/// On creation, if you are on the server, this will run the `fetcher` once to generate
|
||||
/// a `Future` whose value will be serialized from the server to the client. If you are on
|
||||
/// the client, the initial value will be deserialized without re-running that async task.
|
||||
pub fn new_serde_lite<S, Fut>(
|
||||
source: impl Fn() -> S + Send + Sync + 'static,
|
||||
fetcher: impl Fn(S) -> Fut + Send + Sync + 'static,
|
||||
@@ -855,6 +1143,19 @@ where
|
||||
Resource::new_with_options(source, fetcher, false)
|
||||
}
|
||||
|
||||
/// Creates a new blocking resource with the encoding [`SerdeLite`].
|
||||
///
|
||||
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
|
||||
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
|
||||
/// generate a new [`Future`] to load data.
|
||||
///
|
||||
/// On creation, if you are on the server, this will run the `fetcher` once to generate
|
||||
/// a `Future` whose value will be serialized from the server to the client. If you are on
|
||||
/// the client, the initial value will be deserialized without re-running that async task.
|
||||
///
|
||||
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
|
||||
/// This is useful if you need their data to set HTML document metadata or information that
|
||||
/// needs to appear in HTTP headers.
|
||||
pub fn new_serde_lite_blocking<S, Fut>(
|
||||
source: impl Fn() -> S + Send + Sync + 'static,
|
||||
fetcher: impl Fn(S) -> Fut + Send + Sync + 'static,
|
||||
@@ -880,6 +1181,15 @@ where
|
||||
<RkyvCodec as Decoder<T>>::Encoded: FromEncodedStr,
|
||||
T: Send + Sync,
|
||||
{
|
||||
/// Creates a new resource with the encoding [`RkyvCodec`].
|
||||
///
|
||||
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
|
||||
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
|
||||
/// generate a new [`Future`] to load data.
|
||||
///
|
||||
/// On creation, if you are on the server, this will run the `fetcher` once to generate
|
||||
/// a `Future` whose value will be serialized from the server to the client. If you are on
|
||||
/// the client, the initial value will be deserialized without re-running that async task.
|
||||
pub fn new_rkyv<S, Fut>(
|
||||
source: impl Fn() -> S + Send + Sync + 'static,
|
||||
fetcher: impl Fn(S) -> Fut + Send + Sync + 'static,
|
||||
@@ -892,6 +1202,19 @@ where
|
||||
Resource::new_with_options(source, fetcher, false)
|
||||
}
|
||||
|
||||
/// Creates a new blocking resource with the encoding [`RkyvCodec`].
|
||||
///
|
||||
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
|
||||
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
|
||||
/// generate a new [`Future`] to load data.
|
||||
///
|
||||
/// On creation, if you are on the server, this will run the `fetcher` once to generate
|
||||
/// a `Future` whose value will be serialized from the server to the client. If you are on
|
||||
/// the client, the initial value will be deserialized without re-running that async task.
|
||||
///
|
||||
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
|
||||
/// This is useful if you need their data to set HTML document metadata or information that
|
||||
/// needs to appear in HTTP headers.
|
||||
pub fn new_rkyv_blocking<S, Fut>(
|
||||
source: impl Fn() -> S + Send + Sync + 'static,
|
||||
fetcher: impl Fn(S) -> Fut + Send + Sync + 'static,
|
||||
@@ -915,6 +1238,21 @@ where
|
||||
<Ser as Decoder<T>>::Encoded: FromEncodedStr,
|
||||
T: Send + Sync,
|
||||
{
|
||||
/// Creates a new resource with the encoding `Ser`.
|
||||
///
|
||||
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
|
||||
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
|
||||
/// generate a new [`Future`] to load data.
|
||||
///
|
||||
/// On creation, if you are on the server, this will run the `fetcher` once to generate
|
||||
/// a `Future` whose value will be serialized from the server to the client. If you are on
|
||||
/// the client, the initial value will be deserialized without re-running that async task.
|
||||
///
|
||||
/// If `blocking` is `true`, this is a blocking resource.
|
||||
///
|
||||
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
|
||||
/// This is useful if you need their data to set HTML document metadata or information that
|
||||
/// needs to appear in HTTP headers.
|
||||
#[track_caller]
|
||||
pub fn new_with_options<S, Fut>(
|
||||
source: impl Fn() -> S + Send + Sync + 'static,
|
||||
@@ -932,11 +1270,13 @@ where
|
||||
ser: PhantomData,
|
||||
data: data.into(),
|
||||
refetch: refetch.into(),
|
||||
#[cfg(debug_assertions)]
|
||||
#[cfg(any(debug_assertions, leptos_debuginfo))]
|
||||
defined_at: Location::caller(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Synchronously, reactively reads the current value of the resource and applies the function
|
||||
/// `f` to its value if it is `Some(_)`.
|
||||
pub fn map<U>(&self, f: impl FnOnce(&T) -> U) -> Option<U> {
|
||||
self.data
|
||||
.try_with(|n| n.as_ref().map(|n| Some(f(n))))?
|
||||
@@ -961,6 +1301,13 @@ where
|
||||
T: Send + Sync,
|
||||
E: Send + Sync + Clone,
|
||||
{
|
||||
/// Applies the given function when a resource that returns `Result<T, E>`
|
||||
/// has resolved and loaded an `Ok(_)`, rather than requiring nested `.map()`
|
||||
/// calls over the `Option<Result<_, _>>` returned by the resource.
|
||||
///
|
||||
/// This is useful when used with features like server functions, in conjunction
|
||||
/// with `<ErrorBoundary/>` and `<Suspense/>`, when these other components are
|
||||
/// left to handle the `None` and `Err(_)` states.
|
||||
#[track_caller]
|
||||
pub fn and_then<U>(&self, f: impl FnOnce(&T) -> U) -> Option<Result<U, E>> {
|
||||
self.map(|data| data.as_ref().map(f).map_err(|e| e.clone()))
|
||||
@@ -984,6 +1331,8 @@ impl<T, Ser> Resource<T, Ser>
|
||||
where
|
||||
T: Send + Sync + 'static,
|
||||
{
|
||||
/// Returns a new [`Future`] that is ready when the resource has loaded, and accesses its inner
|
||||
/// value by reference.
|
||||
pub fn by_ref(&self) -> AsyncDerivedRefFuture<T> {
|
||||
self.data.by_ref()
|
||||
}
|
||||
|
||||
@@ -31,6 +31,7 @@ pub struct SharedValue<T, Ser = JsonSerdeCodec> {
|
||||
}
|
||||
|
||||
impl<T, Ser> SharedValue<T, Ser> {
|
||||
/// Returns the inner value.
|
||||
pub fn into_inner(self) -> T {
|
||||
self.value
|
||||
}
|
||||
@@ -46,6 +47,12 @@ where
|
||||
<<JsonSerdeCodec as codee::Decoder<T>>::Encoded as FromEncodedStr>::DecodingError:
|
||||
Debug,
|
||||
{
|
||||
/// Wraps the initial value.
|
||||
///
|
||||
/// If this is on the server, the function will be invoked and the value serialized. When it runs
|
||||
/// on the client, it will be deserialized without running the function again.
|
||||
///
|
||||
/// This uses the [`JsonSerdeCodec`] encoding.
|
||||
pub fn new(initial: impl FnOnce() -> T) -> Self {
|
||||
SharedValue::new_with_encoding(initial)
|
||||
}
|
||||
@@ -61,6 +68,12 @@ where
|
||||
<<FromToStringCodec as codee::Decoder<T>>::Encoded as FromEncodedStr>::DecodingError:
|
||||
Debug,
|
||||
{
|
||||
/// Wraps the initial value.
|
||||
///
|
||||
/// If this is on the server, the function will be invoked and the value serialized. When it runs
|
||||
/// on the client, it will be deserialized without running the function again.
|
||||
///
|
||||
/// This uses the [`FromToStringCodec`] encoding.
|
||||
pub fn new_str(initial: impl FnOnce() -> T) -> Self {
|
||||
SharedValue::new_with_encoding(initial)
|
||||
}
|
||||
@@ -77,7 +90,13 @@ where
|
||||
<<SerdeLite<JsonSerdeCodec> as codee::Decoder<T>>::Encoded as FromEncodedStr>::DecodingError:
|
||||
Debug,
|
||||
{
|
||||
pub fn new(initial: impl FnOnce() -> T) -> Self {
|
||||
/// Wraps the initial value.
|
||||
///
|
||||
/// If this is on the server, the function will be invoked and the value serialized. When it runs
|
||||
/// on the client, it will be deserialized without running the function again.
|
||||
///
|
||||
/// This uses the [`SerdeLite`] encoding.
|
||||
pub fn new_serde_lite(initial: impl FnOnce() -> T) -> Self {
|
||||
SharedValue::new_with_encoding(initial)
|
||||
}
|
||||
}
|
||||
@@ -93,7 +112,13 @@ where
|
||||
<<JsonSerdeWasmCodec as codee::Decoder<T>>::Encoded as FromEncodedStr>::DecodingError:
|
||||
Debug,
|
||||
{
|
||||
pub fn new(initial: impl FnOnce() -> T) -> Self {
|
||||
/// Wraps the initial value.
|
||||
///
|
||||
/// If this is on the server, the function will be invoked and the value serialized. When it runs
|
||||
/// on the client, it will be deserialized without running the function again.
|
||||
///
|
||||
/// This uses the [`JsonSerdeWasmCodec`] encoding.
|
||||
pub fn new_serde_wb(initial: impl FnOnce() -> T) -> Self {
|
||||
SharedValue::new_with_encoding(initial)
|
||||
}
|
||||
}
|
||||
@@ -109,7 +134,13 @@ where
|
||||
<<MiniserdeCodec as codee::Decoder<T>>::Encoded as FromEncodedStr>::DecodingError:
|
||||
Debug,
|
||||
{
|
||||
pub fn new(initial: impl FnOnce() -> T) -> Self {
|
||||
/// Wraps the initial value.
|
||||
///
|
||||
/// If this is on the server, the function will be invoked and the value serialized. When it runs
|
||||
/// on the client, it will be deserialized without running the function again.
|
||||
///
|
||||
/// This uses the [`MiniserdeCodec`] encoding.
|
||||
pub fn new_miniserde(initial: impl FnOnce() -> T) -> Self {
|
||||
SharedValue::new_with_encoding(initial)
|
||||
}
|
||||
}
|
||||
@@ -125,7 +156,13 @@ where
|
||||
<<RkyvCodec as codee::Decoder<T>>::Encoded as FromEncodedStr>::DecodingError:
|
||||
Debug,
|
||||
{
|
||||
pub fn new(initial: impl FnOnce() -> T) -> Self {
|
||||
/// Wraps the initial value.
|
||||
///
|
||||
/// If this is on the server, the function will be invoked and the value serialized. When it runs
|
||||
/// on the client, it will be deserialized without running the function again.
|
||||
///
|
||||
/// This uses the [`RkyvCodec`] encoding.
|
||||
pub fn new_rkyv(initial: impl FnOnce() -> T) -> Self {
|
||||
SharedValue::new_with_encoding(initial)
|
||||
}
|
||||
}
|
||||
@@ -140,6 +177,12 @@ where
|
||||
<<Ser as codee::Decoder<T>>::Encoded as FromEncodedStr>::DecodingError:
|
||||
Debug,
|
||||
{
|
||||
/// Wraps the initial value.
|
||||
///
|
||||
/// If this is on the server, the function will be invoked and the value serialized. When it runs
|
||||
/// on the client, it will be deserialized without running the function again.
|
||||
///
|
||||
/// This uses `Ser` as an encoding.
|
||||
pub fn new_with_encoding(initial: impl FnOnce() -> T) -> Self {
|
||||
let value: T;
|
||||
#[cfg(feature = "hydration")]
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "leptos_meta"
|
||||
version = "0.7.0-rc1"
|
||||
version = "0.7.5"
|
||||
authors = ["Greg Johnston"]
|
||||
license = "MIT"
|
||||
repository = "https://github.com/leptos-rs/leptos"
|
||||
@@ -14,8 +14,8 @@ once_cell = "1.20"
|
||||
or_poisoned = { workspace = true }
|
||||
indexmap = "2.6"
|
||||
send_wrapper = "0.6.0"
|
||||
tracing = { version = "0.1.40", optional = true }
|
||||
wasm-bindgen = "0.2.95"
|
||||
tracing = { version = "0.1.41", optional = true }
|
||||
wasm-bindgen = "0.2.97"
|
||||
futures = "0.3.31"
|
||||
|
||||
[dependencies.web-sys]
|
||||
@@ -26,9 +26,13 @@ features = ["HtmlLinkElement", "HtmlMetaElement", "HtmlTitleElement"]
|
||||
default = []
|
||||
ssr = []
|
||||
tracing = ["dep:tracing"]
|
||||
nonce = ["leptos/nonce"]
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
rustdoc-args = ["--generate-link-to-definition"]
|
||||
|
||||
[package.metadata.cargo-all-features]
|
||||
denylist = ["tracing"]
|
||||
|
||||
[lints.rust]
|
||||
unexpected_cfgs = { level = "warn", check-cfg = ['cfg(leptos_debuginfo)'] }
|
||||
|
||||
@@ -7,8 +7,7 @@
|
||||
//! using the [`Leptos`](https://github.com/leptos-rs/leptos) web framework.
|
||||
//!
|
||||
//! Document metadata is updated automatically when running in the browser. For server-side
|
||||
//! rendering, after the component tree is rendered to HTML, [`MetaContext::dehydrate`] can generate
|
||||
//! HTML that should be injected into the `<head>` of the HTML document being rendered.
|
||||
//! rendering, after the component tree is rendered to HTML, [`ServerMetaContextOutput::inject_meta_context`] will inject meta tags into a stream of HTML inside the `<head>`.
|
||||
//!
|
||||
//! ```
|
||||
//! use leptos::prelude::*;
|
||||
@@ -38,20 +37,17 @@
|
||||
//! }
|
||||
//! ```
|
||||
//! # Feature Flags
|
||||
//! - `csr` Client-side rendering: Generate DOM nodes in the browser
|
||||
//! - `ssr` Server-side rendering: Generate an HTML string (typically on the server)
|
||||
//! - `hydrate` Hydration: use this to add interactivity to an SSRed Leptos app
|
||||
//! - `stable` By default, Leptos requires `nightly` Rust, which is what allows the ergonomics
|
||||
//! of calling signals as functions. Enable this feature to support `stable` Rust.
|
||||
//! - `tracing` Adds integration with the `tracing` crate.
|
||||
//!
|
||||
//! **Important Note:** You must enable one of `csr`, `hydrate`, or `ssr` to tell Leptos
|
||||
//! which mode your app is operating in.
|
||||
//! **Important Note:** If you’re using server-side rendering, you should enable `ssr`.
|
||||
|
||||
use futures::{Stream, StreamExt};
|
||||
use leptos::{
|
||||
attr::NextAttribute,
|
||||
component,
|
||||
logging::debug_warn,
|
||||
oco::Oco,
|
||||
reactive::owner::{provide_context, use_context},
|
||||
tachys::{
|
||||
dom::document,
|
||||
@@ -571,3 +567,25 @@ impl RenderHtml for MetaTagsView {
|
||||
) -> Self::State {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) trait OrDefaultNonce {
|
||||
fn or_default_nonce(self) -> Option<Oco<'static, str>>;
|
||||
}
|
||||
|
||||
impl OrDefaultNonce for Option<Oco<'static, str>> {
|
||||
fn or_default_nonce(self) -> Option<Oco<'static, str>> {
|
||||
#[cfg(feature = "nonce")]
|
||||
{
|
||||
use leptos::nonce::use_nonce;
|
||||
|
||||
match self {
|
||||
Some(nonce) => Some(nonce),
|
||||
None => use_nonce().map(|n| Arc::clone(n.as_inner()).into()),
|
||||
}
|
||||
}
|
||||
#[cfg(not(feature = "nonce"))]
|
||||
{
|
||||
self
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::register;
|
||||
use crate::{register, OrDefaultNonce};
|
||||
use leptos::{
|
||||
component, oco::Oco, prelude::*, tachys::html::element::script, IntoView,
|
||||
};
|
||||
@@ -74,7 +74,7 @@ pub fn Script(
|
||||
.fetchpriority(fetchpriority)
|
||||
.integrity(integrity)
|
||||
.nomodule(nomodule)
|
||||
.nonce(nonce)
|
||||
.nonce(nonce.or_default_nonce())
|
||||
.referrerpolicy(referrerpolicy)
|
||||
.src(src)
|
||||
.r#type(type_)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::register;
|
||||
use crate::{register, OrDefaultNonce};
|
||||
use leptos::{
|
||||
component, oco::Oco, prelude::*, tachys::html::element::style, IntoView,
|
||||
};
|
||||
@@ -48,7 +48,7 @@ pub fn Style(
|
||||
style()
|
||||
.id(id)
|
||||
.media(media)
|
||||
.nonce(nonce)
|
||||
.nonce(nonce.or_default_nonce())
|
||||
.title(title)
|
||||
.blocking(blocking)
|
||||
.child(children.map(|c| c())),
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "next_tuple"
|
||||
version = "0.1.0-rc1"
|
||||
version = "0.1.0"
|
||||
authors = ["Greg Johnston"]
|
||||
license = "MIT"
|
||||
readme = "../README.md"
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
//! Defines a trait that allows you to extend a tuple, by returning
|
||||
//! a new tuple with an element of an arbitrary type added.
|
||||
|
||||
#![no_std]
|
||||
#![allow(non_snake_case)]
|
||||
#![forbid(unsafe_code)]
|
||||
#![deny(missing_docs)]
|
||||
|
||||
/// Allows extending a tuple, or creating a new tuple, by adding the next value.
|
||||
pub trait NextTuple {
|
||||
|
||||
@@ -70,7 +70,7 @@ pub enum Oco<'a, T: ?Sized + ToOwned + 'a> {
|
||||
Owned(<T as ToOwned>::Owned),
|
||||
}
|
||||
|
||||
impl<'a, T: ?Sized + ToOwned> Oco<'a, T> {
|
||||
impl<T: ?Sized + ToOwned> Oco<'_, T> {
|
||||
/// Converts the value into an owned value.
|
||||
pub fn into_owned(self) -> <T as ToOwned>::Owned {
|
||||
match self {
|
||||
@@ -339,7 +339,7 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, 'b, A: ?Sized, B: ?Sized> PartialEq<Oco<'b, B>> for Oco<'a, A>
|
||||
impl<'b, A: ?Sized, B: ?Sized> PartialEq<Oco<'b, B>> for Oco<'_, A>
|
||||
where
|
||||
A: PartialEq<B>,
|
||||
A: ToOwned,
|
||||
@@ -352,7 +352,7 @@ where
|
||||
|
||||
impl<T: ?Sized + ToOwned + Eq> Eq for Oco<'_, T> {}
|
||||
|
||||
impl<'a, 'b, A: ?Sized, B: ?Sized> PartialOrd<Oco<'b, B>> for Oco<'a, A>
|
||||
impl<'b, A: ?Sized, B: ?Sized> PartialOrd<Oco<'b, B>> for Oco<'_, A>
|
||||
where
|
||||
A: PartialOrd<B>,
|
||||
A: ToOwned,
|
||||
@@ -551,7 +551,7 @@ impl_slice_eq!(['a, 'b, T: PartialEq] (where [T]: ToOwned), Oco<'a, [T]>, &'b [T
|
||||
impl_slice_eq!([T: PartialEq] (where [T]: ToOwned), Oco<'_, [T]>, Vec<T>);
|
||||
impl_slice_eq!(['a, 'b, T: PartialEq] (where [T]: ToOwned), Oco<'a, [T]>, Cow<'b, [T]>);
|
||||
|
||||
impl<'a, 'b> Add<&'b str> for Oco<'a, str> {
|
||||
impl<'b> Add<&'b str> for Oco<'_, str> {
|
||||
type Output = Oco<'static, str>;
|
||||
|
||||
fn add(self, rhs: &'b str) -> Self::Output {
|
||||
@@ -559,7 +559,7 @@ impl<'a, 'b> Add<&'b str> for Oco<'a, str> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, 'b> Add<Cow<'b, str>> for Oco<'a, str> {
|
||||
impl<'b> Add<Cow<'b, str>> for Oco<'_, str> {
|
||||
type Output = Oco<'static, str>;
|
||||
|
||||
fn add(self, rhs: Cow<'b, str>) -> Self::Output {
|
||||
@@ -567,7 +567,7 @@ impl<'a, 'b> Add<Cow<'b, str>> for Oco<'a, str> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, 'b> Add<Oco<'b, str>> for Oco<'a, str> {
|
||||
impl<'b> Add<Oco<'b, str>> for Oco<'_, str> {
|
||||
type Output = Oco<'static, str>;
|
||||
|
||||
fn add(self, rhs: Oco<'b, str>) -> Self::Output {
|
||||
|
||||
14
projects/hexagonal-architecture/.gitignore
vendored
Normal file
14
projects/hexagonal-architecture/.gitignore
vendored
Normal file
@@ -0,0 +1,14 @@
|
||||
# Generated by Cargo
|
||||
# will have compiled files and executables
|
||||
debug/
|
||||
target/
|
||||
|
||||
# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
|
||||
# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html
|
||||
Cargo.lock
|
||||
|
||||
# These are backup files generated by rustfmt
|
||||
**/*.rs.bk
|
||||
|
||||
# MSVC Windows builds of rustc generate these, which store debugging information
|
||||
*.pdb
|
||||
111
projects/hexagonal-architecture/Cargo.toml
Normal file
111
projects/hexagonal-architecture/Cargo.toml
Normal file
@@ -0,0 +1,111 @@
|
||||
[package]
|
||||
name = "leptos-hexagonal-design"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib", "rlib"]
|
||||
|
||||
[dependencies]
|
||||
leptos = { version = "0.7.0" }
|
||||
leptos_router = { version = "0.7.0" }
|
||||
axum = { version = "0.7", optional = true }
|
||||
console_error_panic_hook = "0.1"
|
||||
leptos_axum = { version = "0.7.0", optional = true }
|
||||
leptos_meta = { version = "0.7.0" }
|
||||
tokio = { version = "1", features = ["rt-multi-thread"], optional = true }
|
||||
tower = { version = "0.4", optional = true }
|
||||
tower-http = { version = "0.5", features = ["fs"], optional = true }
|
||||
wasm-bindgen = "=0.2.99"
|
||||
thiserror = "1"
|
||||
tracing = { version = "0.1", optional = true }
|
||||
http = "1"
|
||||
mockall = "0.13.1"
|
||||
cfg-if = "1.0.0"
|
||||
serde = "1.0.215"
|
||||
pin-project-lite = "0.2.15"
|
||||
|
||||
[features]
|
||||
config_1 = []
|
||||
hydrate = ["leptos/hydrate"]
|
||||
ssr = [
|
||||
"dep:axum",
|
||||
"dep:tokio",
|
||||
"dep:tower",
|
||||
"dep:tower-http",
|
||||
"dep:leptos_axum",
|
||||
"leptos/ssr",
|
||||
"leptos_meta/ssr",
|
||||
"leptos_router/ssr",
|
||||
"dep:tracing",
|
||||
]
|
||||
|
||||
# Defines a size-optimized profile for the WASM bundle in release mode
|
||||
[profile.wasm-release]
|
||||
inherits = "release"
|
||||
opt-level = 'z'
|
||||
lto = true
|
||||
codegen-units = 1
|
||||
panic = "abort"
|
||||
|
||||
[package.metadata.leptos]
|
||||
# The name used by wasm-bindgen/cargo-leptos for the JS/WASM bundle. Defaults to the crate name
|
||||
output-name = "leptos-hexagonal-design"
|
||||
|
||||
# The site root folder is where cargo-leptos generate all output. WARNING: all content of this folder will be erased on a rebuild. Use it in your server setup.
|
||||
site-root = "target/site"
|
||||
|
||||
# The site-root relative folder where all compiled output (JS, WASM and CSS) is written
|
||||
# Defaults to pkg
|
||||
site-pkg-dir = "pkg"
|
||||
|
||||
# [Optional] The source CSS file. If it ends with .sass or .scss then it will be compiled by dart-sass into CSS. The CSS is optimized by Lightning CSS before being written to <site-root>/<site-pkg>/app.css
|
||||
style-file = "style/main.scss"
|
||||
# Assets source dir. All files found here will be copied and synchronized to site-root.
|
||||
# The assets-dir cannot have a sub directory with the same name/path as site-pkg-dir.
|
||||
#
|
||||
# Optional. Env: LEPTOS_ASSETS_DIR.
|
||||
assets-dir = "public"
|
||||
|
||||
# The IP and port (ex: 127.0.0.1:3000) where the server serves the content. Use it in your server setup.
|
||||
site-addr = "127.0.0.1:3000"
|
||||
|
||||
# The port to use for automatic reload monitoring
|
||||
reload-port = 3001
|
||||
|
||||
# [Optional] Command to use when running end2end tests. It will run in the end2end dir.
|
||||
# [Windows] for non-WSL use "npx.cmd playwright test"
|
||||
# This binary name can be checked in Powershell with Get-Command npx
|
||||
end2end-cmd = "npx playwright test"
|
||||
end2end-dir = "end2end"
|
||||
|
||||
# The browserlist query used for optimizing the CSS.
|
||||
browserquery = "defaults"
|
||||
|
||||
# The environment Leptos will run in, usually either "DEV" or "PROD"
|
||||
env = "DEV"
|
||||
|
||||
# The features to use when compiling the bin target
|
||||
#
|
||||
# Optional. Can be over-ridden with the command line parameter --bin-features
|
||||
bin-features = ["ssr"]
|
||||
|
||||
# If the --no-default-features flag should be used when compiling the bin target
|
||||
#
|
||||
# Optional. Defaults to false.
|
||||
bin-default-features = false
|
||||
|
||||
# The features to use when compiling the lib target
|
||||
#
|
||||
# Optional. Can be over-ridden with the command line parameter --lib-features
|
||||
lib-features = ["hydrate"]
|
||||
|
||||
# If the --no-default-features flag should be used when compiling the lib target
|
||||
#
|
||||
# Optional. Defaults to false.
|
||||
lib-default-features = false
|
||||
|
||||
# The profile to use for the lib target when compiling for release
|
||||
#
|
||||
# Optional. Defaults to "release".
|
||||
lib-profile-release = "wasm-release"
|
||||
24
projects/hexagonal-architecture/LICENSE
Normal file
24
projects/hexagonal-architecture/LICENSE
Normal file
@@ -0,0 +1,24 @@
|
||||
This is free and unencumbered software released into the public domain.
|
||||
|
||||
Anyone is free to copy, modify, publish, use, compile, sell, or
|
||||
distribute this software, either in source code form or as a compiled
|
||||
binary, for any purpose, commercial or non-commercial, and by any
|
||||
means.
|
||||
|
||||
In jurisdictions that recognize copyright laws, the author or authors
|
||||
of this software dedicate any and all copyright interest in the
|
||||
software to the public domain. We make this dedication for the benefit
|
||||
of the public at large and to the detriment of our heirs and
|
||||
successors. We intend this dedication to be an overt act of
|
||||
relinquishment in perpetuity of all present and future rights to this
|
||||
software under copyright law.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
||||
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
|
||||
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
|
||||
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
For more information, please refer to <https://unlicense.org>
|
||||
142
projects/hexagonal-architecture/README.md
Normal file
142
projects/hexagonal-architecture/README.md
Normal file
@@ -0,0 +1,142 @@
|
||||
### Leptos Hexagonal Design
|
||||
|
||||
This Blog Post / Github Repository is about applying principles of hexagonal design
|
||||
- Isolating Business Logic from Sub Domains
|
||||
- Decoupling design to improve flexibility and testablity
|
||||
- Applying the principles hierachically so that sub domains which talk to external services also implement also implement hexagonal architecture
|
||||
|
||||
|
||||
There are specific constraints that guide our design decisions
|
||||
|
||||
- Server Functions Can't be Generic
|
||||
- Boxed Traits Objects Have overhead, so we only want to use as much generic code as possible avoid Trait Objects
|
||||
|
||||
The way this works is we define the functionality of our program in the main domain (i.e the business problem and processes our app is trying to solve / proceduralize). We then create sub domains and external services, although they are represented the same. External services are usually the end nodes of your app's architectural graph. Our main application builds it's service layout using configuration flags.
|
||||
|
||||
```rust
|
||||
pub fn config() -> MainAppHandlerAlias {
|
||||
cfg_if::cfg_if! {
|
||||
if #[cfg(feature="open_ai_wrapper")] {
|
||||
fn server_handler_config_1() -> MainAppHandler<
|
||||
AuthService<PostgresDb, Redis>,
|
||||
AiMessageGen<PostgresDb,OpenAiWrapper>,
|
||||
> {
|
||||
MainAppHandler::new_with_postgres_and_redis_open_ai()
|
||||
}
|
||||
server_handler_config_1()
|
||||
} else {
|
||||
fn server_handler_config_2() -> MainAppHandler<
|
||||
AuthService<MySql, MemCache>,
|
||||
OtherAiMessageGen<MySql,HuggingFaceWrapper>,
|
||||
> {
|
||||
MainAppHandler::new_with_my_sql_memcache_hugging_face()
|
||||
}
|
||||
server_handler_config_2()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
And we pass in our handler which implements a trait
|
||||
|
||||
```rust
|
||||
pub trait HandlerServerFn {
|
||||
pub fn server_fn_1_inner(&self);
|
||||
}
|
||||
impl<S,S2> HandlerServerFn for MainAppHandler<S:SubDomain1Trait,S2:SubDomain2Trait> {
|
||||
pub fn server_fn_1_inner(&self) {
|
||||
// do thing
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
in our main fn we produce our applications service graph and pass it to our leptos router.
|
||||
|
||||
```rust
|
||||
main () {
|
||||
let leptos_options = conf.leptos_options;
|
||||
let routes = generate_route_list(crate::app::App);
|
||||
// our feature flag based config function.
|
||||
let handler = config();
|
||||
let handler_c = handler.clone();
|
||||
// we implement FromRef<ServerState> for LeptosOptions
|
||||
let server_state = ServerState {
|
||||
handler,
|
||||
leptos_options: leptos_options.clone(),
|
||||
};
|
||||
let app = Router::new()
|
||||
.leptos_routes_with_context(
|
||||
&server_state,
|
||||
routes,
|
||||
// We pass in the MainAppHandler struct as context so we can fetch it anywhere context is available on the server.
|
||||
// This includes in middleware we define on server functions (see middleware.rs)
|
||||
move || provide_context(handler_c.clone()),
|
||||
{
|
||||
let leptos_options = leptos_options.clone();
|
||||
move || shell(leptos_options.clone())
|
||||
},
|
||||
)
|
||||
.fallback(leptos_axum::file_and_error_handler::<
|
||||
ServerState<HandlerStructAlias>,
|
||||
_,
|
||||
>(shell))
|
||||
.with_state(server_state);
|
||||
}
|
||||
```
|
||||
|
||||
and then in our server functions
|
||||
|
||||
```rust
|
||||
#[server]
|
||||
pub async fn server_fn_1() -> Result<(),ServerFnError> {
|
||||
// we type alias every variation of our services we plan on configuring. The alternative is using Box<dyn Trait> which isn't bad - just slower.
|
||||
Ok(expect_context::<MainAppHandlerAlias>().server_fn_1_inner())
|
||||
}
|
||||
```
|
||||
|
||||
And then we can mock and service trait in any combination like so
|
||||
|
||||
```rust
|
||||
#[tokio::test]
|
||||
pub async fn test_subdomain_1_with_mocks() -> Result<(), Box<dyn Error>> {
|
||||
let mut mock_external_service_1 = MockExternalServiceTrait1::new();
|
||||
mock_external_service_1
|
||||
.expect_external_service_1_method()
|
||||
.returning(|| {
|
||||
println!("Mock external service 1");
|
||||
Ok(ExternalService1Data)
|
||||
});
|
||||
let mut mock_external_service_2 = MockExternalServiceTrait2::new();
|
||||
mock_external_service_2
|
||||
.expect_external_service_2_method()
|
||||
.returning(|| {
|
||||
println!("Mock external service 2");
|
||||
Ok(ExternalService2Data)
|
||||
});
|
||||
let real_subdomain_1_with_mock_externals = SubDomainStruct1 {
|
||||
external_service_1: mock_external_service_1,
|
||||
external_service_2: mock_external_service_2,
|
||||
};
|
||||
let data = real_subdomain_1_with_mock_externals
|
||||
.sub_domain_1_method()
|
||||
.await?;
|
||||
assert_eq!(data, SubDomain1Data);
|
||||
Ok(())
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
Check out the code in the repository for a working example.
|
||||
|
||||
Run the tests with
|
||||
|
||||
` cargo test --features ssr `
|
||||
and otherwise run
|
||||
` cargo leptos serve `
|
||||
and navigate to `127.0.0.1:3000`
|
||||
|
||||
here's a picture
|
||||
|
||||
|
||||

|
||||
167
projects/hexagonal-architecture/end2end/package-lock.json
generated
Normal file
167
projects/hexagonal-architecture/end2end/package-lock.json
generated
Normal file
@@ -0,0 +1,167 @@
|
||||
{
|
||||
"name": "end2end",
|
||||
"version": "1.0.0",
|
||||
"lockfileVersion": 2,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "end2end",
|
||||
"version": "1.0.0",
|
||||
"license": "ISC",
|
||||
"devDependencies": {
|
||||
"@playwright/test": "^1.44.1",
|
||||
"@types/node": "^20.12.12",
|
||||
"typescript": "^5.4.5"
|
||||
}
|
||||
},
|
||||
"node_modules/@playwright/test": {
|
||||
"version": "1.44.1",
|
||||
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.44.1.tgz",
|
||||
"integrity": "sha512-1hZ4TNvD5z9VuhNJ/walIjvMVvYkZKf71axoF/uiAqpntQJXpG64dlXhoDXE3OczPuTuvjf/M5KWFg5VAVUS3Q==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"playwright": "1.44.1"
|
||||
},
|
||||
"bin": {
|
||||
"playwright": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=16"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/node": {
|
||||
"version": "20.12.12",
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-20.12.12.tgz",
|
||||
"integrity": "sha512-eWLDGF/FOSPtAvEqeRAQ4C8LSA7M1I7i0ky1I8U7kD1J5ITyW3AsRhQrKVoWf5pFKZ2kILsEGJhsI9r93PYnOw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"undici-types": "~5.26.4"
|
||||
}
|
||||
},
|
||||
"node_modules/fsevents": {
|
||||
"version": "2.3.2",
|
||||
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",
|
||||
"integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",
|
||||
"dev": true,
|
||||
"hasInstallScript": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"engines": {
|
||||
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/playwright": {
|
||||
"version": "1.44.1",
|
||||
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.44.1.tgz",
|
||||
"integrity": "sha512-qr/0UJ5CFAtloI3avF95Y0L1xQo6r3LQArLIg/z/PoGJ6xa+EwzrwO5lpNr/09STxdHuUoP2mvuELJS+hLdtgg==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"playwright-core": "1.44.1"
|
||||
},
|
||||
"bin": {
|
||||
"playwright": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=16"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"fsevents": "2.3.2"
|
||||
}
|
||||
},
|
||||
"node_modules/playwright-core": {
|
||||
"version": "1.44.1",
|
||||
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.44.1.tgz",
|
||||
"integrity": "sha512-wh0JWtYTrhv1+OSsLPgFzGzt67Y7BE/ZS3jEqgGBlp2ppp1ZDj8c+9IARNW4dwf1poq5MgHreEM2KV/GuR4cFA==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"bin": {
|
||||
"playwright-core": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=16"
|
||||
}
|
||||
},
|
||||
"node_modules/typescript": {
|
||||
"version": "5.4.5",
|
||||
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.4.5.tgz",
|
||||
"integrity": "sha512-vcI4UpRgg81oIRUFwR0WSIHKt11nJ7SAVlYNIu+QpqeyXP+gpQJy/Z4+F0aGxSE4MqwjyXvW/TzgkLAx2AGHwQ==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"bin": {
|
||||
"tsc": "bin/tsc",
|
||||
"tsserver": "bin/tsserver"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14.17"
|
||||
}
|
||||
},
|
||||
"node_modules/undici-types": {
|
||||
"version": "5.26.5",
|
||||
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz",
|
||||
"integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
}
|
||||
},
|
||||
"dependencies": {
|
||||
"@playwright/test": {
|
||||
"version": "1.44.1",
|
||||
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.44.1.tgz",
|
||||
"integrity": "sha512-1hZ4TNvD5z9VuhNJ/walIjvMVvYkZKf71axoF/uiAqpntQJXpG64dlXhoDXE3OczPuTuvjf/M5KWFg5VAVUS3Q==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"playwright": "1.44.1"
|
||||
}
|
||||
},
|
||||
"@types/node": {
|
||||
"version": "20.12.12",
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-20.12.12.tgz",
|
||||
"integrity": "sha512-eWLDGF/FOSPtAvEqeRAQ4C8LSA7M1I7i0ky1I8U7kD1J5ITyW3AsRhQrKVoWf5pFKZ2kILsEGJhsI9r93PYnOw==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"undici-types": "~5.26.4"
|
||||
}
|
||||
},
|
||||
"fsevents": {
|
||||
"version": "2.3.2",
|
||||
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",
|
||||
"integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",
|
||||
"dev": true,
|
||||
"optional": true
|
||||
},
|
||||
"playwright": {
|
||||
"version": "1.44.1",
|
||||
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.44.1.tgz",
|
||||
"integrity": "sha512-qr/0UJ5CFAtloI3avF95Y0L1xQo6r3LQArLIg/z/PoGJ6xa+EwzrwO5lpNr/09STxdHuUoP2mvuELJS+hLdtgg==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"fsevents": "2.3.2",
|
||||
"playwright-core": "1.44.1"
|
||||
}
|
||||
},
|
||||
"playwright-core": {
|
||||
"version": "1.44.1",
|
||||
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.44.1.tgz",
|
||||
"integrity": "sha512-wh0JWtYTrhv1+OSsLPgFzGzt67Y7BE/ZS3jEqgGBlp2ppp1ZDj8c+9IARNW4dwf1poq5MgHreEM2KV/GuR4cFA==",
|
||||
"dev": true
|
||||
},
|
||||
"typescript": {
|
||||
"version": "5.4.5",
|
||||
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.4.5.tgz",
|
||||
"integrity": "sha512-vcI4UpRgg81oIRUFwR0WSIHKt11nJ7SAVlYNIu+QpqeyXP+gpQJy/Z4+F0aGxSE4MqwjyXvW/TzgkLAx2AGHwQ==",
|
||||
"dev": true
|
||||
},
|
||||
"undici-types": {
|
||||
"version": "5.26.5",
|
||||
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz",
|
||||
"integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==",
|
||||
"dev": true
|
||||
}
|
||||
}
|
||||
}
|
||||
15
projects/hexagonal-architecture/end2end/package.json
Normal file
15
projects/hexagonal-architecture/end2end/package.json
Normal file
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"name": "end2end",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"main": "index.js",
|
||||
"scripts": {},
|
||||
"keywords": [],
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
"devDependencies": {
|
||||
"@playwright/test": "^1.44.1",
|
||||
"@types/node": "^20.12.12",
|
||||
"typescript": "^5.4.5"
|
||||
}
|
||||
}
|
||||
105
projects/hexagonal-architecture/end2end/playwright.config.ts
Normal file
105
projects/hexagonal-architecture/end2end/playwright.config.ts
Normal file
@@ -0,0 +1,105 @@
|
||||
import type { PlaywrightTestConfig } from "@playwright/test";
|
||||
import { devices, defineConfig } from "@playwright/test";
|
||||
|
||||
/**
|
||||
* Read environment variables from file.
|
||||
* https://github.com/motdotla/dotenv
|
||||
*/
|
||||
// require('dotenv').config();
|
||||
|
||||
/**
|
||||
* See https://playwright.dev/docs/test-configuration.
|
||||
*/
|
||||
export default defineConfig({
|
||||
testDir: "./tests",
|
||||
/* Maximum time one test can run for. */
|
||||
timeout: 30 * 1000,
|
||||
expect: {
|
||||
/**
|
||||
* Maximum time expect() should wait for the condition to be met.
|
||||
* For example in `await expect(locator).toHaveText();`
|
||||
*/
|
||||
timeout: 5000,
|
||||
},
|
||||
/* Run tests in files in parallel */
|
||||
fullyParallel: true,
|
||||
/* Fail the build on CI if you accidentally left test.only in the source code. */
|
||||
forbidOnly: !!process.env.CI,
|
||||
/* Retry on CI only */
|
||||
retries: process.env.CI ? 2 : 0,
|
||||
/* Opt out of parallel tests on CI. */
|
||||
workers: process.env.CI ? 1 : undefined,
|
||||
/* Reporter to use. See https://playwright.dev/docs/test-reporters */
|
||||
reporter: "html",
|
||||
/* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */
|
||||
use: {
|
||||
/* Maximum time each action such as `click()` can take. Defaults to 0 (no limit). */
|
||||
actionTimeout: 0,
|
||||
/* Base URL to use in actions like `await page.goto('/')`. */
|
||||
// baseURL: 'http://localhost:3000',
|
||||
|
||||
/* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */
|
||||
trace: "on-first-retry",
|
||||
},
|
||||
|
||||
/* Configure projects for major browsers */
|
||||
projects: [
|
||||
{
|
||||
name: "chromium",
|
||||
use: {
|
||||
...devices["Desktop Chrome"],
|
||||
},
|
||||
},
|
||||
|
||||
{
|
||||
name: "firefox",
|
||||
use: {
|
||||
...devices["Desktop Firefox"],
|
||||
},
|
||||
},
|
||||
|
||||
{
|
||||
name: "webkit",
|
||||
use: {
|
||||
...devices["Desktop Safari"],
|
||||
},
|
||||
},
|
||||
|
||||
/* Test against mobile viewports. */
|
||||
// {
|
||||
// name: 'Mobile Chrome',
|
||||
// use: {
|
||||
// ...devices['Pixel 5'],
|
||||
// },
|
||||
// },
|
||||
// {
|
||||
// name: 'Mobile Safari',
|
||||
// use: {
|
||||
// ...devices['iPhone 12'],
|
||||
// },
|
||||
// },
|
||||
|
||||
/* Test against branded browsers. */
|
||||
// {
|
||||
// name: 'Microsoft Edge',
|
||||
// use: {
|
||||
// channel: 'msedge',
|
||||
// },
|
||||
// },
|
||||
// {
|
||||
// name: 'Google Chrome',
|
||||
// use: {
|
||||
// channel: 'chrome',
|
||||
// },
|
||||
// },
|
||||
],
|
||||
|
||||
/* Folder for test artifacts such as screenshots, videos, traces, etc. */
|
||||
// outputDir: 'test-results/',
|
||||
|
||||
/* Run your local dev server before starting the tests */
|
||||
// webServer: {
|
||||
// command: 'npm run start',
|
||||
// port: 3000,
|
||||
// },
|
||||
});
|
||||
@@ -0,0 +1,9 @@
|
||||
import { test, expect } from "@playwright/test";
|
||||
|
||||
test("homepage has title and heading text", async ({ page }) => {
|
||||
await page.goto("http://localhost:3000/");
|
||||
|
||||
await expect(page).toHaveTitle("Welcome to Leptos");
|
||||
|
||||
await expect(page.locator("h1")).toHaveText("Welcome to Leptos!");
|
||||
});
|
||||
109
projects/hexagonal-architecture/end2end/tsconfig.json
Normal file
109
projects/hexagonal-architecture/end2end/tsconfig.json
Normal file
@@ -0,0 +1,109 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
/* Visit https://aka.ms/tsconfig to read more about this file */
|
||||
|
||||
/* Projects */
|
||||
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
|
||||
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
|
||||
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
|
||||
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
|
||||
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
|
||||
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
|
||||
|
||||
/* Language and Environment */
|
||||
"target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
|
||||
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
|
||||
// "jsx": "preserve", /* Specify what JSX code is generated. */
|
||||
// "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
|
||||
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
|
||||
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
|
||||
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
|
||||
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
|
||||
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
|
||||
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
|
||||
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
|
||||
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
|
||||
|
||||
/* Modules */
|
||||
"module": "commonjs", /* Specify what module code is generated. */
|
||||
// "rootDir": "./", /* Specify the root folder within your source files. */
|
||||
// "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */
|
||||
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
|
||||
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
|
||||
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
|
||||
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
|
||||
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
|
||||
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
|
||||
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
|
||||
// "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
|
||||
// "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
|
||||
// "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
|
||||
// "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
|
||||
// "resolveJsonModule": true, /* Enable importing .json files. */
|
||||
// "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
|
||||
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
|
||||
|
||||
/* JavaScript Support */
|
||||
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
|
||||
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
|
||||
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
|
||||
|
||||
/* Emit */
|
||||
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
|
||||
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
|
||||
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
|
||||
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
|
||||
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
|
||||
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
|
||||
// "outDir": "./", /* Specify an output folder for all emitted files. */
|
||||
// "removeComments": true, /* Disable emitting comments. */
|
||||
// "noEmit": true, /* Disable emitting files from a compilation. */
|
||||
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
|
||||
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
|
||||
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
|
||||
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
|
||||
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
|
||||
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
|
||||
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
|
||||
// "newLine": "crlf", /* Set the newline character for emitting files. */
|
||||
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
|
||||
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
|
||||
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
|
||||
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
|
||||
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
|
||||
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
|
||||
|
||||
/* Interop Constraints */
|
||||
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
|
||||
// "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
|
||||
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
|
||||
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
|
||||
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
|
||||
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
|
||||
|
||||
/* Type Checking */
|
||||
"strict": true, /* Enable all strict type-checking options. */
|
||||
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
|
||||
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
|
||||
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
|
||||
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
|
||||
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
|
||||
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
|
||||
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
|
||||
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
|
||||
// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
|
||||
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
|
||||
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
|
||||
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
|
||||
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
|
||||
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
|
||||
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
|
||||
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
|
||||
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
|
||||
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
|
||||
|
||||
/* Completeness */
|
||||
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
|
||||
"skipLibCheck": true /* Skip type checking all .d.ts files. */
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 292 KiB |
BIN
projects/hexagonal-architecture/public/favicon.ico
Normal file
BIN
projects/hexagonal-architecture/public/favicon.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 15 KiB |
87
projects/hexagonal-architecture/src/app.rs
Normal file
87
projects/hexagonal-architecture/src/app.rs
Normal file
@@ -0,0 +1,87 @@
|
||||
use leptos::prelude::*;
|
||||
use leptos_meta::{provide_meta_context, MetaTags, Stylesheet, Title};
|
||||
use leptos_router::{
|
||||
components::{Route, Router, Routes},
|
||||
StaticSegment,
|
||||
};
|
||||
|
||||
#[cfg(feature = "ssr")]
|
||||
use super::{server_types::HandlerStructAlias, traits::HandlerTrait};
|
||||
use crate::ui_types::*;
|
||||
pub fn shell(options: LeptosOptions) -> impl IntoView {
|
||||
view! {
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8"/>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1"/>
|
||||
<AutoReload options=options.clone() />
|
||||
<HydrationScripts options/>
|
||||
<MetaTags/>
|
||||
</head>
|
||||
<body>
|
||||
<App/>
|
||||
</body>
|
||||
</html>
|
||||
}
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn App() -> impl IntoView {
|
||||
// Provides context that manages stylesheets, titles, meta tags, etc.
|
||||
provide_meta_context();
|
||||
|
||||
view! {
|
||||
// injects a stylesheet into the document <head>
|
||||
// id=leptos means cargo-leptos will hot-reload this stylesheet
|
||||
<Stylesheet id="leptos" href="/pkg/leptos-hexagonal-design.css"/>
|
||||
|
||||
// sets the document title
|
||||
<Title text="Welcome to Leptos"/>
|
||||
|
||||
// content for this welcome page
|
||||
<Router>
|
||||
<main>
|
||||
<Routes fallback=|| "Page not found.".into_view()>
|
||||
<Route path=StaticSegment("") view=HomePage/>
|
||||
</Routes>
|
||||
</main>
|
||||
</Router>
|
||||
}
|
||||
}
|
||||
|
||||
/// Renders the home page of your application.
|
||||
#[component]
|
||||
fn HomePage() -> impl IntoView {
|
||||
let server_fn_1 = ServerAction::<ServerFunction1>::new();
|
||||
let server_fn_2 = ServerAction::<ServerFunction2>::new();
|
||||
let server_fn_3 = ServerAction::<ServerFunction3>::new();
|
||||
Effect::new(move |_| {
|
||||
server_fn_1.dispatch(ServerFunction1 {});
|
||||
server_fn_2.dispatch(ServerFunction2 {});
|
||||
server_fn_3.dispatch(ServerFunction3 {});
|
||||
});
|
||||
}
|
||||
|
||||
#[server]
|
||||
#[middleware(crate::middleware::SubDomain1Layer)]
|
||||
pub async fn server_function_1() -> Result<UiMappingFromDomainData, ServerFnError> {
|
||||
Ok(expect_context::<HandlerStructAlias>()
|
||||
.server_fn_1()
|
||||
.await?
|
||||
.into())
|
||||
}
|
||||
#[server]
|
||||
pub async fn server_function_2() -> Result<UiMappingFromDomainData2, ServerFnError> {
|
||||
Ok(expect_context::<HandlerStructAlias>()
|
||||
.server_fn_2()
|
||||
.await?
|
||||
.into())
|
||||
}
|
||||
#[server]
|
||||
pub async fn server_function_3() -> Result<UiMappingFromDomainData3, ServerFnError> {
|
||||
Ok(expect_context::<HandlerStructAlias>()
|
||||
.server_fn_3()
|
||||
.await?
|
||||
.into())
|
||||
}
|
||||
23
projects/hexagonal-architecture/src/config.rs
Normal file
23
projects/hexagonal-architecture/src/config.rs
Normal file
@@ -0,0 +1,23 @@
|
||||
use super::server_types::*;
|
||||
|
||||
pub fn config() -> HandlerStructAlias {
|
||||
cfg_if::cfg_if! {
|
||||
if #[cfg(feature="config_1")] {
|
||||
fn server_handler_config_1() -> HandlerStruct<
|
||||
SubDomainStruct1<ExternalService1_1, ExternalService2_1>,
|
||||
SubDomainStruct2<ExternalService1_1>,
|
||||
> {
|
||||
HandlerStruct::default()
|
||||
}
|
||||
server_handler_config_1()
|
||||
} else {
|
||||
fn server_handler_config_2() -> HandlerStruct<
|
||||
SubDomainStruct1<ExternalService1_2, ExternalService2_2>,
|
||||
SubDomainStruct2<ExternalService1_2>,
|
||||
> {
|
||||
HandlerStruct::new()
|
||||
}
|
||||
server_handler_config_2()
|
||||
}
|
||||
}
|
||||
}
|
||||
150
projects/hexagonal-architecture/src/lib.rs
Normal file
150
projects/hexagonal-architecture/src/lib.rs
Normal file
@@ -0,0 +1,150 @@
|
||||
pub mod app;
|
||||
|
||||
pub mod ui_types;
|
||||
|
||||
#[cfg(feature = "ssr")]
|
||||
pub mod config;
|
||||
#[cfg(feature = "ssr")]
|
||||
pub mod middleware;
|
||||
#[cfg(feature = "ssr")]
|
||||
pub mod server_types;
|
||||
#[cfg(feature = "ssr")]
|
||||
pub mod trait_impl;
|
||||
#[cfg(feature = "ssr")]
|
||||
pub mod traits;
|
||||
|
||||
#[cfg(feature = "hydrate")]
|
||||
#[wasm_bindgen::prelude::wasm_bindgen]
|
||||
pub fn hydrate() {
|
||||
use crate::app::*;
|
||||
console_error_panic_hook::set_once();
|
||||
leptos::mount::hydrate_body(App);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub mod tests {
|
||||
use super::server_types::*;
|
||||
use super::traits::*;
|
||||
use std::error::Error;
|
||||
|
||||
#[tokio::test]
|
||||
pub async fn test_subdomain_1_with_mocks() -> Result<(), Box<dyn Error>> {
|
||||
let mut mock_external_service_1 = MockExternalServiceTrait1::new();
|
||||
mock_external_service_1
|
||||
.expect_external_service_1_method()
|
||||
.returning(|| {
|
||||
println!("Mock external service 1");
|
||||
Ok(ExternalService1Data)
|
||||
});
|
||||
let mut mock_external_service_2 = MockExternalServiceTrait2::new();
|
||||
mock_external_service_2
|
||||
.expect_external_service_2_method()
|
||||
.returning(|| {
|
||||
println!("Mock external service 2");
|
||||
Ok(ExternalService2Data)
|
||||
});
|
||||
let real_subdomain_1_with_mock_externals = SubDomainStruct1 {
|
||||
external_service_1: mock_external_service_1,
|
||||
external_service_2: mock_external_service_2,
|
||||
};
|
||||
let data = real_subdomain_1_with_mock_externals
|
||||
.sub_domain_1_method()
|
||||
.await?;
|
||||
assert_eq!(data, SubDomain1Data);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
pub async fn test_subdomain_2_with_mocks() -> Result<(), Box<dyn Error>> {
|
||||
let mut mock_external_service_1 = MockExternalServiceTrait1::new();
|
||||
mock_external_service_1
|
||||
.expect_external_service_1_method()
|
||||
.returning(|| {
|
||||
println!("Mock external service 1 AGAIN");
|
||||
Ok(ExternalService1Data)
|
||||
});
|
||||
let real_subdomain_2_with_mock_externals = SubDomainStruct2 {
|
||||
external_service_1: mock_external_service_1,
|
||||
};
|
||||
let data = real_subdomain_2_with_mock_externals
|
||||
.sub_domain_2_method()
|
||||
.await?;
|
||||
assert_eq!(data, SubDomain2Data);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
pub async fn test_handler_with_mocks() -> Result<(), Box<dyn Error>> {
|
||||
let mut mock_subdomain_1_trait = MockSubDomainTrait1::new();
|
||||
mock_subdomain_1_trait
|
||||
.expect_sub_domain_1_method()
|
||||
.returning(|| {
|
||||
println!("Mock Subdomain 1");
|
||||
Ok(SubDomain1Data)
|
||||
});
|
||||
let mut mock_subdomain_2_trait = MockSubDomainTrait2::new();
|
||||
mock_subdomain_2_trait
|
||||
.expect_sub_domain_2_method()
|
||||
.returning(|| {
|
||||
println!("Mock Subdomain 2");
|
||||
Ok(SubDomain2Data)
|
||||
});
|
||||
let real_handler_with_mock_subdomains = HandlerStruct {
|
||||
sub_domain_1: mock_subdomain_1_trait,
|
||||
sub_domain_2: mock_subdomain_2_trait,
|
||||
};
|
||||
let data = real_handler_with_mock_subdomains.server_fn_1().await?;
|
||||
assert_eq!(data, DomainData);
|
||||
let data = real_handler_with_mock_subdomains.server_fn_2().await?;
|
||||
assert_eq!(data, DomainData2);
|
||||
let data = real_handler_with_mock_subdomains.server_fn_3().await?;
|
||||
assert_eq!(data, DomainData3);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn mock_subdomain_1() -> SubDomainStruct1<MockExternalServiceTrait1, MockExternalServiceTrait2>
|
||||
{
|
||||
let mut mock_external_service_1 = MockExternalServiceTrait1::new();
|
||||
mock_external_service_1
|
||||
.expect_external_service_1_method()
|
||||
.returning(|| {
|
||||
println!("Mock external service 1");
|
||||
Ok(ExternalService1Data)
|
||||
});
|
||||
let mut mock_external_service_2 = MockExternalServiceTrait2::new();
|
||||
mock_external_service_2
|
||||
.expect_external_service_2_method()
|
||||
.returning(|| {
|
||||
println!("Mock external service 2");
|
||||
Ok(ExternalService2Data)
|
||||
});
|
||||
let real_subdomain_1_with_mock_externals = SubDomainStruct1 {
|
||||
external_service_1: mock_external_service_1,
|
||||
external_service_2: mock_external_service_2,
|
||||
};
|
||||
real_subdomain_1_with_mock_externals
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
pub async fn test_handler_with_mock_and_real_mix() -> Result<(), Box<dyn Error>> {
|
||||
let sub_domain_1 = mock_subdomain_1();
|
||||
let mut mock_subdomain_2_trait = MockSubDomainTrait2::new();
|
||||
mock_subdomain_2_trait
|
||||
.expect_sub_domain_2_method()
|
||||
.returning(|| {
|
||||
println!("Mock Subdomain 2");
|
||||
Ok(SubDomain2Data)
|
||||
});
|
||||
let real_handler = HandlerStruct {
|
||||
sub_domain_1,
|
||||
sub_domain_2: mock_subdomain_2_trait,
|
||||
};
|
||||
let data = real_handler.server_fn_1().await?;
|
||||
assert_eq!(data, DomainData);
|
||||
let data = real_handler.server_fn_2().await?;
|
||||
assert_eq!(data, DomainData2);
|
||||
let data = real_handler.server_fn_3().await?;
|
||||
assert_eq!(data, DomainData3);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
52
projects/hexagonal-architecture/src/main.rs
Normal file
52
projects/hexagonal-architecture/src/main.rs
Normal file
@@ -0,0 +1,52 @@
|
||||
#[cfg(feature = "ssr")]
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
use axum::Router;
|
||||
use leptos::logging::log;
|
||||
use leptos::prelude::*;
|
||||
use leptos_axum::{generate_route_list, LeptosRoutes};
|
||||
use leptos_hexagonal_design::{
|
||||
app::*,
|
||||
config::config,
|
||||
server_types::{HandlerStructAlias, ServerState},
|
||||
};
|
||||
|
||||
let conf = get_configuration(None).unwrap();
|
||||
let addr = conf.leptos_options.site_addr;
|
||||
let leptos_options = conf.leptos_options;
|
||||
let routes = generate_route_list(App);
|
||||
let handler = config();
|
||||
let handler_c = handler.clone();
|
||||
let server_state = ServerState {
|
||||
handler,
|
||||
leptos_options: leptos_options.clone(),
|
||||
};
|
||||
let app = Router::new()
|
||||
.leptos_routes_with_context(
|
||||
&server_state,
|
||||
routes,
|
||||
move || provide_context(handler_c.clone()),
|
||||
{
|
||||
let leptos_options = leptos_options.clone();
|
||||
move || shell(leptos_options.clone())
|
||||
},
|
||||
)
|
||||
.fallback(leptos_axum::file_and_error_handler::<
|
||||
ServerState<HandlerStructAlias>,
|
||||
_,
|
||||
>(shell))
|
||||
.with_state(server_state);
|
||||
|
||||
log!("listening on http://{}", &addr);
|
||||
let listener = tokio::net::TcpListener::bind(&addr).await.unwrap();
|
||||
axum::serve(listener, app.into_make_service())
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "ssr"))]
|
||||
pub fn main() {
|
||||
// no client-side main function
|
||||
// unless we want this to work with e.g., Trunk for pure client-side testing
|
||||
// see lib.rs for hydration function instead
|
||||
}
|
||||
84
projects/hexagonal-architecture/src/middleware.rs
Normal file
84
projects/hexagonal-architecture/src/middleware.rs
Normal file
@@ -0,0 +1,84 @@
|
||||
use axum::{
|
||||
body::Body,
|
||||
http::{Request, Response},
|
||||
};
|
||||
use leptos::prelude::expect_context;
|
||||
use std::{
|
||||
future::Future,
|
||||
pin::Pin,
|
||||
task::{Context, Poll},
|
||||
};
|
||||
use tower::{Layer, Service};
|
||||
|
||||
use crate::{
|
||||
server_types::{HandlerStructAlias, ServerState},
|
||||
traits::SubDomainTrait1,
|
||||
};
|
||||
use pin_project_lite::pin_project;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct SubDomain1Layer;
|
||||
|
||||
impl<S> Layer<S> for SubDomain1Layer {
|
||||
type Service = SubDomain1MiddleWare<S>;
|
||||
|
||||
fn layer(&self, inner: S) -> Self::Service {
|
||||
SubDomain1MiddleWare { inner }
|
||||
}
|
||||
}
|
||||
|
||||
pub struct SubDomain1MiddleWare<S> {
|
||||
inner: S,
|
||||
}
|
||||
|
||||
impl<S, ReqBody> Service<Request<ReqBody>> for SubDomain1MiddleWare<S>
|
||||
where
|
||||
S: Service<Request<ReqBody>, Response = Response<Body>>,
|
||||
S::Error: std::fmt::Debug,
|
||||
S::Future: Send + 'static,
|
||||
{
|
||||
type Response = S::Response;
|
||||
type Error = S::Error;
|
||||
type Future = SubDomain1Future<S::Future>;
|
||||
|
||||
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||
self.inner.poll_ready(cx)
|
||||
}
|
||||
|
||||
fn call(&mut self, req: Request<ReqBody>) -> Self::Future {
|
||||
let req_fut = self.inner.call(req);
|
||||
SubDomain1Future { req_fut }
|
||||
}
|
||||
}
|
||||
pin_project! {
|
||||
pub struct SubDomain1Future<F> {
|
||||
#[pin]
|
||||
req_fut: F,
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, Err> Future for SubDomain1Future<F>
|
||||
where
|
||||
F: Future<Output = Result<Response<Body>, Err>>,
|
||||
{
|
||||
type Output = Result<Response<Body>, Err>;
|
||||
|
||||
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
||||
let this = self.project();
|
||||
let subdomain_1 = expect_context::<ServerState<HandlerStructAlias>>()
|
||||
.handler
|
||||
.sub_domain_1;
|
||||
let mut subdomain_1_fut = subdomain_1.sub_domain_1_method();
|
||||
match Pin::as_mut(&mut subdomain_1_fut).poll(cx) {
|
||||
Poll::Ready(Ok(_)) => {
|
||||
println!("Middleware for Subdomain 1 Passed, calling request...");
|
||||
this.req_fut.poll(cx)
|
||||
}
|
||||
Poll::Ready(Err(_)) => Poll::Ready(Ok(Response::builder()
|
||||
.status(http::StatusCode::FORBIDDEN)
|
||||
.body(Body::from("Access denied"))
|
||||
.unwrap())),
|
||||
Poll::Pending => Poll::Pending,
|
||||
}
|
||||
}
|
||||
}
|
||||
102
projects/hexagonal-architecture/src/server_types.rs
Normal file
102
projects/hexagonal-architecture/src/server_types.rs
Normal file
@@ -0,0 +1,102 @@
|
||||
use super::traits::*;
|
||||
use leptos::config::LeptosOptions;
|
||||
use thiserror::Error;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct ServerState<Handler: HandlerTrait> {
|
||||
pub handler: Handler,
|
||||
pub leptos_options: LeptosOptions,
|
||||
}
|
||||
|
||||
#[cfg(feature = "config_1")]
|
||||
pub type HandlerStructAlias = HandlerStruct<
|
||||
SubDomainStruct1<ExternalService1_1, ExternalService2_1>,
|
||||
SubDomainStruct2<ExternalService1_1>,
|
||||
>;
|
||||
#[cfg(not(feature = "config_1"))]
|
||||
pub type HandlerStructAlias = HandlerStruct<
|
||||
SubDomainStruct1<ExternalService1_2, ExternalService2_2>,
|
||||
SubDomainStruct2<ExternalService1_2>,
|
||||
>;
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
pub struct HandlerStruct<SubDomain1: SubDomainTrait1, SubDomain2: SubDomainTrait2> {
|
||||
pub sub_domain_1: SubDomain1,
|
||||
pub sub_domain_2: SubDomain2,
|
||||
}
|
||||
#[derive(Clone, Default)]
|
||||
pub struct SubDomainStruct1<
|
||||
ExternalService1: ExternalServiceTrait1,
|
||||
ExternalService2: ExternalServiceTrait2,
|
||||
> {
|
||||
pub external_service_1: ExternalService1,
|
||||
pub external_service_2: ExternalService2,
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
pub struct SubDomainStruct2<ExternalService1: ExternalServiceTrait1> {
|
||||
pub external_service_1: ExternalService1,
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
pub struct ExternalService1_1;
|
||||
#[derive(Clone, Default)]
|
||||
pub struct ExternalService1_2;
|
||||
#[derive(Clone, Default)]
|
||||
pub struct ExternalService2_1;
|
||||
#[derive(Clone, Default)]
|
||||
pub struct ExternalService2_2;
|
||||
#[derive(Clone, Default)]
|
||||
pub struct ExternalService1;
|
||||
|
||||
#[derive(Clone, PartialEq, Debug)]
|
||||
pub struct DomainData;
|
||||
#[derive(Clone, PartialEq, Debug)]
|
||||
pub struct DomainData2;
|
||||
#[derive(Clone, PartialEq, Debug)]
|
||||
pub struct DomainData3;
|
||||
#[derive(Clone, PartialEq, Debug)]
|
||||
pub struct SubDomain1Data;
|
||||
#[derive(Clone, PartialEq, Debug)]
|
||||
pub struct SubDomain2Data;
|
||||
#[derive(Clone)]
|
||||
pub struct ExternalService1Data;
|
||||
#[derive(Clone)]
|
||||
pub struct ExternalService2Data;
|
||||
|
||||
#[derive(Clone, Error, Debug)]
|
||||
pub enum DomainError {
|
||||
#[error("Underlying Subdomain 1 Error")]
|
||||
SubDomain1Error(#[from] SubDomain1Error),
|
||||
#[error("Underlying Subdomain 2 Error")]
|
||||
SubDomain2Error(#[from] SubDomain2Error),
|
||||
}
|
||||
|
||||
#[derive(Clone, Error, Debug)]
|
||||
pub enum SubDomain1Error {
|
||||
#[error("Sub Domain 1 Error")]
|
||||
SubDomain1Error,
|
||||
#[error("Underlying Service 1")]
|
||||
ExternalService1Error(#[from] ExternalService1Error),
|
||||
#[error("Underlying Service 2")]
|
||||
ExternalService2Error(#[from] ExternalService2Error),
|
||||
}
|
||||
#[derive(Clone, Error, Debug)]
|
||||
pub enum SubDomain2Error {
|
||||
#[error("Sub Domain 2 Error")]
|
||||
SubDomain2Error,
|
||||
#[error("Underlying Service 1")]
|
||||
ExternalService1Error(#[from] ExternalService1Error),
|
||||
}
|
||||
|
||||
#[derive(Clone, Error, Debug)]
|
||||
pub enum ExternalService1Error {
|
||||
#[error("Service 1 Error")]
|
||||
Error,
|
||||
}
|
||||
|
||||
#[derive(Clone, Error, Debug)]
|
||||
pub enum ExternalService2Error {
|
||||
#[error("Service 2 Error")]
|
||||
Error,
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user