mirror of
https://github.com/leptos-rs/leptos.git
synced 2025-12-27 15:44:42 -05:00
Compare commits
114 Commits
workspace-
...
v0.7.8
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9052804ab4 | ||
|
|
e95c903e85 | ||
|
|
8a179e6f45 | ||
|
|
e765f99016 | ||
|
|
30548eca31 | ||
|
|
d04d4c77f9 | ||
|
|
5c75928b5b | ||
|
|
abc5631654 | ||
|
|
40e5288ac1 | ||
|
|
6ee72f42e2 | ||
|
|
5cfe7f6b5e | ||
|
|
0404efd5c3 | ||
|
|
cd2904f6a6 | ||
|
|
5633148047 | ||
|
|
330920eae2 | ||
|
|
a94bc0a6da | ||
|
|
f85e01f4d6 | ||
|
|
d0bf843821 | ||
|
|
7250bc312e | ||
|
|
0e8242f94c | ||
|
|
439b41f0e8 | ||
|
|
a4e47d4086 | ||
|
|
3164721fdb | ||
|
|
2242ad1847 | ||
|
|
131b18bddb | ||
|
|
5e9d6e2dfd | ||
|
|
d76e5bb4ea | ||
|
|
f752e32ae3 | ||
|
|
a9197102a6 | ||
|
|
58f1bf95e1 | ||
|
|
38a3aae28e | ||
|
|
5eaaff045f | ||
|
|
e9384e3286 | ||
|
|
083f9c663f | ||
|
|
63c9549120 | ||
|
|
6232f6482a | ||
|
|
825e89f25c | ||
|
|
5da4c438d9 | ||
|
|
80ed74c075 | ||
|
|
79e9340a9b | ||
|
|
41d01cedb2 | ||
|
|
374a020d84 | ||
|
|
83fcf8663c | ||
|
|
1363b941bc | ||
|
|
f7a1a2cab2 | ||
|
|
92b82688a6 | ||
|
|
42988b1bc1 | ||
|
|
c75397ea75 | ||
|
|
848fd724dd | ||
|
|
5bc254d49f | ||
|
|
885f4a1654 | ||
|
|
ddd243d07a | ||
|
|
362c300eac | ||
|
|
284a724e5f | ||
|
|
6ecc681cdd | ||
|
|
7c34b4a4a5 | ||
|
|
37cf25fba5 | ||
|
|
f975b8d33b | ||
|
|
4804dac32d | ||
|
|
a9f27d6128 | ||
|
|
04cb036a7d | ||
|
|
1d3784ed7b | ||
|
|
8cc1a34c00 | ||
|
|
68f4d46c5f | ||
|
|
590728e47e | ||
|
|
e84b527743 | ||
|
|
96b125d54f | ||
|
|
16d66362f8 | ||
|
|
e27801a2c2 | ||
|
|
b81f71997b | ||
|
|
2a11325749 | ||
|
|
5604f3e979 | ||
|
|
3a9a0891a3 | ||
|
|
a39add50c0 | ||
|
|
2a2675dd36 | ||
|
|
7be6a9da86 | ||
|
|
c51e07b5a4 | ||
|
|
b17a4c92c7 | ||
|
|
03f9c6cb6d | ||
|
|
9e8b8886da | ||
|
|
6a6b3dee15 | ||
|
|
5d71913523 | ||
|
|
706617ab0a | ||
|
|
cd64bb9d67 | ||
|
|
f881c1877d | ||
|
|
8783f6a478 | ||
|
|
2add714c65 | ||
|
|
88b1b2d882 | ||
|
|
9d3a743d33 | ||
|
|
c6de7c714e | ||
|
|
6154199850 | ||
|
|
32be3a023a | ||
|
|
d9043e4f34 | ||
|
|
e3010c7f1f | ||
|
|
1dcc5838f7 | ||
|
|
1ff373dbc2 | ||
|
|
c35c42c6e3 | ||
|
|
d4cbba7c63 | ||
|
|
9cc8ee3c5a | ||
|
|
f0c5ffe55f | ||
|
|
586c330995 | ||
|
|
72f960a026 | ||
|
|
b62ae56094 | ||
|
|
9ccefbbd8c | ||
|
|
d1108826cc | ||
|
|
d6c4cd2a81 | ||
|
|
f8acdf9168 | ||
|
|
09bbae2a72 | ||
|
|
ac3352724b | ||
|
|
3413825638 | ||
|
|
22b2d8ec84 | ||
|
|
1c3e013a63 | ||
|
|
9d4b1bc4b7 | ||
|
|
f303ff9706 |
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
|
||||
|
||||
6
.github/workflows/ci-semver.yml
vendored
6
.github/workflows/ci-semver.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
|
||||
env:
|
||||
DEBIAN_FRONTEND: noninteractive
|
||||
jobs:
|
||||
@@ -16,7 +18,7 @@ jobs:
|
||||
test:
|
||||
needs: [get-leptos-changed]
|
||||
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)
|
||||
name: Run semver check (nightly-2025-03-05)
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Install Glib
|
||||
@@ -28,4 +30,4 @@ jobs:
|
||||
- name: Semver Checks
|
||||
uses: obi1kenobi/cargo-semver-checks-action@v2
|
||||
with:
|
||||
rust-toolchain: nightly-2024-08-01
|
||||
rust-toolchain: nightly-2025-03-05
|
||||
|
||||
4
.github/workflows/ci.yml
vendored
4
.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
|
||||
@@ -24,4 +26,4 @@ jobs:
|
||||
with:
|
||||
directory: ${{ matrix.directory }}
|
||||
cargo_make_task: "ci"
|
||||
toolchain: nightly-2024-08-01
|
||||
toolchain: nightly-2025-03-05
|
||||
|
||||
2
.github/workflows/run-cargo-make-task.yml
vendored
2
.github/workflows/run-cargo-make-task.yml
vendored
@@ -55,7 +55,7 @@ jobs:
|
||||
- name: Install wasm-bindgen
|
||||
run: cargo binstall wasm-bindgen-cli --no-confirm
|
||||
- name: Install cargo-leptos
|
||||
run: cargo binstall cargo-leptos --no-confirm
|
||||
run: cargo binstall cargo-leptos --locked --no-confirm
|
||||
- name: Install Trunk
|
||||
uses: jetli/trunk-action@v0.5.0
|
||||
with:
|
||||
|
||||
776
Cargo.lock
generated
776
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
43
Cargo.toml
43
Cargo.toml
@@ -40,36 +40,39 @@ members = [
|
||||
exclude = ["benchmarks", "examples", "projects"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.7.4"
|
||||
version = "0.7.8"
|
||||
edition = "2021"
|
||||
rust-version = "1.76"
|
||||
|
||||
[workspace.dependencies]
|
||||
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.0" }
|
||||
either_of = { path = "./either_of/", version = "0.1.0" }
|
||||
const_str_slice_concat = { path = "./const_str_slice_concat", version = "0.1" }
|
||||
either_of = { path = "./either_of/", version = "0.1.5" }
|
||||
hydration_context = { path = "./hydration_context", version = "0.2.0" }
|
||||
leptos = { path = "./leptos", version = "0.7.4" }
|
||||
leptos_config = { path = "./leptos_config", version = "0.7.4" }
|
||||
leptos_dom = { path = "./leptos_dom", version = "0.7.4" }
|
||||
leptos_hot_reload = { path = "./leptos_hot_reload", version = "0.7.4" }
|
||||
leptos_integration_utils = { path = "./integrations/utils", version = "0.7.4" }
|
||||
leptos_macro = { path = "./leptos_macro", version = "0.7.4" }
|
||||
leptos_router = { path = "./router", version = "0.7.4" }
|
||||
leptos_router_macro = { path = "./router_macro", version = "0.7.4" }
|
||||
leptos_server = { path = "./leptos_server", version = "0.7.4" }
|
||||
leptos_meta = { path = "./meta", version = "0.7.4" }
|
||||
itertools = "0.14.0"
|
||||
leptos = { path = "./leptos", version = "0.7.8" }
|
||||
leptos_config = { path = "./leptos_config", version = "0.7.8" }
|
||||
leptos_dom = { path = "./leptos_dom", version = "0.7.8" }
|
||||
leptos_hot_reload = { path = "./leptos_hot_reload", version = "0.7.8" }
|
||||
leptos_integration_utils = { path = "./integrations/utils", version = "0.7.8" }
|
||||
leptos_macro = { path = "./leptos_macro", version = "0.7.8" }
|
||||
leptos_router = { path = "./router", version = "0.7.8" }
|
||||
leptos_router_macro = { path = "./router_macro", version = "0.7.8" }
|
||||
leptos_server = { path = "./leptos_server", version = "0.7.8" }
|
||||
leptos_meta = { path = "./meta", version = "0.7.8" }
|
||||
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" }
|
||||
reactive_stores = { path = "./reactive_stores", version = "0.1.0" }
|
||||
reactive_stores_macro = { path = "./reactive_stores_macro", version = "0.1.0" }
|
||||
server_fn = { path = "./server_fn", version = "0.7.4" }
|
||||
server_fn_macro = { path = "./server_fn_macro", version = "0.7.4" }
|
||||
server_fn_macro_default = { path = "./server_fn/server_fn_macro_default", version = "0.7.4" }
|
||||
tachys = { path = "./tachys", version = "0.1.0" }
|
||||
reactive_graph = { path = "./reactive_graph", version = "0.1.7" }
|
||||
reactive_stores = { path = "./reactive_stores", version = "0.1.7" }
|
||||
reactive_stores_macro = { path = "./reactive_stores_macro", version = "0.1.7" }
|
||||
serde_json = "1.0.0"
|
||||
server_fn = { path = "./server_fn", version = "0.7.8" }
|
||||
server_fn_macro = { path = "./server_fn_macro", version = "0.7.8" }
|
||||
server_fn_macro_default = { path = "./server_fn/server_fn_macro_default", version = "0.7.8" }
|
||||
tachys = { path = "./tachys", version = "0.1.7" }
|
||||
wasm-bindgen = { version = "0.2.100" }
|
||||
|
||||
[profile.release]
|
||||
codegen-units = 1
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
|
||||
[](https://crates.io/crates/leptos)
|
||||
[](https://docs.rs/leptos)
|
||||

|
||||
[](https://discord.gg/YdRAhS7eQB)
|
||||
[](https://matrix.to/#/#leptos:matrix.org)
|
||||
|
||||
@@ -20,7 +21,7 @@ use leptos::*;
|
||||
#[component]
|
||||
pub fn SimpleCounter(initial_value: i32) -> impl IntoView {
|
||||
// create a reactive signal with the initial value
|
||||
let (value, set_value) = create_signal(initial_value);
|
||||
let (value, set_value) = signal(initial_value);
|
||||
|
||||
// create event handlers for our buttons
|
||||
// note that `value` and `set_value` are `Copy`, so it's super easy to move them into closures
|
||||
@@ -45,7 +46,7 @@ pub fn SimpleCounter(initial_value: i32) -> impl IntoView {
|
||||
pub fn SimpleCounterWithBuilder(initial_value: i32) -> impl IntoView {
|
||||
use leptos::html::*;
|
||||
|
||||
let (value, set_value) = create_signal(initial_value);
|
||||
let (value, set_value) = signal(initial_value);
|
||||
let clear = move |_| set_value(0);
|
||||
let decrement = move |_| set_value.update(|value| *value -= 1);
|
||||
let increment = move |_| set_value.update(|value| *value += 1);
|
||||
@@ -167,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:
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ use std::{
|
||||
error,
|
||||
fmt::{self, Display},
|
||||
future::Future,
|
||||
mem, ops,
|
||||
ops,
|
||||
pin::Pin,
|
||||
sync::Arc,
|
||||
task::{Context, Poll},
|
||||
@@ -109,7 +109,7 @@ pub fn get_error_hook() -> Option<Arc<dyn ErrorHook>> {
|
||||
/// Sets the current thread-local error hook, which will be invoked when [`throw`] is called.
|
||||
pub fn set_error_hook(hook: Arc<dyn ErrorHook>) -> ResetErrorHookOnDrop {
|
||||
ResetErrorHookOnDrop(
|
||||
ERROR_HOOK.with_borrow_mut(|this| mem::replace(this, Some(hook))),
|
||||
ERROR_HOOK.with_borrow_mut(|this| Option::replace(this, hook)),
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ tokio = { version = "1.41", optional = true, default-features = false, features
|
||||
"rt",
|
||||
] }
|
||||
tracing = { version = "0.1.41", optional = true }
|
||||
wasm-bindgen-futures = { version = "0.4.47", optional = true }
|
||||
wasm-bindgen-futures = { version = "0.4.50", optional = true }
|
||||
|
||||
[features]
|
||||
async-executor = ["dep:async-executor"]
|
||||
|
||||
@@ -23,7 +23,7 @@ tokio-test = "0.4.0"
|
||||
miniserde = "0.1.0"
|
||||
gloo = "0.8.0"
|
||||
uuid = { version = "1.0", features = ["serde", "v4", "wasm-bindgen"] }
|
||||
wasm-bindgen = "0.2.0"
|
||||
wasm-bindgen = "0.2.100"
|
||||
lazy_static = "1.0"
|
||||
log = "0.4.0"
|
||||
strum = "0.24.0"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "either_of"
|
||||
version = "0.1.3"
|
||||
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,33 +1,489 @@
|
||||
#![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;
|
||||
#[cfg(not(feature = "no_std"))]
|
||||
use std::error::Error; // TODO: replace with core::error::Error once MSRV is >= 1.81.0
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub enum Either<A, B> {
|
||||
Left(A),
|
||||
Right(B),
|
||||
macro_rules! tuples {
|
||||
($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),+> {
|
||||
$($variant ($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,)+
|
||||
{
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
match self {
|
||||
$($name::$variant(this) => this.fmt(f),)+
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "no_std"))]
|
||||
impl<$($ty),+> Error for $name<$($ty),+>
|
||||
where
|
||||
$($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::$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),+> {
|
||||
$($variant { #[pin] inner: $ty },)+
|
||||
}
|
||||
}
|
||||
|
||||
impl<$($ty),+> Future for $fut_name<$($ty),+>
|
||||
where
|
||||
$($ty: Future,)+
|
||||
{
|
||||
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::$variant { inner } => match inner.poll(cx) {
|
||||
Poll::Pending => Poll::Pending,
|
||||
Poll::Ready(inner) => Poll::Ready($name::$variant(inner)),
|
||||
},)+
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<Item, A, B> Iterator for Either<A, B>
|
||||
where
|
||||
A: Iterator<Item = Item>,
|
||||
B: Iterator<Item = Item>,
|
||||
{
|
||||
type Item = Item;
|
||||
tuples!(Either + EitherFuture + EitherFutureProj {
|
||||
Left(A) => (Right) + <A1, B>,
|
||||
Right(B) => (Left) + <A, B1>,
|
||||
});
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
impl<A, B> Either<A, B> {
|
||||
pub fn swap(self) -> Either<B, A> {
|
||||
match self {
|
||||
Either::Left(i) => i.next(),
|
||||
Either::Right(i) => i.next(),
|
||||
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),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -90,6 +546,20 @@ impl<T, E> EitherOr for Result<T, E> {
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
@@ -110,109 +580,177 @@ fn test_either_or() {
|
||||
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')));
|
||||
}
|
||||
|
||||
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)),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! tuples {
|
||||
($name:ident + $fut_name:ident + $fut_proj:ident => $($ty:ident),*) => {
|
||||
#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
|
||||
pub enum $name<$($ty,)*> {
|
||||
$($ty ($ty),)*
|
||||
}
|
||||
|
||||
impl<$($ty,)*> Display for $name<$($ty,)*>
|
||||
where
|
||||
$($ty: Display,)*
|
||||
{
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
match self {
|
||||
$($name::$ty(this) => this.fmt(f),)*
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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(),)*
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pin_project! {
|
||||
#[project = $fut_proj]
|
||||
pub enum $fut_name<$($ty,)*> {
|
||||
$($ty { #[pin] inner: $ty },)*
|
||||
}
|
||||
}
|
||||
|
||||
impl<$($ty,)*> Future for $fut_name<$($ty,)*>
|
||||
where
|
||||
$($ty: Future,)*
|
||||
{
|
||||
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) {
|
||||
Poll::Pending => Poll::Pending,
|
||||
Poll::Ready(inner) => Poll::Ready($name::$ty(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!(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.
|
||||
@@ -303,56 +841,67 @@ macro_rules! either {
|
||||
}; // 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,
|
||||
);
|
||||
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,
|
||||
);
|
||||
#[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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -25,7 +25,7 @@ pub fn RouterExample() -> impl IntoView {
|
||||
// contexts are passed down through the route tree
|
||||
provide_context(ExampleContext(0));
|
||||
|
||||
// this signal will be ued to set whether we are allowed to access a protected route
|
||||
// this signal will be used to set whether we are allowed to access a protected route
|
||||
let (logged_in, set_logged_in) = signal(true);
|
||||
let (is_routing, set_is_routing) = signal(false);
|
||||
|
||||
|
||||
@@ -22,20 +22,20 @@ log = "0.4.22"
|
||||
simple_logger = "5.0"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
axum = { version = "0.7.5", optional = true }
|
||||
tower = { version = "0.4.13", optional = true }
|
||||
tower-http = { version = "0.5.2", features = [
|
||||
tower = { version = "0.5.2", optional = true }
|
||||
tower-http = { version = "0.6.2", features = [
|
||||
"fs",
|
||||
"tracing",
|
||||
"trace",
|
||||
], optional = true }
|
||||
tokio = { version = "1.39", features = ["full"], optional = true }
|
||||
thiserror = "1.0"
|
||||
thiserror = "2.0.11"
|
||||
wasm-bindgen = "0.2.93"
|
||||
serde_toml = "0.0.1"
|
||||
toml = "0.8.19"
|
||||
web-sys = { version = "0.3.70", features = ["FileList", "File"] }
|
||||
strum = { version = "0.26.3", features = ["strum_macros", "derive"] }
|
||||
notify = { version = "6.1", optional = true }
|
||||
strum = { version = "0.27.1", features = ["strum_macros", "derive"] }
|
||||
notify = { version = "8.0", optional = true }
|
||||
pin-project-lite = "0.2.14"
|
||||
dashmap = { version = "6.0", optional = true }
|
||||
once_cell = { version = "1.19", optional = true }
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
[toolchain]
|
||||
channel = "nightly-2024-01-29"
|
||||
channel = "nightly-2025-03-05"
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
@check_instrumented_issue_3719
|
||||
Feature: Using instrumented counters to test regression from #3502.
|
||||
Check that the suspend/suspense and the underlying resources are
|
||||
called with the expected number of times. If this was already in
|
||||
place by #3502 (5c43c18) it should have caught this regression.
|
||||
For a better minimum demonstration see #3719.
|
||||
|
||||
Background:
|
||||
|
||||
Given I see the app
|
||||
And I select the mode Instrumented
|
||||
|
||||
Scenario: follow all paths via CSR avoids #3502
|
||||
Given I select the following links
|
||||
| Item Listing |
|
||||
| Item 1 |
|
||||
| Inspect path2 |
|
||||
| Inspect path2/field3 |
|
||||
And I click on Reset CSR Counters
|
||||
When I select the following links
|
||||
| Inspect path2/field1 |
|
||||
| Inspect path2/field2 |
|
||||
And I go check the Counters
|
||||
Then I see the following counters under section
|
||||
| Suspend Calls | |
|
||||
| item_listing | 0 |
|
||||
| item_overview | 0 |
|
||||
| item_inspect | 2 |
|
||||
And the following counters under section
|
||||
| Server Calls (CSR) | |
|
||||
| list_items | 0 |
|
||||
| get_item | 0 |
|
||||
| inspect_item_root | 0 |
|
||||
| inspect_item_field | 2 |
|
||||
|
||||
# To show that starting directly from within a param will simply
|
||||
# cause the problem.
|
||||
Scenario: Quicker way to demonstrate regression caused by #3502
|
||||
Given I select the link Target 123
|
||||
# And I click on Reset CSR Counters
|
||||
When I select the following links
|
||||
| Inspect path2/field1 |
|
||||
| Inspect path2/field2 |
|
||||
And I go check the Counters
|
||||
Then I see the following counters under section
|
||||
| Suspend Calls | |
|
||||
| item_listing | 0 |
|
||||
| item_overview | 0 |
|
||||
| item_inspect | 3 |
|
||||
And the following counters under section
|
||||
| Server Calls (CSR) | |
|
||||
| list_items | 1 |
|
||||
| get_item | 1 |
|
||||
| inspect_item_root | 0 |
|
||||
| inspect_item_field | 4 |
|
||||
|
||||
Scenario: Follow paths ordinarily down to a target
|
||||
Given I select the following links
|
||||
| Item Listing |
|
||||
| Item 1 |
|
||||
And I click on Reset CSR Counters
|
||||
When I select the following links
|
||||
| Target 4## |
|
||||
| Target 3## |
|
||||
And I go check the Counters
|
||||
Then I see the following counters under section
|
||||
| Suspend Calls | |
|
||||
| item_listing | 0 |
|
||||
| item_overview | 2 |
|
||||
| item_inspect | 0 |
|
||||
And the following counters under section
|
||||
| Server Calls (CSR) | |
|
||||
| list_items | 0 |
|
||||
| get_item | 2 |
|
||||
| inspect_item_root | 0 |
|
||||
| inspect_item_field | 0 |
|
||||
|
||||
Scenario: Same as above, but add a refresh to test hydration
|
||||
Given I select the following links
|
||||
| Item Listing |
|
||||
| Item 1 |
|
||||
And I refresh the page
|
||||
And I click on Reset CSR Counters
|
||||
When I select the following links
|
||||
| Target 4## |
|
||||
| Target 3## |
|
||||
And I go check the Counters
|
||||
Then I see the following counters under section
|
||||
| Suspend Calls | |
|
||||
| item_listing | 0 |
|
||||
| item_overview | 2 |
|
||||
| item_inspect | 0 |
|
||||
And the following counters under section
|
||||
| Server Calls (CSR) | |
|
||||
| list_items | 0 |
|
||||
| get_item | 2 |
|
||||
| inspect_item_root | 0 |
|
||||
| inspect_item_field | 0 |
|
||||
|
||||
@@ -3,12 +3,28 @@ mod fixtures;
|
||||
use anyhow::Result;
|
||||
use cucumber::World;
|
||||
use fixtures::world::AppWorld;
|
||||
use std::{ffi::OsStr, fs::read_dir};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
AppWorld::cucumber()
|
||||
.fail_on_skipped()
|
||||
.run_and_exit("./features")
|
||||
.await;
|
||||
// Normally the below is done, but it's now gotten to the point of
|
||||
// having a sufficient number of tests where the resource contention
|
||||
// of the concurrently running browsers will cause failures on CI.
|
||||
// AppWorld::cucumber()
|
||||
// .fail_on_skipped()
|
||||
// .run_and_exit("./features")
|
||||
// .await;
|
||||
|
||||
// Mitigate the issue by manually stepping through each feature,
|
||||
// rather than letting cucumber glob them and dispatch all at once.
|
||||
for entry in read_dir("./features")? {
|
||||
let path = entry?.path();
|
||||
if path.extension() == Some(OsStr::new("feature")) {
|
||||
AppWorld::cucumber()
|
||||
.fail_on_skipped()
|
||||
.run_and_exit(path)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ use leptos_router::{
|
||||
hooks::use_params,
|
||||
nested_router::Outlet,
|
||||
params::Params,
|
||||
MatchNestedRoutes, ParamSegment, SsrMode, StaticSegment, WildcardSegment,
|
||||
ParamSegment, SsrMode, StaticSegment, WildcardSegment,
|
||||
};
|
||||
|
||||
#[cfg(feature = "ssr")]
|
||||
@@ -21,6 +21,7 @@ pub(super) mod counter {
|
||||
pub struct Counter(AtomicU32);
|
||||
|
||||
impl Counter {
|
||||
#[allow(dead_code)]
|
||||
pub const fn new() -> Self {
|
||||
Self(AtomicU32::new(0))
|
||||
}
|
||||
@@ -203,20 +204,20 @@ pub struct SuspenseCounters {
|
||||
}
|
||||
|
||||
#[component]
|
||||
pub fn InstrumentedRoutes() -> impl MatchNestedRoutes + Clone {
|
||||
pub fn InstrumentedRoutes() -> impl leptos_router::MatchNestedRoutes + Clone {
|
||||
// TODO should make this mode configurable via feature flag?
|
||||
let ssr = SsrMode::Async;
|
||||
view! {
|
||||
<ParentRoute path=StaticSegment("instrumented") view=InstrumentedRoot ssr>
|
||||
<Route path=StaticSegment("/") view=InstrumentedTop/>
|
||||
<Route path=StaticSegment("/") view=InstrumentedTop />
|
||||
<ParentRoute path=StaticSegment("item") view=ItemRoot>
|
||||
<Route path=StaticSegment("/") view=ItemListing/>
|
||||
<Route path=StaticSegment("/") view=ItemListing />
|
||||
<ParentRoute path=ParamSegment("id") view=ItemTop>
|
||||
<Route path=StaticSegment("/") view=ItemOverview/>
|
||||
<Route path=WildcardSegment("path") view=ItemInspect/>
|
||||
<Route path=StaticSegment("/") view=ItemOverview />
|
||||
<Route path=WildcardSegment("path") view=ItemInspect />
|
||||
</ParentRoute>
|
||||
</ParentRoute>
|
||||
<Route path=StaticSegment("counters") view=ShowCounters/>
|
||||
<Route path=StaticSegment("counters") view=ShowCounters />
|
||||
</ParentRoute>
|
||||
}
|
||||
.into_inner()
|
||||
@@ -279,32 +280,41 @@ fn InstrumentedRoot() -> impl IntoView {
|
||||
<section id="instrumented">
|
||||
<nav>
|
||||
<a href="/">"Site Root"</a>
|
||||
<A href="./" exact=true>"Instrumented Root"</A>
|
||||
<A href="item/" strict_trailing_slash=true>"Item Listing"</A>
|
||||
<A href="counters" strict_trailing_slash=true>"Counters"</A>
|
||||
<A href="./" exact=true>
|
||||
"Instrumented Root"
|
||||
</A>
|
||||
<A href="item/" strict_trailing_slash=true>
|
||||
"Item Listing"
|
||||
</A>
|
||||
<A href="counters" strict_trailing_slash=true>
|
||||
"Counters"
|
||||
</A>
|
||||
</nav>
|
||||
<FieldNavPortlet/>
|
||||
<Outlet/>
|
||||
<Suspense>{
|
||||
move || Suspend::new(async move {
|
||||
<FieldNavPortlet />
|
||||
<Outlet />
|
||||
<Suspense>
|
||||
{move || Suspend::new(async move {
|
||||
let clear_suspense_counters = move |_| {
|
||||
counters.update(|c| *c = SuspenseCounters::default());
|
||||
};
|
||||
csr_ticket.get().map(|ticket| {
|
||||
let ticket = ticket.0;
|
||||
view! {
|
||||
<ActionForm action=reset_counters>
|
||||
<input type="hidden" name="ticket" value=format!("{ticket}") />
|
||||
<input
|
||||
id="reset-csr-counters"
|
||||
type="submit"
|
||||
value="Reset CSR Counters"
|
||||
on:click=clear_suspense_counters/>
|
||||
</ActionForm>
|
||||
}
|
||||
})
|
||||
})
|
||||
}</Suspense>
|
||||
csr_ticket
|
||||
.get()
|
||||
.map(|ticket| {
|
||||
let ticket = ticket.0;
|
||||
view! {
|
||||
<ActionForm action=reset_counters>
|
||||
<input type="hidden" name="ticket" value=format!("{ticket}") />
|
||||
<input
|
||||
id="reset-csr-counters"
|
||||
type="submit"
|
||||
value="Reset CSR Counters"
|
||||
on:click=clear_suspense_counters
|
||||
/>
|
||||
</ActionForm>
|
||||
}
|
||||
})
|
||||
})}
|
||||
</Suspense>
|
||||
<footer>
|
||||
<nav>
|
||||
<A href="item/3/">"Target 3##"</A>
|
||||
@@ -323,11 +333,17 @@ fn InstrumentedRoot() -> impl IntoView {
|
||||
fn InstrumentedTop() -> impl IntoView {
|
||||
view! {
|
||||
<h1>"Instrumented Tests"</h1>
|
||||
<p>"These tests validates the number of invocations of server functions and suspenses per access."</p>
|
||||
<p>
|
||||
"These tests validates the number of invocations of server functions and suspenses per access."
|
||||
</p>
|
||||
<ul>
|
||||
// not using `A` because currently some bugs with artix
|
||||
<li><a href="item/">"Item Listing"</a></li>
|
||||
<li><a href="item/4/path1/">"Target 41#"</a></li>
|
||||
<li>
|
||||
<a href="item/">"Item Listing"</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="item/4/path1/">"Target 41#"</a>
|
||||
</li>
|
||||
</ul>
|
||||
}
|
||||
}
|
||||
@@ -342,7 +358,7 @@ fn ItemRoot() -> impl IntoView {
|
||||
|
||||
view! {
|
||||
<h2>"<ItemRoot/>"</h2>
|
||||
<Outlet/>
|
||||
<Outlet />
|
||||
}
|
||||
}
|
||||
|
||||
@@ -360,7 +376,9 @@ fn ItemListing() -> impl IntoView {
|
||||
// adding an extra `/` in artix; manually construct `a` instead.
|
||||
// <li><A href=format!("./{item}/")>"Item "{item}</A></li>
|
||||
view! {
|
||||
<li><a href=format!("/instrumented/item/{item}/")>"Item "{item}</a></li>
|
||||
<li>
|
||||
<a href=format!("/instrumented/item/{item}/")>"Item "{item}</a>
|
||||
</li>
|
||||
}
|
||||
)
|
||||
.collect_view()
|
||||
@@ -373,9 +391,7 @@ fn ItemListing() -> impl IntoView {
|
||||
view! {
|
||||
<h3>"<ItemListing/>"</h3>
|
||||
<ul>
|
||||
<Suspense>
|
||||
{item_listing}
|
||||
</Suspense>
|
||||
<Suspense>{item_listing}</Suspense>
|
||||
</ul>
|
||||
}
|
||||
}
|
||||
@@ -402,7 +418,7 @@ fn ItemTop() -> impl IntoView {
|
||||
));
|
||||
view! {
|
||||
<h4>"<ItemTop/>"</h4>
|
||||
<Outlet/>
|
||||
<Outlet />
|
||||
}
|
||||
}
|
||||
|
||||
@@ -412,24 +428,29 @@ fn ItemOverview() -> impl IntoView {
|
||||
let resource = expect_context::<Resource<Option<GetItemResult>>>();
|
||||
let item_view = move || {
|
||||
Suspend::new(async move {
|
||||
let result = resource.await.map(|GetItemResult(item, names)| view! {
|
||||
<p>{format!("Viewing {item:?}")}</p>
|
||||
<ul>{
|
||||
names.into_iter()
|
||||
.map(|name| {
|
||||
// FIXME seems like relative link isn't working, it is currently
|
||||
// adding an extra `/` in artix; manually construct `a` instead.
|
||||
// <li><A href=format!("./{name}/")>{format!("Inspect {name}")}</A></li>
|
||||
let id = item.id;
|
||||
view! {
|
||||
<li><a href=format!("/instrumented/item/{id}/{name}/")>
|
||||
"Inspect "{name.clone()}
|
||||
</a></li>
|
||||
}
|
||||
})
|
||||
.collect_view()
|
||||
}</ul>
|
||||
});
|
||||
let result = resource.await.map(|GetItemResult(item, names)| {
|
||||
view! {
|
||||
<p>{format!("Viewing {item:?}")}</p>
|
||||
<ul>
|
||||
{names
|
||||
.into_iter()
|
||||
.map(|name| {
|
||||
let id = item.id;
|
||||
// FIXME seems like relative link isn't working, it is currently
|
||||
// adding an extra `/` in artix; manually construct `a` instead.
|
||||
// <li><A href=format!("./{name}/")>{format!("Inspect {name}")}</A></li>
|
||||
view! {
|
||||
<li>
|
||||
<a href=format!(
|
||||
"/instrumented/item/{id}/{name}/",
|
||||
)>"Inspect "{name.clone()}</a>
|
||||
</li>
|
||||
}
|
||||
})
|
||||
.collect_view()}
|
||||
</ul>
|
||||
}
|
||||
});
|
||||
suspense_counters.update_untracked(|c| c.item_overview += 1);
|
||||
result
|
||||
})
|
||||
@@ -437,9 +458,7 @@ fn ItemOverview() -> impl IntoView {
|
||||
|
||||
view! {
|
||||
<h5>"<ItemOverview/>"</h5>
|
||||
<Suspense>
|
||||
{item_view}
|
||||
</Suspense>
|
||||
<Suspense>{item_view}</Suspense>
|
||||
}
|
||||
}
|
||||
|
||||
@@ -473,8 +492,9 @@ fn ItemInspect() -> impl IntoView {
|
||||
// result
|
||||
},
|
||||
);
|
||||
on_cleanup(|| {
|
||||
if let Some(c) = use_context::<WriteSignal<Option<FieldNavCtx>>>() {
|
||||
let ws = use_context::<WriteSignal<Option<FieldNavCtx>>>();
|
||||
on_cleanup(move || {
|
||||
if let Some(c) = ws {
|
||||
c.set(None);
|
||||
}
|
||||
});
|
||||
@@ -496,23 +516,26 @@ fn ItemInspect() -> impl IntoView {
|
||||
));
|
||||
view! {
|
||||
<p>{format!("Inspecting {item:?}")}</p>
|
||||
<ul>{
|
||||
fields.iter()
|
||||
<ul>
|
||||
{fields
|
||||
.iter()
|
||||
.map(|field| {
|
||||
// FIXME seems like relative link to root for a wildcard isn't
|
||||
// working as expected, so manually construct `a` instead.
|
||||
// let text = format!("Inspect {name}/{field}");
|
||||
// view! {
|
||||
// <li><A href=format!("{field}")>{text}</A></li>
|
||||
// <li><A href=format!("{field}")>{text}</A></li>
|
||||
// }
|
||||
view! {
|
||||
<li><a href=format!("/instrumented/item/{id}/{name}/{field}")>{
|
||||
format!("Inspect {name}/{field}")
|
||||
}</a></li>
|
||||
<li>
|
||||
<a href=format!(
|
||||
"/instrumented/item/{id}/{name}/{field}",
|
||||
)>{format!("Inspect {name}/{field}")}</a>
|
||||
</li>
|
||||
}
|
||||
})
|
||||
.collect_view()
|
||||
}</ul>
|
||||
.collect_view()}
|
||||
</ul>
|
||||
}
|
||||
});
|
||||
suspense_counters.update_untracked(|c| c.item_inspect += 1);
|
||||
@@ -527,9 +550,7 @@ fn ItemInspect() -> impl IntoView {
|
||||
|
||||
view! {
|
||||
<h5>"<ItemInspect/>"</h5>
|
||||
<Suspense>
|
||||
{inspect_view}
|
||||
</Suspense>
|
||||
<Suspense>{inspect_view}</Suspense>
|
||||
}
|
||||
}
|
||||
|
||||
@@ -590,7 +611,8 @@ fn ShowCounters() -> impl IntoView {
|
||||
id="reset-counters"
|
||||
type="submit"
|
||||
value="Reset Counters"
|
||||
on:click=clear_suspense_counters/>
|
||||
on:click=clear_suspense_counters
|
||||
/>
|
||||
</ActionForm>
|
||||
}
|
||||
})
|
||||
@@ -601,20 +623,23 @@ fn ShowCounters() -> impl IntoView {
|
||||
<h2>"Counters"</h2>
|
||||
|
||||
<h3 id="suspend-calls">"Suspend Calls"</h3>
|
||||
{move || suspense_counters.with(|c| view! {
|
||||
<dl>
|
||||
<dt>"item_listing"</dt>
|
||||
<dd id="item_listing">{c.item_listing}</dd>
|
||||
<dt>"item_overview"</dt>
|
||||
<dd id="item_overview">{c.item_overview}</dd>
|
||||
<dt>"item_inspect"</dt>
|
||||
<dd id="item_inspect">{c.item_inspect}</dd>
|
||||
</dl>
|
||||
})}
|
||||
{move || {
|
||||
suspense_counters
|
||||
.with(|c| {
|
||||
view! {
|
||||
<dl>
|
||||
<dt>"item_listing"</dt>
|
||||
<dd id="item_listing">{c.item_listing}</dd>
|
||||
<dt>"item_overview"</dt>
|
||||
<dd id="item_overview">{c.item_overview}</dd>
|
||||
<dt>"item_inspect"</dt>
|
||||
<dd id="item_inspect">{c.item_inspect}</dd>
|
||||
</dl>
|
||||
}
|
||||
})
|
||||
}}
|
||||
|
||||
<Suspense>
|
||||
{counter_view}
|
||||
</Suspense>
|
||||
<Suspense>{counter_view}</Suspense>
|
||||
}
|
||||
}
|
||||
|
||||
@@ -642,17 +667,17 @@ pub fn FieldNavPortlet() -> impl IntoView {
|
||||
view! {
|
||||
<div id="FieldNavPortlet">
|
||||
<span>"FieldNavPortlet:"</span>
|
||||
<nav>{
|
||||
ctx.0.map(|ctx| {
|
||||
ctx.into_iter()
|
||||
.map(|FieldNavItem { href, text }| {
|
||||
view! {
|
||||
<A href=href>{text}</A>
|
||||
}
|
||||
})
|
||||
.collect_view()
|
||||
})
|
||||
}</nav>
|
||||
<nav>
|
||||
{ctx
|
||||
.0
|
||||
.map(|ctx| {
|
||||
ctx.into_iter()
|
||||
.map(|FieldNavItem { href, text }| {
|
||||
view! { <A href=href>{text}</A> }
|
||||
})
|
||||
.collect_view()
|
||||
})}
|
||||
</nav>
|
||||
</div>
|
||||
}
|
||||
})
|
||||
|
||||
@@ -1,3 +1 @@
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
@import "tailwindcss";
|
||||
|
||||
@@ -1,3 +1 @@
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
@import "tailwindcss";
|
||||
|
||||
@@ -14,7 +14,7 @@ throw_error = { workspace = true }
|
||||
or_poisoned = { workspace = true }
|
||||
futures = "0.3.31"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
wasm-bindgen = { version = "0.2.97", optional = true }
|
||||
wasm-bindgen = { version = "0.2.100", optional = true }
|
||||
js-sys = { version = "0.3.74", optional = true }
|
||||
once_cell = "1.20"
|
||||
pin-project-lite = "0.2.15"
|
||||
|
||||
@@ -21,10 +21,10 @@ leptos_macro = { workspace = true, features = ["actix"] }
|
||||
leptos_meta = { workspace = true, features = ["nonce"] }
|
||||
leptos_router = { workspace = true, features = ["ssr"] }
|
||||
server_fn = { workspace = true, features = ["actix"] }
|
||||
serde_json = "1.0"
|
||||
serde_json = { workspace = true }
|
||||
parking_lot = "0.12.3"
|
||||
tracing = { version = "0.1", optional = true }
|
||||
tokio = { version = "1.41", features = ["rt", "fs"] }
|
||||
tokio = { version = "1.43", features = ["rt", "fs"] }
|
||||
send_wrapper = "0.6.0"
|
||||
dashmap = "6"
|
||||
once_cell = "1"
|
||||
|
||||
@@ -274,14 +274,13 @@ pub fn redirect(path: &str) {
|
||||
///
|
||||
/// This can then be set up at an appropriate route in your application:
|
||||
///
|
||||
/// ```
|
||||
/// ```no_run
|
||||
/// use actix_web::*;
|
||||
///
|
||||
/// fn register_server_functions() {
|
||||
/// // call ServerFn::register() for each of the server functions you've defined
|
||||
/// }
|
||||
///
|
||||
/// # if false { // don't actually try to run a server in a doctest...
|
||||
/// #[actix_web::main]
|
||||
/// async fn main() -> std::io::Result<()> {
|
||||
/// // make sure you actually register your server functions
|
||||
@@ -297,7 +296,6 @@ pub fn redirect(path: &str) {
|
||||
/// .run()
|
||||
/// .await
|
||||
/// }
|
||||
/// # }
|
||||
/// ```
|
||||
///
|
||||
/// ## Provided Context Types
|
||||
@@ -433,7 +431,7 @@ pub fn handle_server_fns_with_context(
|
||||
/// but requires some client-side JavaScript.
|
||||
///
|
||||
/// This can then be set up at an appropriate route in your application:
|
||||
/// ```
|
||||
/// ```no_run
|
||||
/// use actix_web::{App, HttpServer};
|
||||
/// use leptos::prelude::*;
|
||||
/// use leptos_router::Method;
|
||||
@@ -444,7 +442,6 @@ pub fn handle_server_fns_with_context(
|
||||
/// view! { <main>"Hello, world!"</main> }
|
||||
/// }
|
||||
///
|
||||
/// # if false { // don't actually try to run a server in a doctest...
|
||||
/// #[actix_web::main]
|
||||
/// async fn main() -> std::io::Result<()> {
|
||||
/// let conf = get_configuration(Some("Cargo.toml")).unwrap();
|
||||
@@ -464,7 +461,6 @@ pub fn handle_server_fns_with_context(
|
||||
/// .run()
|
||||
/// .await
|
||||
/// }
|
||||
/// # }
|
||||
/// ```
|
||||
///
|
||||
/// ## Provided Context Types
|
||||
@@ -492,7 +488,7 @@ where
|
||||
/// sending down its HTML. The app will become interactive once it has fully loaded.
|
||||
///
|
||||
/// This can then be set up at an appropriate route in your application:
|
||||
/// ```
|
||||
/// ```no_run
|
||||
/// use actix_web::{App, HttpServer};
|
||||
/// use leptos::prelude::*;
|
||||
/// use leptos_router::Method;
|
||||
@@ -503,7 +499,6 @@ where
|
||||
/// view! { <main>"Hello, world!"</main> }
|
||||
/// }
|
||||
///
|
||||
/// # if false { // don't actually try to run a server in a doctest...
|
||||
/// #[actix_web::main]
|
||||
/// async fn main() -> std::io::Result<()> {
|
||||
/// let conf = get_configuration(Some("Cargo.toml")).unwrap();
|
||||
@@ -526,7 +521,6 @@ where
|
||||
/// .run()
|
||||
/// .await
|
||||
/// }
|
||||
/// # }
|
||||
/// ```
|
||||
///
|
||||
/// ## Provided Context Types
|
||||
@@ -552,7 +546,7 @@ where
|
||||
/// `async` resources have loaded.
|
||||
///
|
||||
/// This can then be set up at an appropriate route in your application:
|
||||
/// ```
|
||||
/// ```no_run
|
||||
/// use actix_web::{App, HttpServer};
|
||||
/// use leptos::prelude::*;
|
||||
/// use leptos_router::Method;
|
||||
@@ -563,7 +557,6 @@ where
|
||||
/// view! { <main>"Hello, world!"</main> }
|
||||
/// }
|
||||
///
|
||||
/// # if false { // don't actually try to run a server in a doctest...
|
||||
/// #[actix_web::main]
|
||||
/// async fn main() -> std::io::Result<()> {
|
||||
/// let conf = get_configuration(Some("Cargo.toml")).unwrap();
|
||||
@@ -583,7 +576,6 @@ where
|
||||
/// .run()
|
||||
/// .await
|
||||
/// }
|
||||
/// # }
|
||||
/// ```
|
||||
///
|
||||
/// ## Provided Context Types
|
||||
|
||||
@@ -24,14 +24,14 @@ 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 }
|
||||
tokio = { version = "1.43", default-features = false }
|
||||
tower = { version = "0.5.1", features = ["util"] }
|
||||
tower-http = "0.6.2"
|
||||
tracing = { version = "0.1.41", optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
axum = "0.7.9"
|
||||
tokio = { version = "1.41", features = ["net", "rt-multi-thread"] }
|
||||
tokio = { version = "1.43", features = ["net", "rt-multi-thread"] }
|
||||
|
||||
[features]
|
||||
wasm = []
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#![forbid(unsafe_code)]
|
||||
#![deny(missing_docs)]
|
||||
#![allow(clippy::type_complexity)]
|
||||
|
||||
//! Provides functions to easily integrate Leptos with Axum.
|
||||
//!
|
||||
@@ -278,12 +279,11 @@ pub fn generate_request_and_parts(
|
||||
///
|
||||
/// This can then be set up at an appropriate route in your application:
|
||||
///
|
||||
/// ```
|
||||
/// ```no_run
|
||||
/// use axum::{handler::Handler, routing::post, Router};
|
||||
/// use leptos::prelude::*;
|
||||
/// use std::net::SocketAddr;
|
||||
///
|
||||
/// # if false { // don't actually try to run a server in a doctest...
|
||||
/// #[cfg(feature = "default")]
|
||||
/// #[tokio::main]
|
||||
/// async fn main() {
|
||||
@@ -299,7 +299,9 @@ pub fn generate_request_and_parts(
|
||||
/// .await
|
||||
/// .unwrap();
|
||||
/// }
|
||||
/// # }
|
||||
///
|
||||
/// # #[cfg(not(feature = "default"))]
|
||||
/// # fn main() { }
|
||||
/// ```
|
||||
/// Leptos provides a generic implementation of `handle_server_fns`. If access to more specific parts of the Request is desired,
|
||||
/// you can specify your own server fn handler based on this one and give it it's own route in the server macro.
|
||||
@@ -442,7 +444,7 @@ pub type PinnedHtmlStream =
|
||||
/// to route it using [leptos_router], serving an HTML stream of your application.
|
||||
///
|
||||
/// This can then be set up at an appropriate route in your application:
|
||||
/// ```
|
||||
/// ```no_run
|
||||
/// use axum::{handler::Handler, Router};
|
||||
/// use leptos::{config::get_configuration, prelude::*};
|
||||
/// use std::{env, net::SocketAddr};
|
||||
@@ -452,7 +454,6 @@ pub type PinnedHtmlStream =
|
||||
/// view! { <main>"Hello, world!"</main> }
|
||||
/// }
|
||||
///
|
||||
/// # if false { // don't actually try to run a server in a doctest...
|
||||
/// #[cfg(feature = "default")]
|
||||
/// #[tokio::main]
|
||||
/// async fn main() {
|
||||
@@ -471,7 +472,9 @@ pub type PinnedHtmlStream =
|
||||
/// .await
|
||||
/// .unwrap();
|
||||
/// }
|
||||
/// # }
|
||||
///
|
||||
/// # #[cfg(not(feature = "default"))]
|
||||
/// # fn main() { }
|
||||
/// ```
|
||||
///
|
||||
/// ## Provided Context Types
|
||||
@@ -530,7 +533,7 @@ where
|
||||
/// sending down its HTML. The app will become interactive once it has fully loaded.
|
||||
///
|
||||
/// This can then be set up at an appropriate route in your application:
|
||||
/// ```
|
||||
/// ```no_run
|
||||
/// use axum::{handler::Handler, Router};
|
||||
/// use leptos::{config::get_configuration, prelude::*};
|
||||
/// use std::{env, net::SocketAddr};
|
||||
@@ -540,7 +543,6 @@ where
|
||||
/// view! { <main>"Hello, world!"</main> }
|
||||
/// }
|
||||
///
|
||||
/// # if false { // don't actually try to run a server in a doctest...
|
||||
/// #[cfg(feature = "default")]
|
||||
/// #[tokio::main]
|
||||
/// async fn main() {
|
||||
@@ -559,7 +561,9 @@ where
|
||||
/// .await
|
||||
/// .unwrap();
|
||||
/// }
|
||||
/// # }
|
||||
///
|
||||
/// # #[cfg(not(feature = "default"))]
|
||||
/// # fn main() { }
|
||||
/// ```
|
||||
///
|
||||
/// ## Provided Context Types
|
||||
@@ -937,7 +941,7 @@ fn provide_contexts(
|
||||
/// `async` resources have loaded.
|
||||
///
|
||||
/// This can then be set up at an appropriate route in your application:
|
||||
/// ```
|
||||
/// ```no_run
|
||||
/// use axum::{handler::Handler, Router};
|
||||
/// use leptos::{config::get_configuration, prelude::*};
|
||||
/// use std::{env, net::SocketAddr};
|
||||
@@ -947,7 +951,6 @@ fn provide_contexts(
|
||||
/// view! { <main>"Hello, world!"</main> }
|
||||
/// }
|
||||
///
|
||||
/// # if false { // don't actually try to run a server in a doctest...
|
||||
/// #[cfg(feature = "default")]
|
||||
/// #[tokio::main]
|
||||
/// async fn main() {
|
||||
@@ -967,7 +970,9 @@ fn provide_contexts(
|
||||
/// .await
|
||||
/// .unwrap();
|
||||
/// }
|
||||
/// # }
|
||||
///
|
||||
/// # #[cfg(not(feature = "default"))]
|
||||
/// # fn main() { }
|
||||
/// ```
|
||||
///
|
||||
/// ## Provided Context Types
|
||||
@@ -1981,7 +1986,8 @@ where
|
||||
/// 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>(
|
||||
pub fn file_and_error_handler_with_context<S, IV>(
|
||||
additional_context: impl Fn() + 'static + Clone + Send,
|
||||
shell: fn(LeptosOptions) -> IV,
|
||||
) -> impl Fn(
|
||||
Uri,
|
||||
@@ -1997,40 +2003,68 @@ where
|
||||
LeptosOptions: FromRef<S>,
|
||||
{
|
||||
move |uri: Uri, State(state): State<S>, req: Request<Body>| {
|
||||
Box::pin(async move {
|
||||
let options = LeptosOptions::from_ref(&state);
|
||||
let res = get_static_file(uri, &options.site_root, req.headers());
|
||||
let res = res.await.unwrap();
|
||||
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 || {
|
||||
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
|
||||
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,
|
||||
) -> 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>,
|
||||
{
|
||||
file_and_error_handler_with_context(move || (), shell)
|
||||
}
|
||||
|
||||
#[cfg(feature = "default")]
|
||||
async fn get_static_file(
|
||||
uri: Uri,
|
||||
|
||||
@@ -52,12 +52,11 @@ web-sys = { version = "0.3.72", features = [
|
||||
"ShadowRootInit",
|
||||
"ShadowRootMode",
|
||||
] }
|
||||
wasm-bindgen = "0.2.97"
|
||||
wasm-bindgen = { workspace = true }
|
||||
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 = [
|
||||
@@ -66,13 +65,12 @@ hydration = [
|
||||
"hydration_context/browser",
|
||||
"leptos_dom/hydration",
|
||||
]
|
||||
csr = ["leptos_macro/csr", "reactive_graph/effects", "dep:getrandom"]
|
||||
csr = ["leptos_macro/csr", "reactive_graph/effects"]
|
||||
hydrate = [
|
||||
"leptos_macro/hydrate",
|
||||
"hydration",
|
||||
"tachys/hydrate",
|
||||
"reactive_graph/effects",
|
||||
"dep:getrandom",
|
||||
]
|
||||
default-tls = ["server_fn/default-tls"]
|
||||
rustls = ["server_fn/rustls"]
|
||||
@@ -84,10 +82,7 @@ ssr = [
|
||||
"tachys/ssr",
|
||||
]
|
||||
nightly = ["leptos_macro/nightly", "reactive_graph/nightly", "tachys/nightly"]
|
||||
rkyv = [
|
||||
"server_fn/rkyv",
|
||||
"leptos_server/rkyv"
|
||||
]
|
||||
rkyv = ["server_fn/rkyv", "leptos_server/rkyv"]
|
||||
tracing = [
|
||||
"dep:tracing",
|
||||
"reactive_graph/tracing",
|
||||
|
||||
@@ -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)]
|
||||
@@ -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;
|
||||
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;
|
||||
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));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -303,11 +303,13 @@ where
|
||||
let eff = reactive_graph::effect::Effect::new_isomorphic({
|
||||
move |_| {
|
||||
tasks.track();
|
||||
if tasks.read().is_empty() {
|
||||
if let Some(tx) = tasks_tx.take() {
|
||||
// If the receiver has dropped, it means the ScopedFuture has already
|
||||
// dropped, so it doesn't matter if we manage to send this.
|
||||
_ = tx.send(());
|
||||
if let Some(tasks) = tasks.try_read() {
|
||||
if tasks.is_empty() {
|
||||
if let Some(tx) = tasks_tx.take() {
|
||||
// If the receiver has dropped, it means the ScopedFuture has already
|
||||
// dropped, so it doesn't matter if we manage to send this.
|
||||
_ = tx.send(());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ rust-version.workspace = true
|
||||
edition.workspace = true
|
||||
|
||||
[dependencies]
|
||||
config = { version = "0.14.1", default-features = false, features = [
|
||||
config = { version = "0.15.8", default-features = false, features = [
|
||||
"toml",
|
||||
"convert-case",
|
||||
] }
|
||||
@@ -20,7 +20,7 @@ thiserror = "2.0"
|
||||
typed-builder = "0.20.0"
|
||||
|
||||
[dev-dependencies]
|
||||
tokio = { version = "1.41", features = ["rt", "macros"] }
|
||||
tokio = { version = "1.43", features = ["rt", "macros"] }
|
||||
tempfile = "3.14"
|
||||
temp-env = { version = "0.3.6", features = ["async_closure"] }
|
||||
|
||||
@@ -28,4 +28,4 @@ temp-env = { version = "0.3.6", features = ["async_closure"] }
|
||||
rustdoc-args = ["--generate-link-to-definition"]
|
||||
|
||||
[lints.rust]
|
||||
unexpected_cfgs = { level = "warn", check-cfg = ['cfg(leptos_debuginfo)'] }
|
||||
unexpected_cfgs = { level = "warn", check-cfg = ['cfg(leptos_debuginfo)'] }
|
||||
|
||||
@@ -15,7 +15,7 @@ or_poisoned = { workspace = true }
|
||||
js-sys = "0.3.74"
|
||||
send_wrapper = "0.6.0"
|
||||
tracing = { version = "0.1.41", optional = true }
|
||||
wasm-bindgen = "0.2.97"
|
||||
wasm-bindgen = { workspace = true }
|
||||
serde_json = { version = "1.0", optional = true }
|
||||
serde = { version = "1.0", optional = true }
|
||||
|
||||
@@ -39,4 +39,4 @@ rustdoc-args = ["--generate-link-to-definition"]
|
||||
denylist = ["tracing"]
|
||||
|
||||
[lints.rust]
|
||||
unexpected_cfgs = { level = "warn", check-cfg = ['cfg(leptos_debuginfo)'] }
|
||||
unexpected_cfgs = { level = "warn", check-cfg = ['cfg(leptos_debuginfo)'] }
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "leptos_macro"
|
||||
version = "0.7.4"
|
||||
version = { workspace = true }
|
||||
authors = ["Greg Johnston"]
|
||||
license = "MIT"
|
||||
repository = "https://github.com/leptos-rs/leptos"
|
||||
@@ -16,7 +16,7 @@ proc-macro = true
|
||||
attribute-derive = { version = "0.10.3", features = ["syn-full"] }
|
||||
cfg-if = "1.0"
|
||||
html-escape = "0.2.13"
|
||||
itertools = "0.13.0"
|
||||
itertools = { workspace = true }
|
||||
prettyplease = "0.2.25"
|
||||
proc-macro-error2 = { version = "2.0", default-features = false }
|
||||
proc-macro2 = "1.0"
|
||||
@@ -25,7 +25,7 @@ syn = { version = "2.0", features = ["full"] }
|
||||
rstml = "0.12.0"
|
||||
leptos_hot_reload = { workspace = true }
|
||||
server_fn_macro = { workspace = true }
|
||||
convert_case = "0.6.0"
|
||||
convert_case = "0.7"
|
||||
uuid = { version = "1.11", features = ["v4"] }
|
||||
tracing = { version = "0.1.41", optional = true }
|
||||
|
||||
@@ -34,6 +34,7 @@ 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"
|
||||
@@ -54,30 +55,30 @@ generic = ["server_fn_macro/generic"]
|
||||
[package.metadata.cargo-all-features]
|
||||
denylist = ["nightly", "tracing", "trace-component-props"]
|
||||
skip_feature_sets = [
|
||||
[
|
||||
"csr",
|
||||
"hydrate",
|
||||
],
|
||||
[
|
||||
"hydrate",
|
||||
"csr",
|
||||
],
|
||||
[
|
||||
"hydrate",
|
||||
"ssr",
|
||||
],
|
||||
[
|
||||
"actix",
|
||||
"axum",
|
||||
],
|
||||
[
|
||||
"actix",
|
||||
"generic",
|
||||
],
|
||||
[
|
||||
"generic",
|
||||
"axum",
|
||||
],
|
||||
[
|
||||
"csr",
|
||||
"hydrate",
|
||||
],
|
||||
[
|
||||
"hydrate",
|
||||
"csr",
|
||||
],
|
||||
[
|
||||
"hydrate",
|
||||
"ssr",
|
||||
],
|
||||
[
|
||||
"actix",
|
||||
"axum",
|
||||
],
|
||||
[
|
||||
"actix",
|
||||
"generic",
|
||||
],
|
||||
[
|
||||
"generic",
|
||||
"axum",
|
||||
],
|
||||
]
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
@@ -85,6 +86,6 @@ rustdoc-args = ["--generate-link-to-definition"]
|
||||
|
||||
[lints.rust]
|
||||
unexpected_cfgs = { level = "warn", check-cfg = [
|
||||
'cfg(leptos_debuginfo)',
|
||||
'cfg(erase_components)',
|
||||
'cfg(leptos_debuginfo)',
|
||||
'cfg(erase_components)',
|
||||
] }
|
||||
|
||||
@@ -11,13 +11,13 @@ dependencies = [
|
||||
[tasks.test-leptos_macro-example]
|
||||
description = "Tests the leptos_macro/example to check if macro handles doc comments correctly"
|
||||
command = "cargo"
|
||||
args = ["+nightly-2024-08-01", "test", "--doc"]
|
||||
args = ["+nightly-2025-03-05", "test", "--doc"]
|
||||
cwd = "example"
|
||||
install_crate = false
|
||||
|
||||
[tasks.doc-leptos_macro-example]
|
||||
description = "Docs the leptos_macro/example to check if macro handles doc comments correctly"
|
||||
command = "cargo"
|
||||
args = ["+nightly-2024-08-01", "doc"]
|
||||
args = ["+nightly-2025-03-05", "doc"]
|
||||
cwd = "example"
|
||||
install_crate = false
|
||||
|
||||
@@ -144,8 +144,6 @@ impl ToTokens for Model {
|
||||
let (impl_generics, generics, where_clause) =
|
||||
body.sig.generics.split_for_impl();
|
||||
|
||||
let lifetimes = body.sig.generics.lifetimes();
|
||||
|
||||
let props_name = format_ident!("{name}Props");
|
||||
let props_builder_name = format_ident!("{name}PropsBuilder");
|
||||
let props_serialized_name = format_ident!("{name}PropsSerialized");
|
||||
@@ -301,7 +299,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
|
||||
@@ -312,7 +310,7 @@ impl ToTokens for Model {
|
||||
}
|
||||
} else {
|
||||
quote! {
|
||||
::leptos::prelude::untrack(
|
||||
::leptos::reactive::graph::untrack_with_diagnostics(
|
||||
move || {
|
||||
#tracing_guard_expr
|
||||
#tracing_props_expr
|
||||
@@ -570,7 +568,7 @@ impl ToTokens for Model {
|
||||
#tracing_instrument_attr
|
||||
#vis fn #name #impl_generics (
|
||||
#props_arg
|
||||
) #ret #(+ #lifetimes)*
|
||||
) #ret
|
||||
#where_clause
|
||||
{
|
||||
#body
|
||||
|
||||
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()
|
||||
}
|
||||
@@ -23,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;
|
||||
@@ -676,17 +677,21 @@ fn component_macro(
|
||||
#[allow(non_snake_case, dead_code, clippy::too_many_arguments, clippy::needless_lifetimes)]
|
||||
#unexpanded
|
||||
}
|
||||
} else if let Ok(mut dummy) = dummy {
|
||||
dummy.sig.ident = unmodified_fn_name_from_fn_name(&dummy.sig.ident);
|
||||
quote! {
|
||||
#[doc(hidden)]
|
||||
#[allow(non_snake_case, dead_code, clippy::too_many_arguments, clippy::needless_lifetimes)]
|
||||
#dummy
|
||||
}
|
||||
} else {
|
||||
quote! {}
|
||||
}
|
||||
.into()
|
||||
match dummy {
|
||||
Ok(mut dummy) => {
|
||||
dummy.sig.ident = unmodified_fn_name_from_fn_name(&dummy.sig.ident);
|
||||
quote! {
|
||||
#[doc(hidden)]
|
||||
#[allow(non_snake_case, dead_code, clippy::too_many_arguments, clippy::needless_lifetimes)]
|
||||
#dummy
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
proc_macro_error2::abort!(e.span(), e);
|
||||
}
|
||||
}
|
||||
}.into()
|
||||
}
|
||||
|
||||
/// Annotates a struct so that it can be used with your Component as a `slot`.
|
||||
@@ -1002,3 +1007,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();
|
||||
|
||||
@@ -171,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())
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -154,7 +154,12 @@ fn is_inert_element(orig_node: &Node<impl CustomNode>) -> bool {
|
||||
Some(value) => {
|
||||
matches!(&value.value, KVAttributeValue::Expr(expr) if {
|
||||
if let Expr::Lit(lit) = expr {
|
||||
matches!(&lit.lit, Lit::Str(_))
|
||||
let key = attr.key.to_string();
|
||||
if key.starts_with("style:") || key.starts_with("prop:") || key.starts_with("on:") || key.starts_with("use:") || key.starts_with("bind") {
|
||||
false
|
||||
} else {
|
||||
matches!(&lit.lit, Lit::Str(_))
|
||||
}
|
||||
} else {
|
||||
false
|
||||
}
|
||||
@@ -1129,6 +1134,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)
|
||||
@@ -1147,8 +1157,14 @@ pub(crate) fn two_way_binding_to_tokens(
|
||||
let ident =
|
||||
format_ident!("{}", name.to_case(UpperCamel), span = node.key.span());
|
||||
|
||||
quote! {
|
||||
.bind(::leptos::attr::#ident, #value)
|
||||
if name == "group" {
|
||||
quote! {
|
||||
.bind(leptos::tachys::reactive_graph::bind::#ident, #value)
|
||||
}
|
||||
} else {
|
||||
quote! {
|
||||
.bind(::leptos::attr::#ident, #value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1169,8 +1185,7 @@ pub(crate) fn event_type_and_handler(
|
||||
) -> (TokenStream, TokenStream, TokenStream) {
|
||||
let handler = attribute_value(node, false);
|
||||
|
||||
let (event_type, is_custom, is_force_undelegated, is_targeted) =
|
||||
parse_event_name(name);
|
||||
let (event_type, is_custom, options) = parse_event_name(name);
|
||||
|
||||
let event_name_ident = match &node.key {
|
||||
NodeName::Punctuated(parts) => {
|
||||
@@ -1188,11 +1203,17 @@ pub(crate) fn event_type_and_handler(
|
||||
}
|
||||
_ => unreachable!(),
|
||||
};
|
||||
let capture_ident = match &node.key {
|
||||
NodeName::Punctuated(parts) => {
|
||||
parts.iter().find(|part| part.to_string() == "capture")
|
||||
}
|
||||
_ => unreachable!(),
|
||||
};
|
||||
let on = match &node.key {
|
||||
NodeName::Punctuated(parts) => &parts[0],
|
||||
_ => unreachable!(),
|
||||
};
|
||||
let on = if is_targeted {
|
||||
let on = if options.targeted {
|
||||
Ident::new("on_target", on.span()).to_token_stream()
|
||||
} else {
|
||||
on.to_token_stream()
|
||||
@@ -1205,15 +1226,29 @@ pub(crate) fn event_type_and_handler(
|
||||
event_type
|
||||
};
|
||||
|
||||
let event_type = if is_force_undelegated {
|
||||
let event_type = quote! {
|
||||
::leptos::tachys::html::event::#event_type
|
||||
};
|
||||
let event_type = if options.captured {
|
||||
let capture = if let Some(capture) = capture_ident {
|
||||
quote! { #capture }
|
||||
} else {
|
||||
quote! { capture }
|
||||
};
|
||||
quote! { ::leptos::tachys::html::event::#capture(#event_type) }
|
||||
} else {
|
||||
event_type
|
||||
};
|
||||
|
||||
let event_type = if options.undelegated {
|
||||
let undelegated = if let Some(undelegated) = undelegated_ident {
|
||||
quote! { #undelegated }
|
||||
} else {
|
||||
quote! { undelegated }
|
||||
};
|
||||
quote! { ::leptos::tachys::html::event::#undelegated(::leptos::tachys::html::event::#event_type) }
|
||||
quote! { ::leptos::tachys::html::event::#undelegated(#event_type) }
|
||||
} else {
|
||||
quote! { ::leptos::tachys::html::event::#event_type }
|
||||
event_type
|
||||
};
|
||||
|
||||
(on, event_type, handler)
|
||||
@@ -1419,13 +1454,22 @@ fn is_ambiguous_element(tag: &str) -> bool {
|
||||
tag == "a" || tag == "script" || tag == "title"
|
||||
}
|
||||
|
||||
fn parse_event(event_name: &str) -> (String, bool, bool) {
|
||||
let is_undelegated = event_name.contains(":undelegated");
|
||||
let is_targeted = event_name.contains(":target");
|
||||
fn parse_event(event_name: &str) -> (String, EventNameOptions) {
|
||||
let undelegated = event_name.contains(":undelegated");
|
||||
let targeted = event_name.contains(":target");
|
||||
let captured = event_name.contains(":capture");
|
||||
let event_name = event_name
|
||||
.replace(":undelegated", "")
|
||||
.replace(":target", "");
|
||||
(event_name, is_undelegated, is_targeted)
|
||||
.replace(":target", "")
|
||||
.replace(":capture", "");
|
||||
(
|
||||
event_name,
|
||||
EventNameOptions {
|
||||
undelegated,
|
||||
targeted,
|
||||
captured,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/// Escapes Rust keywords that are also HTML attribute names
|
||||
@@ -1617,8 +1661,17 @@ const TYPED_EVENTS: [&str; 126] = [
|
||||
|
||||
const CUSTOM_EVENT: &str = "Custom";
|
||||
|
||||
pub(crate) fn parse_event_name(name: &str) -> (TokenStream, bool, bool, bool) {
|
||||
let (name, is_force_undelegated, is_targeted) = parse_event(name);
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct EventNameOptions {
|
||||
undelegated: bool,
|
||||
targeted: bool,
|
||||
captured: bool,
|
||||
}
|
||||
|
||||
pub(crate) fn parse_event_name(
|
||||
name: &str,
|
||||
) -> (TokenStream, bool, EventNameOptions) {
|
||||
let (name, options) = parse_event(name);
|
||||
|
||||
let (event_type, is_custom) = TYPED_EVENTS
|
||||
.binary_search(&name.as_str())
|
||||
@@ -1634,7 +1687,7 @@ pub(crate) fn parse_event_name(name: &str) -> (TokenStream, bool, bool, bool) {
|
||||
} else {
|
||||
event_type
|
||||
};
|
||||
(event_type, is_custom, is_force_undelegated, is_targeted)
|
||||
(event_type, is_custom, options)
|
||||
}
|
||||
|
||||
fn convert_to_snake_case(name: String) -> String {
|
||||
|
||||
@@ -104,3 +104,18 @@ fn component_nostrip() {
|
||||
/>
|
||||
};
|
||||
}
|
||||
|
||||
#[component]
|
||||
fn WithLifetime<'a>(data: &'a str) -> impl IntoView {
|
||||
_ = data;
|
||||
"static lifetime"
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn returns_static_lifetime() {
|
||||
#[allow(unused)]
|
||||
fn can_return_impl_intoview_from_body() -> impl IntoView {
|
||||
let val = String::from("non_static_lifetime");
|
||||
WithLifetime(WithLifetimeProps::builder().data(&val).build())
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
);
|
||||
}
|
||||
@@ -11,7 +11,7 @@ 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 }
|
||||
@@ -26,8 +26,8 @@ send_wrapper = "0.6"
|
||||
# serialization formats
|
||||
serde = { version = "1.0" }
|
||||
js-sys = { version = "0.3.74", optional = true }
|
||||
wasm-bindgen = { version = "0.2.97", optional = true }
|
||||
serde_json = { version = "1.0" }
|
||||
wasm-bindgen = { version = "0.2.100", optional = true }
|
||||
serde_json = { workspace = true }
|
||||
|
||||
[features]
|
||||
ssr = []
|
||||
@@ -46,4 +46,4 @@ denylist = ["tracing"]
|
||||
rustdoc-args = ["--generate-link-to-definition"]
|
||||
|
||||
[lints.rust]
|
||||
unexpected_cfgs = { level = "warn", check-cfg = ['cfg(leptos_debuginfo)'] }
|
||||
unexpected_cfgs = { level = "warn", check-cfg = ['cfg(leptos_debuginfo)'] }
|
||||
|
||||
@@ -12,7 +12,9 @@ use reactive_graph::{
|
||||
guards::{AsyncPlain, ReadGuard},
|
||||
ArcRwSignal, RwSignal,
|
||||
},
|
||||
traits::{DefinedAt, IsDisposed, ReadUntracked, Track, Update, Write},
|
||||
traits::{
|
||||
DefinedAt, IsDisposed, ReadUntracked, Track, Update, With, Write,
|
||||
},
|
||||
};
|
||||
use send_wrapper::SendWrapper;
|
||||
use std::{
|
||||
@@ -91,6 +93,34 @@ impl<T> ArcLocalResource<T> {
|
||||
pub fn refetch(&self) {
|
||||
*self.refetch.write() += 1;
|
||||
}
|
||||
|
||||
/// 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(&SendWrapper<T>) -> U) -> Option<U>
|
||||
where
|
||||
T: 'static,
|
||||
{
|
||||
self.data.try_with(|n| n.as_ref().map(f))?
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, E> ArcLocalResource<Result<T, E>>
|
||||
where
|
||||
T: 'static,
|
||||
E: 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()))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> IntoFuture for ArcLocalResource<T>
|
||||
@@ -142,12 +172,6 @@ where
|
||||
fn try_read_untracked(&self) -> Option<Self::Value> {
|
||||
if let Some(mut notifier) = use_context::<LocalResourceNotifier>() {
|
||||
notifier.notify();
|
||||
} else if cfg!(feature = "ssr") {
|
||||
panic!(
|
||||
"Reading from a LocalResource outside Suspense in `ssr` mode \
|
||||
will cause the response to hang, because LocalResources are \
|
||||
always pending on the server."
|
||||
);
|
||||
}
|
||||
self.data.try_read_untracked()
|
||||
}
|
||||
@@ -334,12 +358,6 @@ where
|
||||
fn try_read_untracked(&self) -> Option<Self::Value> {
|
||||
if let Some(mut notifier) = use_context::<LocalResourceNotifier>() {
|
||||
notifier.notify();
|
||||
} else if cfg!(feature = "ssr") {
|
||||
panic!(
|
||||
"Reading from a LocalResource outside Suspense in `ssr` mode \
|
||||
will cause the response to hang, because LocalResources are \
|
||||
always pending on the server."
|
||||
);
|
||||
}
|
||||
self.data.try_read_untracked()
|
||||
}
|
||||
|
||||
@@ -168,6 +168,41 @@ where
|
||||
|
||||
data
|
||||
}
|
||||
|
||||
/// 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
|
||||
T: Send + Sync + 'static,
|
||||
{
|
||||
self.try_with(|n| n.as_ref().map(f))?
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, E, Ser> ArcOnceResource<Result<T, E>, Ser>
|
||||
where
|
||||
Ser: Encoder<Result<T, E>> + Decoder<Result<T, E>>,
|
||||
<Ser as Encoder<Result<T, E>>>::Error: Debug,
|
||||
<Ser as Decoder<Result<T, E>>>::Error: Debug,
|
||||
<<Ser as Decoder<Result<T, E>>>::Encoded as FromEncodedStr>::DecodingError:
|
||||
Debug,
|
||||
<Ser as Encoder<Result<T, E>>>::Encoded: IntoEncodedString,
|
||||
<Ser as Decoder<Result<T, E>>>::Encoded: FromEncodedStr,
|
||||
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()))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, Ser> ArcOnceResource<T, Ser> {
|
||||
@@ -534,6 +569,37 @@ where
|
||||
defined_at,
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.try_with(|n| n.as_ref().map(|n| Some(f(n))))?.flatten()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, E, Ser> OnceResource<Result<T, E>, Ser>
|
||||
where
|
||||
Ser: Encoder<Result<T, E>> + Decoder<Result<T, E>>,
|
||||
<Ser as Encoder<Result<T, E>>>::Error: Debug,
|
||||
<Ser as Decoder<Result<T, E>>>::Error: Debug,
|
||||
<<Ser as Decoder<Result<T, E>>>::Encoded as FromEncodedStr>::DecodingError:
|
||||
Debug,
|
||||
<Ser as Encoder<Result<T, E>>>::Encoded: IntoEncodedString,
|
||||
<Ser as Decoder<Result<T, E>>>::Encoded: FromEncodedStr,
|
||||
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()))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, Ser> OnceResource<T, Ser>
|
||||
|
||||
@@ -215,16 +215,11 @@ where
|
||||
None
|
||||
}
|
||||
Ok(encoded) => {
|
||||
match Ser::decode(encoded.borrow()) {
|
||||
#[allow(unused_variables)]
|
||||
// used in tracing
|
||||
Err(e) => {
|
||||
#[cfg(feature = "tracing")]
|
||||
tracing::error!("{e:?}");
|
||||
None
|
||||
}
|
||||
Ok(value) => Some(value),
|
||||
}
|
||||
let decoded = Ser::decode(encoded.borrow());
|
||||
#[cfg(feature = "tracing")]
|
||||
let decoded = decoded
|
||||
.inspect_err(|e| tracing::error!("{e:?}"));
|
||||
decoded.ok()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "leptos_meta"
|
||||
version = "0.7.4"
|
||||
version = "0.7.8"
|
||||
authors = ["Greg Johnston"]
|
||||
license = "MIT"
|
||||
repository = "https://github.com/leptos-rs/leptos"
|
||||
@@ -15,7 +15,7 @@ or_poisoned = { workspace = true }
|
||||
indexmap = "2.6"
|
||||
send_wrapper = "0.6.0"
|
||||
tracing = { version = "0.1.41", optional = true }
|
||||
wasm-bindgen = "0.2.97"
|
||||
wasm-bindgen = { workspace = true }
|
||||
futures = "0.3.31"
|
||||
|
||||
[dependencies.web-sys]
|
||||
|
||||
@@ -323,37 +323,13 @@ pub(crate) fn register<E, At, Ch>(
|
||||
where
|
||||
HtmlElement<E, At, Ch>: RenderHtml,
|
||||
{
|
||||
#[allow(unused_mut)] // used for `ssr`
|
||||
let mut el = Some(el);
|
||||
|
||||
#[cfg(feature = "ssr")]
|
||||
if let Some(cx) = use_context::<ServerMetaContext>() {
|
||||
let mut buf = String::new();
|
||||
el.take().unwrap().to_html_with_buf(
|
||||
&mut buf,
|
||||
&mut Position::NextChild,
|
||||
false,
|
||||
false,
|
||||
);
|
||||
_ = cx.elements.send(buf); // fails only if the receiver is already dropped
|
||||
} else {
|
||||
let msg = "tried to use a leptos_meta component without \
|
||||
`ServerMetaContext` provided";
|
||||
|
||||
#[cfg(feature = "tracing")]
|
||||
tracing::warn!("{}", msg);
|
||||
|
||||
#[cfg(not(feature = "tracing"))]
|
||||
eprintln!("{}", msg);
|
||||
}
|
||||
|
||||
RegisteredMetaTag { el }
|
||||
}
|
||||
|
||||
struct RegisteredMetaTag<E, At, Ch> {
|
||||
// this is `None` if we've already taken it out to render to HTML on the server
|
||||
// we don't render it in place in RenderHtml, so it's fine
|
||||
el: Option<HtmlElement<E, At, Ch>>,
|
||||
el: HtmlElement<E, At, Ch>,
|
||||
}
|
||||
|
||||
struct RegisteredMetaTagState<E, At, Ch>
|
||||
@@ -391,12 +367,12 @@ where
|
||||
type State = RegisteredMetaTagState<E, At, Ch>;
|
||||
|
||||
fn build(self) -> Self::State {
|
||||
let state = self.el.unwrap().build();
|
||||
let state = self.el.build();
|
||||
RegisteredMetaTagState { state }
|
||||
}
|
||||
|
||||
fn rebuild(self, state: &mut Self::State) {
|
||||
self.el.unwrap().rebuild(&mut state.state);
|
||||
self.el.rebuild(&mut state.state);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -417,7 +393,7 @@ where
|
||||
Self::Output<NewAttr>: RenderHtml,
|
||||
{
|
||||
RegisteredMetaTag {
|
||||
el: self.el.map(|inner| inner.add_any_attr(attr)),
|
||||
el: self.el.add_any_attr(attr),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -449,6 +425,26 @@ where
|
||||
) {
|
||||
// meta tags are rendered into the buffer stored into the context
|
||||
// the value has already been taken out, when we're on the server
|
||||
#[cfg(feature = "ssr")]
|
||||
if let Some(cx) = use_context::<ServerMetaContext>() {
|
||||
let mut buf = String::new();
|
||||
self.el.to_html_with_buf(
|
||||
&mut buf,
|
||||
&mut Position::NextChild,
|
||||
false,
|
||||
false,
|
||||
);
|
||||
_ = cx.elements.send(buf); // fails only if the receiver is already dropped
|
||||
} else {
|
||||
let msg = "tried to use a leptos_meta component without \
|
||||
`ServerMetaContext` provided";
|
||||
|
||||
#[cfg(feature = "tracing")]
|
||||
tracing::warn!("{}", msg);
|
||||
|
||||
#[cfg(not(feature = "tracing"))]
|
||||
eprintln!("{}", msg);
|
||||
}
|
||||
}
|
||||
|
||||
fn hydrate<const FROM_SERVER: bool>(
|
||||
@@ -462,7 +458,7 @@ where
|
||||
MetaContext provided",
|
||||
)
|
||||
.cursor;
|
||||
let state = self.el.unwrap().hydrate::<FROM_SERVER>(
|
||||
let state = self.el.hydrate::<FROM_SERVER>(
|
||||
&cursor,
|
||||
&PositionState::new(Position::NextChild),
|
||||
);
|
||||
|
||||
@@ -13,4 +13,4 @@ serde = "1.0"
|
||||
thiserror = "2.0"
|
||||
|
||||
[dev-dependencies]
|
||||
serde_json = "1.0"
|
||||
serde_json = { workspace = true }
|
||||
|
||||
@@ -35,7 +35,7 @@ pub trait OrPoisoned {
|
||||
fn or_poisoned(self) -> Self::Inner;
|
||||
}
|
||||
|
||||
impl<'a, T> OrPoisoned
|
||||
impl<'a, T: ?Sized> OrPoisoned
|
||||
for Result<RwLockReadGuard<'a, T>, PoisonError<RwLockReadGuard<'a, T>>>
|
||||
{
|
||||
type Inner = RwLockReadGuard<'a, T>;
|
||||
@@ -45,7 +45,7 @@ impl<'a, T> OrPoisoned
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T> OrPoisoned
|
||||
impl<'a, T: ?Sized> OrPoisoned
|
||||
for Result<RwLockWriteGuard<'a, T>, PoisonError<RwLockWriteGuard<'a, T>>>
|
||||
{
|
||||
type Inner = RwLockWriteGuard<'a, T>;
|
||||
@@ -55,7 +55,7 @@ impl<'a, T> OrPoisoned
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T> OrPoisoned for LockResult<MutexGuard<'a, T>> {
|
||||
impl<'a, T: ?Sized> OrPoisoned for LockResult<MutexGuard<'a, T>> {
|
||||
type Inner = MutexGuard<'a, T>;
|
||||
|
||||
fn or_poisoned(self) -> Self::Inner {
|
||||
|
||||
@@ -8,19 +8,19 @@ codegen-units = 1
|
||||
lto = true
|
||||
|
||||
[dependencies]
|
||||
leptos = { version = "0.6.13", features = ["csr"] }
|
||||
leptos_meta = { version = "0.6.13", features = ["csr"] }
|
||||
leptos_router = { version = "0.6.13", features = ["csr"] }
|
||||
leptos = { version = "0.7.8", features = ["csr"] }
|
||||
leptos_meta = { version = "0.7.8" }
|
||||
leptos_router = { version = "0.7.8" }
|
||||
console_log = "1.0"
|
||||
log = "0.4.22"
|
||||
console_error_panic_hook = "0.1.7"
|
||||
bevy = "0.14.1"
|
||||
bevy = "0.15.2"
|
||||
crossbeam-channel = "0.5.13"
|
||||
|
||||
[dev-dependencies]
|
||||
wasm-bindgen = "0.2.92"
|
||||
wasm-bindgen-test = "0.3.42"
|
||||
web-sys = "0.3.69"
|
||||
wasm-bindgen = "0.2.100"
|
||||
wasm-bindgen-test = "0.3.50"
|
||||
web-sys = "0.3.77"
|
||||
|
||||
[workspace]
|
||||
# The empty workspace here is to keep rust-analyzer satisfied
|
||||
|
||||
@@ -17,7 +17,7 @@ impl DuplexEventsPlugin {
|
||||
let (bevy_sender, client_receiver) = crossbeam_channel::bounded(50);
|
||||
// For sending message from the client to bevy
|
||||
let (client_sender, bevy_receiver) = crossbeam_channel::bounded(50);
|
||||
let instance = DuplexEventsPlugin {
|
||||
DuplexEventsPlugin {
|
||||
client_processor: EventProcessor {
|
||||
sender: client_sender,
|
||||
receiver: client_receiver,
|
||||
@@ -26,8 +26,7 @@ impl DuplexEventsPlugin {
|
||||
sender: bevy_sender,
|
||||
receiver: bevy_receiver,
|
||||
},
|
||||
};
|
||||
instance
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the client event processor
|
||||
|
||||
@@ -23,14 +23,13 @@ impl Scene {
|
||||
/// Create a new instance
|
||||
pub fn new(canvas_id: String) -> Scene {
|
||||
let plugin = DuplexEventsPlugin::new();
|
||||
let instance = Scene {
|
||||
Scene {
|
||||
is_setup: false,
|
||||
canvas_id: canvas_id,
|
||||
canvas_id,
|
||||
evt_plugin: plugin.clone(),
|
||||
shared_state: SharedState::new(),
|
||||
processor: plugin.get_processor(),
|
||||
};
|
||||
instance
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the shared state
|
||||
@@ -47,7 +46,7 @@ impl Scene {
|
||||
|
||||
/// Setup and attach the bevy instance to the html canvas element
|
||||
pub fn setup(&mut self) {
|
||||
if self.is_setup == true {
|
||||
if self.is_setup {
|
||||
return;
|
||||
};
|
||||
App::new()
|
||||
@@ -76,40 +75,37 @@ fn setup_scene(
|
||||
) {
|
||||
let name = resource.0.lock().unwrap().name.clone();
|
||||
// circular base
|
||||
commands.spawn(PbrBundle {
|
||||
mesh: meshes.add(Circle::new(4.0)),
|
||||
material: materials.add(Color::WHITE),
|
||||
transform: Transform::from_rotation(Quat::from_rotation_x(
|
||||
commands.spawn((
|
||||
Mesh3d(meshes.add(Circle::new(4.0))),
|
||||
MeshMaterial3d(materials.add(Color::WHITE)),
|
||||
Transform::from_rotation(Quat::from_rotation_x(
|
||||
-std::f32::consts::FRAC_PI_2,
|
||||
)),
|
||||
..default()
|
||||
});
|
||||
));
|
||||
|
||||
// cube
|
||||
commands.spawn((
|
||||
PbrBundle {
|
||||
mesh: meshes.add(Cuboid::new(1.0, 1.0, 1.0)),
|
||||
material: materials.add(Color::rgb_u8(124, 144, 255)),
|
||||
transform: Transform::from_xyz(0.0, 0.5, 0.0),
|
||||
..default()
|
||||
},
|
||||
Mesh3d(meshes.add(Cuboid::new(1.0, 1.0, 1.0))),
|
||||
MeshMaterial3d(materials.add(Color::srgb_u8(124, 144, 255))),
|
||||
Transform::from_xyz(0.0, 0.5, 0.0),
|
||||
Cube,
|
||||
));
|
||||
|
||||
// light
|
||||
commands.spawn(PointLightBundle {
|
||||
point_light: PointLight {
|
||||
commands.spawn((
|
||||
PointLight {
|
||||
shadows_enabled: true,
|
||||
..default()
|
||||
},
|
||||
transform: Transform::from_xyz(4.0, 8.0, 4.0),
|
||||
..default()
|
||||
});
|
||||
Transform::from_xyz(4.0, 8.0, 4.0),
|
||||
));
|
||||
|
||||
// camera
|
||||
commands.spawn(Camera3dBundle {
|
||||
transform: Transform::from_xyz(-2.5, 4.5, 9.0)
|
||||
.looking_at(Vec3::ZERO, Vec3::Y),
|
||||
..default()
|
||||
});
|
||||
commands.spawn(TextBundle::from_section(name, TextStyle::default()));
|
||||
commands.spawn((
|
||||
Camera3d::default(),
|
||||
Transform::from_xyz(-2.5, 4.5, 9.0).looking_at(Vec3::ZERO, Vec3::Y),
|
||||
));
|
||||
commands.spawn((Text::new(name), TextFont::default()));
|
||||
}
|
||||
|
||||
/// Move the Cube on event
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
mod demos;
|
||||
mod routes;
|
||||
use leptos::*;
|
||||
use leptos::prelude::*;
|
||||
use routes::RootPage;
|
||||
|
||||
pub fn main() {
|
||||
|
||||
@@ -2,7 +2,7 @@ use crate::demos::bevydemo1::eventqueue::events::{
|
||||
ClientInEvents, CounterEvtData,
|
||||
};
|
||||
use crate::demos::bevydemo1::scene::Scene;
|
||||
use leptos::*;
|
||||
use leptos::prelude::*;
|
||||
|
||||
/// 3d view component
|
||||
#[component]
|
||||
@@ -10,18 +10,18 @@ pub fn Demo1() -> impl IntoView {
|
||||
// Setup a Counter
|
||||
let initial_value: i32 = 0;
|
||||
let step: i32 = 1;
|
||||
let (value, set_value) = create_signal(initial_value);
|
||||
let (value, set_value) = signal(initial_value);
|
||||
|
||||
// Setup a bevy 3d scene
|
||||
let scene = Scene::new("#bevy".to_string());
|
||||
let sender = scene.get_processor().sender;
|
||||
let (sender_sig, _set_sender_sig) = create_signal(sender);
|
||||
let (scene_sig, _set_scene_sig) = create_signal(scene);
|
||||
let (sender_sig, _set_sender_sig) = signal(sender);
|
||||
let (scene_sig, _set_scene_sig) = signal(scene);
|
||||
|
||||
// We need to add the 3D view onto the canvas post render.
|
||||
create_effect(move |_| {
|
||||
Effect::new(move |_| {
|
||||
request_animation_frame(move || {
|
||||
scene_sig.get().setup();
|
||||
scene_sig.get_untracked().setup();
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
pub mod demo1;
|
||||
use demo1::Demo1;
|
||||
use leptos::*;
|
||||
use leptos_meta::{provide_meta_context, Meta, Stylesheet, Title};
|
||||
use leptos_router::*;
|
||||
|
||||
use leptos::prelude::*;
|
||||
use leptos_meta::Meta;
|
||||
use leptos_meta::Title;
|
||||
use leptos_meta::{provide_meta_context, MetaTags, Stylesheet};
|
||||
use leptos_router::components::*;
|
||||
use leptos_router::StaticSegment;
|
||||
#[component]
|
||||
pub fn RootPage() -> impl IntoView {
|
||||
provide_meta_context();
|
||||
@@ -13,11 +15,12 @@ pub fn RootPage() -> impl IntoView {
|
||||
<Meta name="description" content="Leptonic CSR template"/>
|
||||
<Meta name="viewport" content="width=device-width, initial-scale=1.0"/>
|
||||
<Meta name="theme-color" content="#e66956"/>
|
||||
<Stylesheet href="https://fonts.googleapis.com/css?family=Roboto&display=swap"/>
|
||||
<Title text="Leptos Bevy3D Example"/>
|
||||
<Stylesheet href="https://fonts.googleapis.com/css?family=Roboto&display=swap"/>
|
||||
<MetaTags/>
|
||||
<Router>
|
||||
<Routes>
|
||||
<Route path="" view=|| view! { <Demo1/> }/>
|
||||
<Routes fallback=move || "Not found.">
|
||||
<Route path=StaticSegment("") view=Demo1 />
|
||||
</Routes>
|
||||
</Router>
|
||||
}
|
||||
|
||||
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,
|
||||
}
|
||||
149
projects/hexagonal-architecture/src/trait_impl.rs
Normal file
149
projects/hexagonal-architecture/src/trait_impl.rs
Normal file
@@ -0,0 +1,149 @@
|
||||
use crate::ui_types::*;
|
||||
|
||||
use super::server_types::*;
|
||||
use super::traits::*;
|
||||
use axum::async_trait;
|
||||
use axum::extract::FromRef;
|
||||
use leptos::config::LeptosOptions;
|
||||
|
||||
// So we can pass our server state as state into our leptos router.
|
||||
impl<Handler: HandlerTrait + Clone> FromRef<ServerState<Handler>> for LeptosOptions {
|
||||
fn from_ref(input: &ServerState<Handler>) -> Self {
|
||||
input.leptos_options.clone()
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<SubDomain1, SubDomain2> HandlerTrait for HandlerStruct<SubDomain1, SubDomain2>
|
||||
where
|
||||
SubDomain1: SubDomainTrait1 + Send + Sync,
|
||||
SubDomain2: SubDomainTrait2 + Send + Sync,
|
||||
{
|
||||
async fn server_fn_1(&self) -> Result<DomainData, DomainError> {
|
||||
Ok(self.sub_domain_1.sub_domain_1_method().await?.into())
|
||||
}
|
||||
|
||||
async fn server_fn_2(&self) -> Result<DomainData2, DomainError> {
|
||||
Ok(self.sub_domain_2.sub_domain_2_method().await?.into())
|
||||
}
|
||||
|
||||
async fn server_fn_3(&self) -> Result<DomainData3, DomainError> {
|
||||
Ok((
|
||||
self.sub_domain_1.sub_domain_1_method().await?,
|
||||
self.sub_domain_2.sub_domain_2_method().await?,
|
||||
)
|
||||
.into())
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<ExternalService1, ExternalService2> SubDomainTrait1
|
||||
for SubDomainStruct1<ExternalService1, ExternalService2>
|
||||
where
|
||||
ExternalService1: ExternalServiceTrait1 + Send + Sync,
|
||||
ExternalService2: ExternalServiceTrait2 + Send + Sync,
|
||||
{
|
||||
async fn sub_domain_1_method(&self) -> Result<SubDomain1Data, SubDomain1Error> {
|
||||
Ok((
|
||||
self.external_service_1.external_service_1_method().await?,
|
||||
self.external_service_2.external_service_2_method().await?,
|
||||
)
|
||||
.into())
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<ExternalService1> SubDomainTrait2 for SubDomainStruct2<ExternalService1>
|
||||
where
|
||||
ExternalService1: ExternalServiceTrait1 + Send + Sync,
|
||||
{
|
||||
async fn sub_domain_2_method(&self) -> Result<SubDomain2Data, SubDomain2Error> {
|
||||
Ok(self
|
||||
.external_service_1
|
||||
.external_service_1_method()
|
||||
.await?
|
||||
.into())
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl ExternalServiceTrait1 for ExternalService1_1 {
|
||||
async fn external_service_1_method(
|
||||
&self,
|
||||
) -> Result<ExternalService1Data, ExternalService1Error> {
|
||||
println!("External Service 1 From External Service 1_1");
|
||||
Ok(ExternalService1Data)
|
||||
}
|
||||
}
|
||||
#[async_trait]
|
||||
impl ExternalServiceTrait1 for ExternalService1_2 {
|
||||
async fn external_service_1_method(
|
||||
&self,
|
||||
) -> Result<ExternalService1Data, ExternalService1Error> {
|
||||
println!("External Service 1 From External Service 1_2");
|
||||
Ok(ExternalService1Data)
|
||||
}
|
||||
}
|
||||
#[async_trait]
|
||||
impl ExternalServiceTrait2 for ExternalService2_1 {
|
||||
async fn external_service_2_method(
|
||||
&self,
|
||||
) -> Result<ExternalService2Data, ExternalService2Error> {
|
||||
println!("External Service 2 From External Service 2_1");
|
||||
Ok(ExternalService2Data)
|
||||
}
|
||||
}
|
||||
#[async_trait]
|
||||
impl ExternalServiceTrait2 for ExternalService2_2 {
|
||||
async fn external_service_2_method(
|
||||
&self,
|
||||
) -> Result<ExternalService2Data, ExternalService2Error> {
|
||||
println!("External Service 2 From External Service 2_2");
|
||||
Ok(ExternalService2Data)
|
||||
}
|
||||
}
|
||||
|
||||
// Sub Domain mapping
|
||||
impl From<(ExternalService1Data, ExternalService2Data)> for SubDomain1Data {
|
||||
fn from(_: (ExternalService1Data, ExternalService2Data)) -> Self {
|
||||
Self
|
||||
}
|
||||
}
|
||||
impl From<ExternalService1Data> for SubDomain2Data {
|
||||
fn from(_: ExternalService1Data) -> Self {
|
||||
Self
|
||||
}
|
||||
}
|
||||
// Domain Mapping
|
||||
impl From<SubDomain1Data> for DomainData {
|
||||
fn from(_: SubDomain1Data) -> Self {
|
||||
Self
|
||||
}
|
||||
}
|
||||
impl From<SubDomain2Data> for DomainData2 {
|
||||
fn from(_: SubDomain2Data) -> Self {
|
||||
Self
|
||||
}
|
||||
}
|
||||
impl From<(SubDomain1Data, SubDomain2Data)> for DomainData3 {
|
||||
fn from(_: (SubDomain1Data, SubDomain2Data)) -> Self {
|
||||
Self
|
||||
}
|
||||
}
|
||||
|
||||
// Ui Mapping
|
||||
impl From<DomainData> for UiMappingFromDomainData {
|
||||
fn from(_: DomainData) -> Self {
|
||||
Self
|
||||
}
|
||||
}
|
||||
impl From<DomainData2> for UiMappingFromDomainData2 {
|
||||
fn from(_: DomainData2) -> Self {
|
||||
Self
|
||||
}
|
||||
}
|
||||
impl From<DomainData3> for UiMappingFromDomainData3 {
|
||||
fn from(_: DomainData3) -> Self {
|
||||
Self
|
||||
}
|
||||
}
|
||||
42
projects/hexagonal-architecture/src/traits.rs
Normal file
42
projects/hexagonal-architecture/src/traits.rs
Normal file
@@ -0,0 +1,42 @@
|
||||
use super::server_types::*;
|
||||
use axum::async_trait;
|
||||
use mockall::automock;
|
||||
pub trait New {
|
||||
fn new() -> Self;
|
||||
}
|
||||
|
||||
#[automock]
|
||||
#[async_trait]
|
||||
pub trait HandlerTrait {
|
||||
async fn server_fn_1(&self) -> Result<DomainData, DomainError>;
|
||||
async fn server_fn_2(&self) -> Result<DomainData2, DomainError>;
|
||||
async fn server_fn_3(&self) -> Result<DomainData3, DomainError>;
|
||||
}
|
||||
|
||||
#[automock]
|
||||
#[async_trait]
|
||||
pub trait SubDomainTrait1 {
|
||||
async fn sub_domain_1_method(&self) -> Result<SubDomain1Data, SubDomain1Error>;
|
||||
}
|
||||
|
||||
#[automock]
|
||||
#[async_trait]
|
||||
pub trait SubDomainTrait2 {
|
||||
async fn sub_domain_2_method(&self) -> Result<SubDomain2Data, SubDomain2Error>;
|
||||
}
|
||||
|
||||
#[automock]
|
||||
#[async_trait]
|
||||
pub trait ExternalServiceTrait1 {
|
||||
async fn external_service_1_method(
|
||||
&self,
|
||||
) -> Result<ExternalService1Data, ExternalService1Error>;
|
||||
}
|
||||
|
||||
#[automock]
|
||||
#[async_trait]
|
||||
pub trait ExternalServiceTrait2 {
|
||||
async fn external_service_2_method(
|
||||
&self,
|
||||
) -> Result<ExternalService2Data, ExternalService2Error>;
|
||||
}
|
||||
8
projects/hexagonal-architecture/src/ui_types.rs
Normal file
8
projects/hexagonal-architecture/src/ui_types.rs
Normal file
@@ -0,0 +1,8 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub struct UiMappingFromDomainData;
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub struct UiMappingFromDomainData2;
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub struct UiMappingFromDomainData3;
|
||||
4
projects/hexagonal-architecture/style/main.scss
Normal file
4
projects/hexagonal-architecture/style/main.scss
Normal file
@@ -0,0 +1,4 @@
|
||||
body {
|
||||
font-family: sans-serif;
|
||||
text-align: center;
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "reactive_graph"
|
||||
version = "0.1.4"
|
||||
version = "0.1.8"
|
||||
authors = ["Greg Johnston"]
|
||||
license = "MIT"
|
||||
readme = "../README.md"
|
||||
@@ -28,7 +28,7 @@ send_wrapper = { version = "0.6.0", features = ["futures"] }
|
||||
web-sys = { version = "0.3.72", features = ["console"] }
|
||||
|
||||
[dev-dependencies]
|
||||
tokio = { version = "1.41", features = ["rt-multi-thread", "macros"] }
|
||||
tokio = { version = "1.43", features = ["rt-multi-thread", "macros"] }
|
||||
tokio-test = { version = "0.4.4" }
|
||||
any_spawner = { workspace = true, features = ["futures-executor", "tokio"] }
|
||||
|
||||
|
||||
@@ -939,7 +939,8 @@ where
|
||||
#[track_caller]
|
||||
pub fn dispatch(&self, input: I) -> ActionAbortHandle {
|
||||
self.inner
|
||||
.try_with_value(|inner| inner.dispatch(input))
|
||||
.try_get_value()
|
||||
.map(|inner| inner.dispatch(input))
|
||||
.unwrap_or_else(unwrap_signal!(self))
|
||||
}
|
||||
}
|
||||
@@ -954,7 +955,8 @@ where
|
||||
#[track_caller]
|
||||
pub fn dispatch_local(&self, input: I) -> ActionAbortHandle {
|
||||
self.inner
|
||||
.try_with_value(|inner| inner.dispatch_local(input))
|
||||
.try_get_value()
|
||||
.map(|inner| inner.dispatch_local(input))
|
||||
.unwrap_or_else(unwrap_signal!(self))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,7 +15,6 @@ use crate::{
|
||||
};
|
||||
pub use arc_memo::*;
|
||||
pub use async_derived::*;
|
||||
pub(crate) use inner::MemoInner;
|
||||
pub use memo::*;
|
||||
pub use selector::*;
|
||||
|
||||
|
||||
@@ -12,11 +12,10 @@ use crate::{
|
||||
traits::{DefinedAt, Get, IsDisposed, ReadUntracked},
|
||||
};
|
||||
use core::fmt::Debug;
|
||||
use or_poisoned::OrPoisoned;
|
||||
use std::{
|
||||
hash::Hash,
|
||||
panic::Location,
|
||||
sync::{Arc, RwLock, Weak},
|
||||
sync::{Arc, Weak},
|
||||
};
|
||||
|
||||
/// An efficient derived reactive value based on other reactive values.
|
||||
@@ -95,7 +94,7 @@ where
|
||||
{
|
||||
#[cfg(any(debug_assertions, leptos_debuginfo))]
|
||||
defined_at: &'static Location<'static>,
|
||||
inner: Arc<RwLock<MemoInner<T, S>>>,
|
||||
inner: Arc<MemoInner<T, S>>,
|
||||
}
|
||||
|
||||
impl<T: 'static> ArcMemo<T, SyncStorage>
|
||||
@@ -161,7 +160,7 @@ where
|
||||
Weak::clone(weak) as Weak<dyn Subscriber + Send + Sync>,
|
||||
);
|
||||
|
||||
RwLock::new(MemoInner::new(Arc::new(fun), subscriber))
|
||||
MemoInner::new(Arc::new(fun), subscriber)
|
||||
});
|
||||
Self {
|
||||
#[cfg(any(debug_assertions, leptos_debuginfo))]
|
||||
@@ -312,15 +311,11 @@ where
|
||||
S: Storage<T>,
|
||||
{
|
||||
fn add_source(&self, source: AnySource) {
|
||||
self.inner.write().or_poisoned().sources.insert(source);
|
||||
self.inner.add_source(source);
|
||||
}
|
||||
|
||||
fn clear_sources(&self, subscriber: &AnySubscriber) {
|
||||
self.inner
|
||||
.write()
|
||||
.or_poisoned()
|
||||
.sources
|
||||
.clear_sources(subscriber);
|
||||
self.inner.clear_sources(subscriber);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -328,15 +323,15 @@ impl<T: 'static, S> ReadUntracked for ArcMemo<T, S>
|
||||
where
|
||||
S: Storage<T>,
|
||||
{
|
||||
type Value = ReadGuard<T, Mapped<Plain<MemoInner<T, S>>, T>>;
|
||||
type Value = ReadGuard<T, Mapped<Plain<Option<S::Wrapped>>, T>>;
|
||||
|
||||
fn try_read_untracked(&self) -> Option<Self::Value> {
|
||||
self.update_if_necessary();
|
||||
|
||||
Mapped::try_new(Arc::clone(&self.inner), |t| {
|
||||
Mapped::try_new(Arc::clone(&self.inner.value), |t| {
|
||||
// safe to unwrap here because update_if_necessary
|
||||
// guarantees the value is Some
|
||||
t.value.as_ref().unwrap().as_borrowed()
|
||||
t.as_ref().unwrap().as_borrowed()
|
||||
})
|
||||
.map(ReadGuard::new)
|
||||
}
|
||||
|
||||
@@ -324,7 +324,7 @@ macro_rules! spawn_derived {
|
||||
}
|
||||
|
||||
while rx.next().await.is_some() {
|
||||
let update_if_necessary = if $should_track {
|
||||
let update_if_necessary = !owner.paused() && if $should_track {
|
||||
any_subscriber
|
||||
.with_observer(|| any_subscriber.update_if_necessary())
|
||||
} else {
|
||||
|
||||
@@ -15,10 +15,15 @@ pub struct MemoInner<T, S>
|
||||
where
|
||||
S: Storage<T>,
|
||||
{
|
||||
pub(crate) value: Option<S::Wrapped>,
|
||||
/// Must always be aquired *after* the reactivity lock
|
||||
pub(crate) value: Arc<RwLock<Option<S::Wrapped>>>,
|
||||
#[allow(clippy::type_complexity)]
|
||||
pub(crate) fun: Arc<dyn Fn(Option<T>) -> (T, bool) + Send + Sync>,
|
||||
pub(crate) owner: Owner,
|
||||
pub(crate) reactivity: RwLock<MemoInnerReactivity>,
|
||||
}
|
||||
|
||||
pub(crate) struct MemoInnerReactivity {
|
||||
pub(crate) state: ReactiveNodeState,
|
||||
pub(crate) sources: SourceSet,
|
||||
pub(crate) subscribers: SubscriberSet,
|
||||
@@ -44,40 +49,44 @@ where
|
||||
any_subscriber: AnySubscriber,
|
||||
) -> Self {
|
||||
Self {
|
||||
value: None,
|
||||
value: Arc::new(RwLock::new(None)),
|
||||
fun,
|
||||
owner: Owner::new(),
|
||||
state: ReactiveNodeState::Dirty,
|
||||
sources: Default::default(),
|
||||
subscribers: SubscriberSet::new(),
|
||||
any_subscriber,
|
||||
reactivity: RwLock::new(MemoInnerReactivity {
|
||||
state: ReactiveNodeState::Dirty,
|
||||
sources: Default::default(),
|
||||
subscribers: SubscriberSet::new(),
|
||||
any_subscriber,
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: 'static, S> ReactiveNode for RwLock<MemoInner<T, S>>
|
||||
impl<T: 'static, S> ReactiveNode for MemoInner<T, S>
|
||||
where
|
||||
S: Storage<T>,
|
||||
{
|
||||
fn mark_dirty(&self) {
|
||||
self.write().or_poisoned().state = ReactiveNodeState::Dirty;
|
||||
self.reactivity.write().or_poisoned().state = ReactiveNodeState::Dirty;
|
||||
self.mark_subscribers_check();
|
||||
}
|
||||
|
||||
fn mark_check(&self) {
|
||||
{
|
||||
let mut lock = self.write().or_poisoned();
|
||||
let mut lock = self.reactivity.write().or_poisoned();
|
||||
if lock.state != ReactiveNodeState::Dirty {
|
||||
lock.state = ReactiveNodeState::Check;
|
||||
}
|
||||
}
|
||||
for sub in (&self.read().or_poisoned().subscribers).into_iter() {
|
||||
for sub in
|
||||
(&self.reactivity.read().or_poisoned().subscribers).into_iter()
|
||||
{
|
||||
sub.mark_check();
|
||||
}
|
||||
}
|
||||
|
||||
fn mark_subscribers_check(&self) {
|
||||
let lock = self.read().or_poisoned();
|
||||
let lock = self.reactivity.read().or_poisoned();
|
||||
for sub in (&lock.subscribers).into_iter() {
|
||||
sub.mark_check();
|
||||
}
|
||||
@@ -85,7 +94,7 @@ where
|
||||
|
||||
fn update_if_necessary(&self) -> bool {
|
||||
let (state, sources) = {
|
||||
let inner = self.read().or_poisoned();
|
||||
let inner = self.reactivity.read().or_poisoned();
|
||||
(inner.state, inner.sources.clone())
|
||||
};
|
||||
|
||||
@@ -94,32 +103,37 @@ where
|
||||
ReactiveNodeState::Dirty => true,
|
||||
ReactiveNodeState::Check => (&sources).into_iter().any(|source| {
|
||||
source.update_if_necessary()
|
||||
|| self.read().or_poisoned().state
|
||||
|| self.reactivity.read().or_poisoned().state
|
||||
== ReactiveNodeState::Dirty
|
||||
}),
|
||||
};
|
||||
|
||||
if needs_update {
|
||||
let (fun, value, owner) = {
|
||||
let mut lock = self.write().or_poisoned();
|
||||
(lock.fun.clone(), lock.value.take(), lock.owner.clone())
|
||||
};
|
||||
let fun = self.fun.clone();
|
||||
let owner = self.owner.clone();
|
||||
// No deadlock risk, because we only hold the value lock.
|
||||
let value = self.value.write().or_poisoned().take();
|
||||
|
||||
let any_subscriber =
|
||||
{ self.read().or_poisoned().any_subscriber.clone() };
|
||||
{ self.reactivity.read().or_poisoned().any_subscriber.clone() };
|
||||
any_subscriber.clear_sources(&any_subscriber);
|
||||
let (new_value, changed) = owner.with_cleanup(|| {
|
||||
any_subscriber
|
||||
.with_observer(|| fun(value.map(StorageAccess::into_taken)))
|
||||
});
|
||||
|
||||
let mut lock = self.write().or_poisoned();
|
||||
lock.value = Some(S::wrap(new_value));
|
||||
lock.state = ReactiveNodeState::Clean;
|
||||
// Two locks are aquired, so order matters.
|
||||
let mut reactivity_lock = self.reactivity.write().or_poisoned();
|
||||
{
|
||||
// Safety: Can block endlessly if the user is has a ReadGuard on the value
|
||||
let mut value_lock = self.value.write().or_poisoned();
|
||||
*value_lock = Some(S::wrap(new_value));
|
||||
}
|
||||
reactivity_lock.state = ReactiveNodeState::Clean;
|
||||
|
||||
if changed {
|
||||
let subs = lock.subscribers.clone();
|
||||
drop(lock);
|
||||
let subs = reactivity_lock.subscribers.clone();
|
||||
drop(reactivity_lock);
|
||||
for sub in subs {
|
||||
// don't trigger reruns of effects/memos
|
||||
// basically: if one of the observers has triggered this memo to
|
||||
@@ -128,49 +142,54 @@ where
|
||||
sub.mark_dirty();
|
||||
}
|
||||
}
|
||||
} else {
|
||||
drop(reactivity_lock);
|
||||
}
|
||||
|
||||
changed
|
||||
} else {
|
||||
if let Ok(mut lock) = self.try_write() {
|
||||
lock.state = ReactiveNodeState::Clean;
|
||||
}
|
||||
let mut lock = self.reactivity.write().or_poisoned();
|
||||
lock.state = ReactiveNodeState::Clean;
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: 'static, S> Source for RwLock<MemoInner<T, S>>
|
||||
impl<T: 'static, S> Source for MemoInner<T, S>
|
||||
where
|
||||
S: Storage<T>,
|
||||
{
|
||||
fn add_subscriber(&self, subscriber: AnySubscriber) {
|
||||
if let Ok(mut lock) = self.try_write() {
|
||||
lock.subscribers.subscribe(subscriber);
|
||||
}
|
||||
let mut lock = self.reactivity.write().or_poisoned();
|
||||
lock.subscribers.subscribe(subscriber);
|
||||
}
|
||||
|
||||
fn remove_subscriber(&self, subscriber: &AnySubscriber) {
|
||||
self.write()
|
||||
self.reactivity
|
||||
.write()
|
||||
.or_poisoned()
|
||||
.subscribers
|
||||
.unsubscribe(subscriber);
|
||||
}
|
||||
|
||||
fn clear_subscribers(&self) {
|
||||
self.write().or_poisoned().subscribers.take();
|
||||
self.reactivity.write().or_poisoned().subscribers.take();
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: 'static, S> Subscriber for RwLock<MemoInner<T, S>>
|
||||
impl<T: 'static, S> Subscriber for MemoInner<T, S>
|
||||
where
|
||||
S: Storage<T>,
|
||||
{
|
||||
fn add_source(&self, source: AnySource) {
|
||||
self.write().or_poisoned().sources.insert(source);
|
||||
self.reactivity.write().or_poisoned().sources.insert(source);
|
||||
}
|
||||
|
||||
fn clear_sources(&self, subscriber: &AnySubscriber) {
|
||||
self.write().or_poisoned().sources.clear_sources(subscriber);
|
||||
self.reactivity
|
||||
.write()
|
||||
.or_poisoned()
|
||||
.sources
|
||||
.clear_sources(subscriber);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::{inner::MemoInner, ArcMemo};
|
||||
use super::ArcMemo;
|
||||
use crate::{
|
||||
owner::{ArenaItem, FromLocal, LocalStorage, Storage, SyncStorage},
|
||||
signal::{
|
||||
@@ -306,7 +306,8 @@ where
|
||||
T: 'static,
|
||||
S: Storage<ArcMemo<T, S>> + Storage<T>,
|
||||
{
|
||||
type Value = ReadGuard<T, Mapped<Plain<MemoInner<T, S>>, T>>;
|
||||
type Value =
|
||||
ReadGuard<T, Mapped<Plain<Option<<S as Storage<T>>::Wrapped>>, T>>;
|
||||
|
||||
fn try_read_untracked(&self) -> Option<Self::Value> {
|
||||
self.inner
|
||||
|
||||
@@ -3,11 +3,13 @@
|
||||
#[allow(clippy::module_inception)]
|
||||
mod effect;
|
||||
mod effect_function;
|
||||
mod immediate;
|
||||
mod inner;
|
||||
mod render_effect;
|
||||
|
||||
pub use effect::*;
|
||||
pub use effect_function::*;
|
||||
pub use immediate::*;
|
||||
pub use render_effect::*;
|
||||
|
||||
/// Creates a new render effect, which immediately runs `fun`.
|
||||
|
||||
@@ -170,9 +170,10 @@ impl Effect<LocalStorage> {
|
||||
|
||||
async move {
|
||||
while rx.next().await.is_some() {
|
||||
if subscriber
|
||||
.with_observer(|| subscriber.update_if_necessary())
|
||||
|| first_run
|
||||
if !owner.paused()
|
||||
&& (subscriber.with_observer(|| {
|
||||
subscriber.update_if_necessary()
|
||||
}) || first_run)
|
||||
{
|
||||
first_run = false;
|
||||
subscriber.clear_sources(&subscriber);
|
||||
@@ -321,9 +322,10 @@ impl Effect<LocalStorage> {
|
||||
|
||||
async move {
|
||||
while rx.next().await.is_some() {
|
||||
if subscriber
|
||||
.with_observer(|| subscriber.update_if_necessary())
|
||||
|| first_run
|
||||
if !owner.paused()
|
||||
&& (subscriber.with_observer(|| {
|
||||
subscriber.update_if_necessary()
|
||||
}) || first_run)
|
||||
{
|
||||
subscriber.clear_sources(&subscriber);
|
||||
|
||||
@@ -372,46 +374,16 @@ impl Effect<SyncStorage> {
|
||||
/// This spawns a task that can be run on any thread. For an effect that will be spawned on
|
||||
/// the current thread, use [`new`](Effect::new).
|
||||
pub fn new_sync<T, M>(
|
||||
mut fun: impl EffectFunction<T, M> + Send + Sync + 'static,
|
||||
fun: impl EffectFunction<T, M> + Send + Sync + 'static,
|
||||
) -> Self
|
||||
where
|
||||
T: Send + Sync + 'static,
|
||||
{
|
||||
let inner = cfg!(feature = "effects").then(|| {
|
||||
let (mut rx, owner, inner) = effect_base();
|
||||
let mut first_run = true;
|
||||
let value = Arc::new(RwLock::new(None::<T>));
|
||||
if !cfg!(feature = "effects") {
|
||||
return Self { inner: None };
|
||||
}
|
||||
|
||||
crate::spawn({
|
||||
let value = Arc::clone(&value);
|
||||
let subscriber = inner.to_any_subscriber();
|
||||
|
||||
async move {
|
||||
while rx.next().await.is_some() {
|
||||
if subscriber
|
||||
.with_observer(|| subscriber.update_if_necessary())
|
||||
|| first_run
|
||||
{
|
||||
first_run = false;
|
||||
subscriber.clear_sources(&subscriber);
|
||||
|
||||
let old_value =
|
||||
mem::take(&mut *value.write().or_poisoned());
|
||||
let new_value = owner.with_cleanup(|| {
|
||||
subscriber.with_observer(|| {
|
||||
run_in_effect_scope(|| fun.run(old_value))
|
||||
})
|
||||
});
|
||||
*value.write().or_poisoned() = Some(new_value);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
ArenaItem::new_with_storage(Some(inner))
|
||||
});
|
||||
|
||||
Self { inner }
|
||||
Self::new_isomorphic(fun)
|
||||
}
|
||||
|
||||
/// Creates a new effect, which runs once on the next “tick”, and then runs again when reactive values
|
||||
@@ -434,9 +406,10 @@ impl Effect<SyncStorage> {
|
||||
|
||||
async move {
|
||||
while rx.next().await.is_some() {
|
||||
if subscriber
|
||||
.with_observer(|| subscriber.update_if_necessary())
|
||||
|| first_run
|
||||
if !owner.paused()
|
||||
&& (subscriber
|
||||
.with_observer(|| subscriber.update_if_necessary())
|
||||
|| first_run)
|
||||
{
|
||||
first_run = false;
|
||||
subscriber.clear_sources(&subscriber);
|
||||
@@ -487,9 +460,10 @@ impl Effect<SyncStorage> {
|
||||
|
||||
async move {
|
||||
while rx.next().await.is_some() {
|
||||
if subscriber
|
||||
.with_observer(|| subscriber.update_if_necessary())
|
||||
|| first_run
|
||||
if !owner.paused()
|
||||
&& (subscriber.with_observer(|| {
|
||||
subscriber.update_if_necessary()
|
||||
}) || first_run)
|
||||
{
|
||||
subscriber.clear_sources(&subscriber);
|
||||
|
||||
|
||||
379
reactive_graph/src/effect/immediate.rs
Normal file
379
reactive_graph/src/effect/immediate.rs
Normal file
@@ -0,0 +1,379 @@
|
||||
use crate::{
|
||||
graph::{AnySubscriber, ReactiveNode, ToAnySubscriber},
|
||||
owner::on_cleanup,
|
||||
traits::{DefinedAt, Dispose},
|
||||
};
|
||||
use or_poisoned::OrPoisoned;
|
||||
use std::{
|
||||
panic::Location,
|
||||
sync::{Arc, Mutex, RwLock},
|
||||
};
|
||||
|
||||
/// Effects run a certain chunk of code whenever the signals they depend on change.
|
||||
///
|
||||
/// The effect runs on creation and again as soon as any tracked signal changes.
|
||||
///
|
||||
/// NOTE: you probably want use [`Effect`](super::Effect) instead.
|
||||
/// This is for the few cases where it's important to execute effects immediately and in order.
|
||||
///
|
||||
/// [ImmediateEffect]s stop running when dropped.
|
||||
///
|
||||
/// NOTE: since effects are executed immediately, they might recurse.
|
||||
/// Under recursion or parallelism only the last run to start is tracked.
|
||||
///
|
||||
/// ## Example
|
||||
///
|
||||
/// ```
|
||||
/// # use reactive_graph::computed::*;
|
||||
/// # use reactive_graph::signal::*; let owner = reactive_graph::owner::Owner::new(); owner.set();
|
||||
/// # use reactive_graph::prelude::*;
|
||||
/// # use reactive_graph::effect::ImmediateEffect;
|
||||
/// # use reactive_graph::owner::ArenaItem;
|
||||
/// # let owner = reactive_graph::owner::Owner::new(); owner.set();
|
||||
/// let a = RwSignal::new(0);
|
||||
/// let b = RwSignal::new(0);
|
||||
///
|
||||
/// // ✅ use effects to interact between reactive state and the outside world
|
||||
/// let _drop_guard = ImmediateEffect::new(move || {
|
||||
/// // on the next “tick” prints "Value: 0" and subscribes to `a`
|
||||
/// println!("Value: {}", a.get());
|
||||
/// });
|
||||
///
|
||||
/// // The effect runs immediately and subscribes to `a`, in the process it prints "Value: 0"
|
||||
/// # assert_eq!(a.get(), 0);
|
||||
/// a.set(1);
|
||||
/// # assert_eq!(a.get(), 1);
|
||||
/// // ✅ because it's subscribed to `a`, the effect reruns and prints "Value: 1"
|
||||
/// ```
|
||||
/// ## Notes
|
||||
///
|
||||
/// 1. **Scheduling**: Effects run immediately, as soon as any tracked signal changes.
|
||||
/// 2. By default, effects do not run unless the `effects` feature is enabled. If you are using
|
||||
/// this with a web framework, this generally means that effects **do not run on the server**.
|
||||
/// and you can call browser-specific APIs within the effect function without causing issues.
|
||||
/// If you need an effect to run on the server, use [`ImmediateEffect::new_isomorphic`].
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ImmediateEffect {
|
||||
inner: StoredEffect,
|
||||
}
|
||||
|
||||
type StoredEffect = Option<Arc<RwLock<inner::EffectInner>>>;
|
||||
|
||||
impl Dispose for ImmediateEffect {
|
||||
fn dispose(self) {}
|
||||
}
|
||||
|
||||
impl ImmediateEffect {
|
||||
/// Creates a new effect which runs immediately, then again as soon as any tracked signal changes.
|
||||
///
|
||||
/// NOTE: this requires a `Fn` function because it might recurse.
|
||||
/// Use [Self::new_mut] to pass a `FnMut` function, it'll panic on recursion.
|
||||
#[track_caller]
|
||||
#[must_use]
|
||||
pub fn new(fun: impl Fn() + Send + Sync + 'static) -> Self {
|
||||
if !cfg!(feature = "effects") {
|
||||
return Self { inner: None };
|
||||
}
|
||||
|
||||
let inner = inner::EffectInner::new(fun);
|
||||
|
||||
inner.update_if_necessary();
|
||||
|
||||
Self { inner: Some(inner) }
|
||||
}
|
||||
/// Creates a new effect which runs immediately, then again as soon as any tracked signal changes.
|
||||
///
|
||||
/// # Panics
|
||||
/// Panics on recursion or if triggered in parallel. Also see [Self::new]
|
||||
#[track_caller]
|
||||
#[must_use]
|
||||
pub fn new_mut(fun: impl FnMut() + Send + Sync + 'static) -> Self {
|
||||
const MSG: &str = "The effect recursed or its function panicked.";
|
||||
let fun = Mutex::new(fun);
|
||||
Self::new(move || fun.try_lock().expect(MSG)())
|
||||
}
|
||||
/// Creates a new effect which runs immediately, then again as soon as any tracked signal changes.
|
||||
///
|
||||
/// NOTE: this requires a `Fn` function because it might recurse.
|
||||
/// NOTE: this effect is automatically cleaned up when the current owner is cleared or disposed.
|
||||
#[track_caller]
|
||||
pub fn new_scoped(fun: impl Fn() + Send + Sync + 'static) {
|
||||
let effect = Self::new(fun);
|
||||
|
||||
on_cleanup(move || effect.dispose());
|
||||
}
|
||||
|
||||
/// Creates a new effect which runs immediately, then again as soon as any tracked signal changes.
|
||||
///
|
||||
/// This will run whether the `effects` feature is enabled or not.
|
||||
#[track_caller]
|
||||
#[must_use]
|
||||
pub fn new_isomorphic(fun: impl Fn() + Send + Sync + 'static) -> Self {
|
||||
let inner = inner::EffectInner::new(fun);
|
||||
|
||||
inner.update_if_necessary();
|
||||
|
||||
Self { inner: Some(inner) }
|
||||
}
|
||||
}
|
||||
|
||||
impl ToAnySubscriber for ImmediateEffect {
|
||||
fn to_any_subscriber(&self) -> AnySubscriber {
|
||||
const MSG: &str = "tried to set effect that has been stopped";
|
||||
self.inner.as_ref().expect(MSG).to_any_subscriber()
|
||||
}
|
||||
}
|
||||
|
||||
impl DefinedAt for ImmediateEffect {
|
||||
fn defined_at(&self) -> Option<&'static Location<'static>> {
|
||||
self.inner.as_ref()?.read().or_poisoned().defined_at()
|
||||
}
|
||||
}
|
||||
|
||||
mod inner {
|
||||
use crate::{
|
||||
graph::{
|
||||
AnySource, AnySubscriber, ReactiveNode, ReactiveNodeState,
|
||||
SourceSet, Subscriber, ToAnySubscriber, WithObserver,
|
||||
},
|
||||
log_warning,
|
||||
owner::Owner,
|
||||
traits::DefinedAt,
|
||||
};
|
||||
use or_poisoned::OrPoisoned;
|
||||
use std::{
|
||||
panic::Location,
|
||||
sync::{Arc, RwLock, Weak},
|
||||
thread::{self, ThreadId},
|
||||
};
|
||||
|
||||
/// Handles subscription logic for effects.
|
||||
///
|
||||
/// To handle parallelism and recursion we assign ordered (1..) ids to each run.
|
||||
/// We only keep the sources tracked by the run with the highest id (the last one).
|
||||
///
|
||||
/// We do this by:
|
||||
/// - Clearing the sources before every run, so the last one clears anything before it.
|
||||
/// - We stop tracking sources after the last run has completed.
|
||||
/// (A parent run will start before and end after a recursive child run.)
|
||||
/// - To handle parallelism with the last run, we only allow sources to be added by its thread.
|
||||
pub(super) struct EffectInner {
|
||||
#[cfg(any(debug_assertions, leptos_debuginfo))]
|
||||
defined_at: &'static Location<'static>,
|
||||
owner: Owner,
|
||||
state: ReactiveNodeState,
|
||||
/// The number of effect runs in this 'batch'.
|
||||
/// Cleared when no runs are *ongoing* anymore.
|
||||
/// Used to assign ordered ids to each run, and to know when we can clear these values.
|
||||
run_count_start: usize,
|
||||
/// The number of effect runs that have completed in the current 'batch'.
|
||||
/// Cleared when no runs are *ongoing* anymore.
|
||||
/// Used to know when we can clear these values.
|
||||
run_done_count: usize,
|
||||
/// Given ordered ids (1..), the run with the highest id that has completed in this 'batch'.
|
||||
/// Cleared when no runs are *ongoing* anymore.
|
||||
/// Used to know whether the current run is the latest one.
|
||||
run_done_max: usize,
|
||||
/// The [ThreadId] of the run with the highest id.
|
||||
/// Used to prevent over-subscribing during parallel execution with the last run.
|
||||
///
|
||||
/// ```text
|
||||
/// Thread 1:
|
||||
/// -------------------------
|
||||
/// --- --- =======
|
||||
///
|
||||
/// Thread 2:
|
||||
/// -------------------------
|
||||
/// -----------
|
||||
/// ```
|
||||
///
|
||||
/// In the parallel example above, we can see why we need this.
|
||||
/// The last run is marked using `=`, but another run in the other thread might
|
||||
/// also be gathering sources. So we only allow the run from the correct [ThreadId] to push sources.
|
||||
last_run_thread_id: ThreadId,
|
||||
fun: Arc<dyn Fn() + Send + Sync>,
|
||||
sources: SourceSet,
|
||||
any_subscriber: AnySubscriber,
|
||||
}
|
||||
|
||||
impl EffectInner {
|
||||
#[track_caller]
|
||||
pub fn new(
|
||||
fun: impl Fn() + Send + Sync + 'static,
|
||||
) -> Arc<RwLock<EffectInner>> {
|
||||
let owner = Owner::new();
|
||||
|
||||
Arc::new_cyclic(|weak| {
|
||||
let any_subscriber = AnySubscriber(
|
||||
weak.as_ptr() as usize,
|
||||
Weak::clone(weak) as Weak<dyn Subscriber + Send + Sync>,
|
||||
);
|
||||
|
||||
RwLock::new(EffectInner {
|
||||
#[cfg(any(debug_assertions, leptos_debuginfo))]
|
||||
defined_at: Location::caller(),
|
||||
owner,
|
||||
state: ReactiveNodeState::Dirty,
|
||||
run_count_start: 0,
|
||||
run_done_count: 0,
|
||||
run_done_max: 0,
|
||||
last_run_thread_id: thread::current().id(),
|
||||
fun: Arc::new(fun),
|
||||
sources: SourceSet::new(),
|
||||
any_subscriber,
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl ToAnySubscriber for Arc<RwLock<EffectInner>> {
|
||||
fn to_any_subscriber(&self) -> AnySubscriber {
|
||||
AnySubscriber(
|
||||
Arc::as_ptr(self) as usize,
|
||||
Arc::downgrade(self) as Weak<dyn Subscriber + Send + Sync>,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl ReactiveNode for RwLock<EffectInner> {
|
||||
fn mark_subscribers_check(&self) {}
|
||||
|
||||
fn update_if_necessary(&self) -> bool {
|
||||
let state = {
|
||||
let guard = self.read().or_poisoned();
|
||||
|
||||
if guard.owner.paused() {
|
||||
return false;
|
||||
}
|
||||
|
||||
guard.state
|
||||
};
|
||||
|
||||
let needs_update = match state {
|
||||
ReactiveNodeState::Clean => false,
|
||||
ReactiveNodeState::Check => {
|
||||
let sources = self.read().or_poisoned().sources.clone();
|
||||
sources
|
||||
.into_iter()
|
||||
.any(|source| source.update_if_necessary())
|
||||
}
|
||||
ReactiveNodeState::Dirty => true,
|
||||
};
|
||||
|
||||
if needs_update {
|
||||
let mut guard = self.write().or_poisoned();
|
||||
|
||||
let owner = guard.owner.clone();
|
||||
let any_subscriber = guard.any_subscriber.clone();
|
||||
let fun = guard.fun.clone();
|
||||
|
||||
// New run has started.
|
||||
guard.run_count_start += 1;
|
||||
// We get a value for this run, the highest value will be what we keep the sources from.
|
||||
let recursion_count = guard.run_count_start;
|
||||
// We clear the sources before running the effect.
|
||||
// Note that this is tied to the ordering of the initial write lock acquisition
|
||||
// to ensure the last run is also the last to clear them.
|
||||
guard.sources.clear_sources(&any_subscriber);
|
||||
// Only this thread will be able to subscribe.
|
||||
guard.last_run_thread_id = thread::current().id();
|
||||
|
||||
if recursion_count > 2 {
|
||||
warn_excessive_recursion(&guard);
|
||||
}
|
||||
|
||||
drop(guard);
|
||||
|
||||
// We execute the effect.
|
||||
// Note that *this could happen in parallel across threads*.
|
||||
owner.with_cleanup(|| any_subscriber.with_observer(|| fun()));
|
||||
|
||||
let mut guard = self.write().or_poisoned();
|
||||
|
||||
// This run has completed.
|
||||
guard.run_done_count += 1;
|
||||
|
||||
// We update the done count.
|
||||
// Sources will only be added if recursion_done_max < recursion_count_start.
|
||||
// (Meaning the last run is not done yet.)
|
||||
guard.run_done_max =
|
||||
Ord::max(recursion_count, guard.run_done_max);
|
||||
|
||||
// The same amount of runs has started and completed,
|
||||
// so we can clear everything up for next time.
|
||||
if guard.run_count_start == guard.run_done_count {
|
||||
guard.run_count_start = 0;
|
||||
guard.run_done_count = 0;
|
||||
guard.run_done_max = 0;
|
||||
// Can be left unchanged, it'll be set again next time.
|
||||
// guard.last_run_thread_id = thread::current().id();
|
||||
}
|
||||
|
||||
guard.state = ReactiveNodeState::Clean;
|
||||
}
|
||||
|
||||
needs_update
|
||||
}
|
||||
|
||||
fn mark_check(&self) {
|
||||
self.write().or_poisoned().state = ReactiveNodeState::Check;
|
||||
self.update_if_necessary();
|
||||
}
|
||||
|
||||
fn mark_dirty(&self) {
|
||||
self.write().or_poisoned().state = ReactiveNodeState::Dirty;
|
||||
self.update_if_necessary();
|
||||
}
|
||||
}
|
||||
|
||||
impl Subscriber for RwLock<EffectInner> {
|
||||
fn add_source(&self, source: AnySource) {
|
||||
let mut guard = self.write().or_poisoned();
|
||||
if guard.run_done_max < guard.run_count_start
|
||||
&& guard.last_run_thread_id == thread::current().id()
|
||||
{
|
||||
guard.sources.insert(source);
|
||||
}
|
||||
}
|
||||
|
||||
fn clear_sources(&self, subscriber: &AnySubscriber) {
|
||||
self.write().or_poisoned().sources.clear_sources(subscriber);
|
||||
}
|
||||
}
|
||||
|
||||
impl DefinedAt for EffectInner {
|
||||
fn defined_at(&self) -> Option<&'static Location<'static>> {
|
||||
#[cfg(any(debug_assertions, leptos_debuginfo))]
|
||||
{
|
||||
Some(self.defined_at)
|
||||
}
|
||||
#[cfg(not(any(debug_assertions, leptos_debuginfo)))]
|
||||
{
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for EffectInner {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("EffectInner")
|
||||
.field("owner", &self.owner)
|
||||
.field("state", &self.state)
|
||||
.field("sources", &self.sources)
|
||||
.field("any_subscriber", &self.any_subscriber)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
fn warn_excessive_recursion(effect: &EffectInner) {
|
||||
const MSG: &str = "ImmediateEffect recursed more than once.";
|
||||
match effect.defined_at() {
|
||||
Some(defined_at) => {
|
||||
log_warning(format_args!("{MSG} Defined at: {}", defined_at));
|
||||
}
|
||||
None => {
|
||||
log_warning(format_args!("{MSG}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -30,21 +30,19 @@ impl ReactiveNode for RwLock<EffectInner> {
|
||||
|
||||
fn update_if_necessary(&self) -> bool {
|
||||
let mut guard = self.write().or_poisoned();
|
||||
let (is_dirty, sources) =
|
||||
(guard.dirty, (!guard.dirty).then(|| guard.sources.clone()));
|
||||
|
||||
if is_dirty {
|
||||
if guard.dirty {
|
||||
guard.dirty = false;
|
||||
return true;
|
||||
}
|
||||
|
||||
let sources = guard.sources.clone();
|
||||
|
||||
drop(guard);
|
||||
for source in sources.into_iter().flatten() {
|
||||
if source.update_if_necessary() {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
|
||||
sources
|
||||
.into_iter()
|
||||
.any(|source| source.update_if_necessary())
|
||||
}
|
||||
|
||||
fn mark_check(&self) {
|
||||
|
||||
@@ -91,9 +91,11 @@ where
|
||||
|
||||
async move {
|
||||
while rx.next().await.is_some() {
|
||||
if subscriber.with_observer(|| {
|
||||
subscriber.update_if_necessary()
|
||||
}) {
|
||||
if !owner.paused()
|
||||
&& subscriber.with_observer(|| {
|
||||
subscriber.update_if_necessary()
|
||||
})
|
||||
{
|
||||
subscriber.clear_sources(&subscriber);
|
||||
|
||||
let old_value = mem::take(
|
||||
@@ -159,8 +161,10 @@ where
|
||||
|
||||
async move {
|
||||
while rx.next().await.is_some() {
|
||||
if subscriber
|
||||
.with_observer(|| subscriber.update_if_necessary())
|
||||
if !owner.paused()
|
||||
&& subscriber.with_observer(|| {
|
||||
subscriber.update_if_necessary()
|
||||
})
|
||||
{
|
||||
subscriber.clear_sources(&subscriber);
|
||||
|
||||
|
||||
@@ -135,6 +135,13 @@ pub fn untrack<T>(fun: impl FnOnce() -> T) -> T {
|
||||
fun()
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
#[track_caller]
|
||||
pub fn untrack_with_diagnostics<T>(fun: impl FnOnce() -> T) -> T {
|
||||
let _prev = Observer::take();
|
||||
fun()
|
||||
}
|
||||
|
||||
/// Converts a [`Subscriber`] to a type-erased [`AnySubscriber`].
|
||||
pub trait ToAnySubscriber {
|
||||
/// Converts this type to its type-erased equivalent.
|
||||
|
||||
@@ -48,10 +48,10 @@
|
||||
//!
|
||||
//! ## Design Principles and Assumptions
|
||||
//! - **Effects are expensive.** The library is built on the assumption that the side effects
|
||||
//! (making a network request, rendering something to the DOM, writing to disk) are orders of
|
||||
//! magnitude more expensive than propagating signal updates. As a result, the algorithm is
|
||||
//! designed to avoid re-running side effects unnecessarily, and is willing to sacrifice a small
|
||||
//! amount of raw update speed to that goal.
|
||||
//! (making a network request, rendering something to the DOM, writing to disk) are orders of
|
||||
//! magnitude more expensive than propagating signal updates. As a result, the algorithm is
|
||||
//! designed to avoid re-running side effects unnecessarily, and is willing to sacrifice a small
|
||||
//! amount of raw update speed to that goal.
|
||||
//! - **Automatic dependency tracking.** Dependencies are not specified as a compile-time list, but
|
||||
//! tracked at runtime. This in turn enables **dynamic dependency tracking**: subscribers
|
||||
//! unsubscribe from their sources between runs, which means that a subscriber that contains a
|
||||
|
||||
@@ -60,6 +60,38 @@ pub struct Owner {
|
||||
pub(crate) shared_context: Option<Arc<dyn SharedContext + Send + Sync>>,
|
||||
}
|
||||
|
||||
impl Owner {
|
||||
fn downgrade(&self) -> WeakOwner {
|
||||
WeakOwner {
|
||||
inner: Arc::downgrade(&self.inner),
|
||||
#[cfg(feature = "hydration")]
|
||||
shared_context: self.shared_context.as_ref().map(Arc::downgrade),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct WeakOwner {
|
||||
inner: Weak<RwLock<OwnerInner>>,
|
||||
#[cfg(feature = "hydration")]
|
||||
shared_context: Option<Weak<dyn SharedContext + Send + Sync>>,
|
||||
}
|
||||
|
||||
impl WeakOwner {
|
||||
fn upgrade(&self) -> Option<Owner> {
|
||||
self.inner.upgrade().map(|inner| {
|
||||
#[cfg(feature = "hydration")]
|
||||
let shared_context =
|
||||
self.shared_context.as_ref().and_then(|sc| sc.upgrade());
|
||||
Owner {
|
||||
inner,
|
||||
#[cfg(feature = "hydration")]
|
||||
shared_context,
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for Owner {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
Arc::ptr_eq(&self.inner, &other.inner)
|
||||
@@ -67,7 +99,7 @@ impl PartialEq for Owner {
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static OWNER: RefCell<Option<Owner>> = Default::default();
|
||||
static OWNER: RefCell<Option<WeakOwner>> = Default::default();
|
||||
}
|
||||
|
||||
impl Owner {
|
||||
@@ -107,12 +139,16 @@ impl Owner {
|
||||
/// Creates a new `Owner` and registers it as a child of the current `Owner`, if there is one.
|
||||
pub fn new() -> Self {
|
||||
#[cfg(not(feature = "hydration"))]
|
||||
let parent = OWNER
|
||||
.with(|o| o.borrow().as_ref().map(|o| Arc::downgrade(&o.inner)));
|
||||
let parent = OWNER.with(|o| {
|
||||
o.borrow()
|
||||
.as_ref()
|
||||
.and_then(|o| o.upgrade())
|
||||
.map(|o| Arc::downgrade(&o.inner))
|
||||
});
|
||||
#[cfg(feature = "hydration")]
|
||||
let (parent, shared_context) = OWNER
|
||||
.with(|o| {
|
||||
o.borrow().as_ref().map(|o| {
|
||||
o.borrow().as_ref().and_then(|o| o.upgrade()).map(|o| {
|
||||
(Some(Arc::downgrade(&o.inner)), o.shared_context.clone())
|
||||
})
|
||||
})
|
||||
@@ -130,6 +166,7 @@ impl Owner {
|
||||
.and_then(|parent| parent.upgrade())
|
||||
.map(|parent| parent.read().or_poisoned().arena.clone())
|
||||
.unwrap_or_default(),
|
||||
paused: false,
|
||||
})),
|
||||
#[cfg(feature = "hydration")]
|
||||
shared_context,
|
||||
@@ -163,6 +200,7 @@ impl Owner {
|
||||
children: Default::default(),
|
||||
#[cfg(feature = "sandboxed-arenas")]
|
||||
arena: Default::default(),
|
||||
paused: false,
|
||||
})),
|
||||
#[cfg(feature = "hydration")]
|
||||
shared_context,
|
||||
@@ -174,8 +212,10 @@ impl Owner {
|
||||
/// Creates a new `Owner` that is the child of the current `Owner`, if any.
|
||||
pub fn child(&self) -> Self {
|
||||
let parent = Some(Arc::downgrade(&self.inner));
|
||||
let mut inner = self.inner.write().or_poisoned();
|
||||
#[cfg(feature = "sandboxed-arenas")]
|
||||
let arena = self.inner.read().or_poisoned().arena.clone();
|
||||
let arena = inner.arena.clone();
|
||||
let paused = inner.paused;
|
||||
let child = Self {
|
||||
inner: Arc::new(RwLock::new(OwnerInner {
|
||||
parent,
|
||||
@@ -185,21 +225,18 @@ impl Owner {
|
||||
children: Default::default(),
|
||||
#[cfg(feature = "sandboxed-arenas")]
|
||||
arena,
|
||||
paused,
|
||||
})),
|
||||
#[cfg(feature = "hydration")]
|
||||
shared_context: self.shared_context.clone(),
|
||||
};
|
||||
self.inner
|
||||
.write()
|
||||
.or_poisoned()
|
||||
.children
|
||||
.push(Arc::downgrade(&child.inner));
|
||||
inner.children.push(Arc::downgrade(&child.inner));
|
||||
child
|
||||
}
|
||||
|
||||
/// Sets this as the current `Owner`.
|
||||
pub fn set(&self) {
|
||||
OWNER.with_borrow_mut(|owner| *owner = Some(self.clone()));
|
||||
OWNER.with_borrow_mut(|owner| *owner = Some(self.downgrade()));
|
||||
#[cfg(feature = "sandboxed-arenas")]
|
||||
Arena::set(&self.inner.read().or_poisoned().arena);
|
||||
}
|
||||
@@ -208,7 +245,7 @@ impl Owner {
|
||||
pub fn with<T>(&self, fun: impl FnOnce() -> T) -> T {
|
||||
let prev = {
|
||||
OWNER.with(|o| {
|
||||
mem::replace(&mut *o.borrow_mut(), Some(self.clone()))
|
||||
Option::replace(&mut *o.borrow_mut(), self.downgrade())
|
||||
})
|
||||
};
|
||||
#[cfg(feature = "sandboxed-arenas")]
|
||||
@@ -256,7 +293,7 @@ impl Owner {
|
||||
|
||||
/// Returns the current `Owner`, if any.
|
||||
pub fn current() -> Option<Owner> {
|
||||
OWNER.with(|o| o.borrow().clone())
|
||||
OWNER.with(|o| o.borrow().as_ref().and_then(|n| n.upgrade()))
|
||||
}
|
||||
|
||||
/// Returns the [`SharedContext`] associated with this owner, if any.
|
||||
@@ -270,7 +307,7 @@ impl Owner {
|
||||
/// Removes this from its state as the thread-local owner and drops it.
|
||||
pub fn unset(self) {
|
||||
OWNER.with_borrow_mut(|owner| {
|
||||
if owner.as_ref() == Some(&self) {
|
||||
if owner.as_ref().and_then(|n| n.upgrade()) == Some(self) {
|
||||
mem::take(owner);
|
||||
}
|
||||
})
|
||||
@@ -283,6 +320,7 @@ impl Owner {
|
||||
OWNER.with(|o| {
|
||||
o.borrow()
|
||||
.as_ref()
|
||||
.and_then(|o| o.upgrade())
|
||||
.and_then(|current| current.shared_context.clone())
|
||||
})
|
||||
}
|
||||
@@ -296,6 +334,7 @@ impl Owner {
|
||||
|
||||
let sc = OWNER.with_borrow(|o| {
|
||||
o.as_ref()
|
||||
.and_then(|o| o.upgrade())
|
||||
.and_then(|current| current.shared_context.clone())
|
||||
});
|
||||
match sc {
|
||||
@@ -321,6 +360,7 @@ impl Owner {
|
||||
|
||||
let sc = OWNER.with_borrow(|o| {
|
||||
o.as_ref()
|
||||
.and_then(|o| o.upgrade())
|
||||
.and_then(|current| current.shared_context.clone())
|
||||
});
|
||||
match sc {
|
||||
@@ -337,6 +377,47 @@ impl Owner {
|
||||
|
||||
inner(Box::new(fun))
|
||||
}
|
||||
|
||||
/// Pauses the execution of side effects for this owner, and any of its descendants.
|
||||
///
|
||||
/// If this owner is the owner for an [`Effect`](crate::effect::Effect) or [`RenderEffect`](crate::effect::RenderEffect), this effect will not run until [`Owner::resume`] is called. All children of this effects are also paused.
|
||||
///
|
||||
/// Any notifications will be ignored; effects that are notified will paused will not run when
|
||||
/// resumed, until they are notified again by a source after being resumed.
|
||||
pub fn pause(&self) {
|
||||
let mut stack = Vec::with_capacity(16);
|
||||
stack.push(Arc::downgrade(&self.inner));
|
||||
while let Some(curr) = stack.pop() {
|
||||
if let Some(curr) = curr.upgrade() {
|
||||
let mut curr = curr.write().or_poisoned();
|
||||
curr.paused = true;
|
||||
stack.extend(curr.children.iter().map(Weak::clone));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether this owner has been paused by [`Owner::pause`].
|
||||
pub fn paused(&self) -> bool {
|
||||
self.inner.read().or_poisoned().paused
|
||||
}
|
||||
|
||||
/// Resumes side effects that have been paused by [`Owner::pause`].
|
||||
///
|
||||
/// All children will also be resumed.
|
||||
///
|
||||
/// This will *not* cause side effects that were notified while paused to run, until they are
|
||||
/// notified again by a source after being resumed.
|
||||
pub fn resume(&self) {
|
||||
let mut stack = Vec::with_capacity(16);
|
||||
stack.push(Arc::downgrade(&self.inner));
|
||||
while let Some(curr) = stack.pop() {
|
||||
if let Some(curr) = curr.upgrade() {
|
||||
let mut curr = curr.write().or_poisoned();
|
||||
curr.paused = false;
|
||||
stack.extend(curr.children.iter().map(Weak::clone));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
@@ -363,6 +444,7 @@ pub(crate) struct OwnerInner {
|
||||
pub children: Vec<Weak<RwLock<OwnerInner>>>,
|
||||
#[cfg(feature = "sandboxed-arenas")]
|
||||
arena: Arc<RwLock<ArenaMap>>,
|
||||
paused: bool,
|
||||
}
|
||||
|
||||
impl Debug for OwnerInner {
|
||||
|
||||
@@ -48,20 +48,30 @@ impl Arena {
|
||||
fun(&MAP.get_or_init(Default::default).read().or_poisoned())
|
||||
}
|
||||
#[cfg(feature = "sandboxed-arenas")]
|
||||
{
|
||||
Arena::try_with(fun).unwrap_or_else(|| {
|
||||
panic!(
|
||||
"at {}, the `sandboxed-arenas` feature is active, but no \
|
||||
Arena is active",
|
||||
std::panic::Location::caller()
|
||||
)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[track_caller]
|
||||
pub fn try_with<U>(fun: impl FnOnce(&ArenaMap) -> U) -> Option<U> {
|
||||
#[cfg(not(feature = "sandboxed-arenas"))]
|
||||
{
|
||||
Some(fun(&MAP.get_or_init(Default::default).read().or_poisoned()))
|
||||
}
|
||||
#[cfg(feature = "sandboxed-arenas")]
|
||||
{
|
||||
MAP.with_borrow(|arena| {
|
||||
fun(&arena
|
||||
arena
|
||||
.as_ref()
|
||||
.and_then(Weak::upgrade)
|
||||
.unwrap_or_else(|| {
|
||||
panic!(
|
||||
"at {}, the `sandboxed-arenas` feature is active, \
|
||||
but no Arena is active",
|
||||
std::panic::Location::caller()
|
||||
)
|
||||
})
|
||||
.read()
|
||||
.or_poisoned())
|
||||
.map(|n| fun(&n.read().or_poisoned()))
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -74,20 +84,32 @@ impl Arena {
|
||||
}
|
||||
#[cfg(feature = "sandboxed-arenas")]
|
||||
{
|
||||
let caller = std::panic::Location::caller();
|
||||
Arena::try_with_mut(fun).unwrap_or_else(|| {
|
||||
panic!(
|
||||
"at {}, the `sandboxed-arenas` feature is active, but no \
|
||||
Arena is active",
|
||||
std::panic::Location::caller()
|
||||
)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[track_caller]
|
||||
pub fn try_with_mut<U>(fun: impl FnOnce(&mut ArenaMap) -> U) -> Option<U> {
|
||||
#[cfg(not(feature = "sandboxed-arenas"))]
|
||||
{
|
||||
Some(fun(&mut MAP
|
||||
.get_or_init(Default::default)
|
||||
.write()
|
||||
.or_poisoned()))
|
||||
}
|
||||
#[cfg(feature = "sandboxed-arenas")]
|
||||
{
|
||||
MAP.with_borrow(|arena| {
|
||||
fun(&mut arena
|
||||
arena
|
||||
.as_ref()
|
||||
.and_then(Weak::upgrade)
|
||||
.unwrap_or_else(|| {
|
||||
panic!(
|
||||
"at {}, the `sandboxed-arenas` feature is active, \
|
||||
but no Arena is active",
|
||||
caller
|
||||
)
|
||||
})
|
||||
.write()
|
||||
.or_poisoned())
|
||||
.map(|n| fun(&mut n.write().or_poisoned()))
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -126,6 +148,7 @@ pub mod sandboxed {
|
||||
/// called.
|
||||
///
|
||||
/// [item]:[crate::owner::ArenaItem]
|
||||
#[track_caller]
|
||||
pub fn new(inner: T) -> Self {
|
||||
let arena = MAP.with_borrow(|n| n.as_ref().and_then(Weak::upgrade));
|
||||
Self { arena, inner }
|
||||
|
||||
@@ -53,7 +53,7 @@ where
|
||||
})
|
||||
};
|
||||
OWNER.with(|o| {
|
||||
if let Some(owner) = &*o.borrow() {
|
||||
if let Some(owner) = o.borrow().as_ref().and_then(|o| o.upgrade()) {
|
||||
owner.register(node);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -76,24 +76,26 @@ where
|
||||
}
|
||||
|
||||
fn try_with<U>(node: NodeId, fun: impl FnOnce(&T) -> U) -> Option<U> {
|
||||
Arena::with(|arena| {
|
||||
Arena::try_with(|arena| {
|
||||
let m = arena.get(node);
|
||||
m.and_then(|n| n.downcast_ref::<T>()).map(fun)
|
||||
})
|
||||
.flatten()
|
||||
}
|
||||
|
||||
fn try_with_mut<U>(
|
||||
node: NodeId,
|
||||
fun: impl FnOnce(&mut T) -> U,
|
||||
) -> Option<U> {
|
||||
Arena::with_mut(|arena| {
|
||||
Arena::try_with_mut(|arena| {
|
||||
let m = arena.get_mut(node);
|
||||
m.and_then(|n| n.downcast_mut::<T>()).map(fun)
|
||||
})
|
||||
.flatten()
|
||||
}
|
||||
|
||||
fn try_set(node: NodeId, value: T) -> Option<T> {
|
||||
Arena::with_mut(|arena| {
|
||||
Arena::try_with_mut(|arena| {
|
||||
let m = arena.get_mut(node);
|
||||
match m.and_then(|n| n.downcast_mut::<T>()) {
|
||||
Some(inner) => {
|
||||
@@ -103,6 +105,7 @@ where
|
||||
None => Some(value),
|
||||
}
|
||||
})
|
||||
.flatten()
|
||||
}
|
||||
|
||||
fn take(node: NodeId) -> Option<T> {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::subscriber_traits::AsSubscriberSet;
|
||||
use crate::{
|
||||
graph::{ReactiveNode, SubscriberSet},
|
||||
traits::{DefinedAt, IsDisposed, Notify},
|
||||
traits::{DefinedAt, IsDisposed, Notify, Track},
|
||||
};
|
||||
use std::{
|
||||
fmt::{Debug, Formatter, Result},
|
||||
@@ -69,6 +69,22 @@ impl AsSubscriberSet for ArcTrigger {
|
||||
}
|
||||
}
|
||||
|
||||
impl Notify for Vec<ArcTrigger> {
|
||||
fn notify(&self) {
|
||||
for trigger in self {
|
||||
trigger.notify();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Track for Vec<ArcTrigger> {
|
||||
fn track(&self) {
|
||||
for trigger in self {
|
||||
trigger.track();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl DefinedAt for ArcTrigger {
|
||||
#[inline(always)]
|
||||
fn defined_at(&self) -> Option<&'static Location<'static>> {
|
||||
|
||||
@@ -55,7 +55,7 @@ impl<T: AsSubscriberSet + DefinedAt> ReactiveNode for T {
|
||||
|
||||
fn mark_subscribers_check(&self) {
|
||||
if let Some(inner) = self.as_subscriber_set() {
|
||||
let subs = inner.borrow().write().unwrap().take();
|
||||
let subs = inner.borrow().read().unwrap().clone();
|
||||
for sub in subs {
|
||||
sub.mark_dirty();
|
||||
}
|
||||
|
||||
@@ -37,9 +37,9 @@ impl AsyncTransition {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
let global_transition = global_transition();
|
||||
let inner = TransitionInner { tx };
|
||||
let prev = std::mem::replace(
|
||||
let prev = Option::replace(
|
||||
&mut *global_transition.write().or_poisoned(),
|
||||
Some(inner.clone()),
|
||||
inner.clone(),
|
||||
);
|
||||
let value = action().await;
|
||||
_ = std::mem::replace(
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
/// Types that abstract over signals with values that can be read.
|
||||
pub mod read {
|
||||
use crate::{
|
||||
computed::{ArcMemo, Memo, MemoInner},
|
||||
computed::{ArcMemo, Memo},
|
||||
graph::untrack,
|
||||
owner::{
|
||||
ArcStoredValue, ArenaItem, FromLocal, LocalStorage, Storage,
|
||||
@@ -1735,22 +1735,40 @@ pub mod read {
|
||||
}
|
||||
|
||||
/// The content of a [`Signal`] wrapper read guard, variable depending on the signal type.
|
||||
#[derive(Debug)]
|
||||
pub enum SignalReadGuard<T: 'static, S: Storage<T>> {
|
||||
/// A read signal guard.
|
||||
Read(ReadGuard<T, Plain<T>>),
|
||||
#[allow(clippy::type_complexity)]
|
||||
/// A memo guard.
|
||||
Memo(ReadGuard<T, Mapped<Plain<MemoInner<T, S>>, T>>),
|
||||
Memo(
|
||||
ReadGuard<T, Mapped<Plain<Option<<S as Storage<T>>::Wrapped>>, T>>,
|
||||
),
|
||||
/// A fake guard for derived signals, the content had to actually be cloned, so it's not a guard but we pretend it is.
|
||||
Owned(T),
|
||||
}
|
||||
|
||||
impl<T: 'static + std::fmt::Debug, S: Storage<T> + std::fmt::Debug>
|
||||
std::fmt::Debug for SignalReadGuard<T, S>
|
||||
where
|
||||
<S as Storage<T>>::Wrapped: std::fmt::Debug,
|
||||
{
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::Read(arg0) => f.debug_tuple("Read").field(arg0).finish(),
|
||||
Self::Memo(arg0) => f.debug_tuple("Memo").field(arg0).finish(),
|
||||
Self::Owned(arg0) => {
|
||||
f.debug_tuple("Owned").field(arg0).finish()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S> Clone for SignalReadGuard<T, S>
|
||||
where
|
||||
S: Storage<T>,
|
||||
T: Clone,
|
||||
Plain<T>: Clone,
|
||||
Mapped<Plain<MemoInner<T, S>>, T>: Clone,
|
||||
Mapped<Plain<Option<<S as Storage<T>>::Wrapped>>, T>: Clone,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
match self {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user