mirror of
https://github.com/leptos-rs/leptos.git
synced 2025-12-27 09:54:41 -05:00
Merge remote-tracking branch 'origin' into leptos_0.8
This commit is contained in:
4
.github/workflows/ci-semver.yml
vendored
4
.github/workflows/ci-semver.yml
vendored
@@ -18,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-02-19)
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Install Glib
|
||||
@@ -30,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-02-19
|
||||
|
||||
2
.github/workflows/ci.yml
vendored
2
.github/workflows/ci.yml
vendored
@@ -26,4 +26,4 @@ jobs:
|
||||
with:
|
||||
directory: ${{ matrix.directory }}
|
||||
cargo_make_task: "ci"
|
||||
toolchain: nightly-2024-08-01
|
||||
toolchain: nightly-2025-02-19
|
||||
|
||||
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:
|
||||
|
||||
553
Cargo.lock
generated
553
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
13
Cargo.toml
13
Cargo.toml
@@ -48,8 +48,9 @@ rust-version = "1.76"
|
||||
throw_error = { path = "./any_error/", version = "0.3.0" }
|
||||
any_spawner = { path = "./any_spawner/", version = "0.2.0" }
|
||||
const_str_slice_concat = { path = "./const_str_slice_concat", version = "0.1" }
|
||||
either_of = { path = "./either_of/", version = "0.1.0" }
|
||||
either_of = { path = "./either_of/", version = "0.1.5" }
|
||||
hydration_context = { path = "./hydration_context", version = "0.2.0" }
|
||||
itertools = "0.14.0"
|
||||
leptos = { path = "./leptos", version = "0.8.0-alpha" }
|
||||
leptos_config = { path = "./leptos_config", version = "0.8.0-alpha" }
|
||||
leptos_dom = { path = "./leptos_dom", version = "0.8.0-alpha" }
|
||||
@@ -63,13 +64,15 @@ leptos_meta = { path = "./meta", version = "0.8.0-alpha" }
|
||||
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.4" }
|
||||
reactive_stores = { path = "./reactive_stores", version = "0.1.3" }
|
||||
reactive_stores_macro = { path = "./reactive_stores_macro", 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.8.0-alpha" }
|
||||
server_fn_macro = { path = "./server_fn_macro", version = "0.8.0-alpha" }
|
||||
server_fn_macro_default = { path = "./server_fn/server_fn_macro_default", version = "0.8.0-alpha" }
|
||||
tachys = { path = "./tachys", version = "0.1.4" }
|
||||
tachys = { path = "./tachys", version = "0.1.7" }
|
||||
wasm-bindgen = { version = "0.2.100" }
|
||||
|
||||
[profile.release]
|
||||
codegen-units = 1
|
||||
|
||||
@@ -21,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
|
||||
@@ -46,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);
|
||||
|
||||
@@ -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.4"
|
||||
version = "0.1.5"
|
||||
authors = ["Greg Johnston"]
|
||||
license = "MIT"
|
||||
readme = "../README.md"
|
||||
@@ -15,4 +15,4 @@ paste = "1.0.15"
|
||||
|
||||
[features]
|
||||
default = ["no_std"]
|
||||
no_std = []
|
||||
no_std = []
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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
|
||||
@@ -432,7 +430,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;
|
||||
@@ -443,7 +441,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();
|
||||
@@ -463,7 +460,6 @@ pub fn handle_server_fns_with_context(
|
||||
/// .run()
|
||||
/// .await
|
||||
/// }
|
||||
/// # }
|
||||
/// ```
|
||||
///
|
||||
/// ## Provided Context Types
|
||||
@@ -491,7 +487,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;
|
||||
@@ -502,7 +498,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();
|
||||
@@ -525,7 +520,6 @@ where
|
||||
/// .run()
|
||||
/// .await
|
||||
/// }
|
||||
/// # }
|
||||
/// ```
|
||||
///
|
||||
/// ## Provided Context Types
|
||||
@@ -551,7 +545,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;
|
||||
@@ -562,7 +556,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();
|
||||
@@ -582,7 +575,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.8.1"
|
||||
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.
|
||||
@@ -440,7 +442,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};
|
||||
@@ -450,7 +452,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() {
|
||||
@@ -469,7 +470,9 @@ pub type PinnedHtmlStream =
|
||||
/// .await
|
||||
/// .unwrap();
|
||||
/// }
|
||||
/// # }
|
||||
///
|
||||
/// # #[cfg(not(feature = "default"))]
|
||||
/// # fn main() { }
|
||||
/// ```
|
||||
///
|
||||
/// ## Provided Context Types
|
||||
@@ -528,7 +531,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};
|
||||
@@ -538,7 +541,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() {
|
||||
@@ -557,7 +559,9 @@ where
|
||||
/// .await
|
||||
/// .unwrap();
|
||||
/// }
|
||||
/// # }
|
||||
///
|
||||
/// # #[cfg(not(feature = "default"))]
|
||||
/// # fn main() { }
|
||||
/// ```
|
||||
///
|
||||
/// ## Provided Context Types
|
||||
@@ -941,7 +945,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};
|
||||
@@ -951,7 +955,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() {
|
||||
@@ -971,7 +974,9 @@ fn provide_contexts(
|
||||
/// .await
|
||||
/// .unwrap();
|
||||
/// }
|
||||
/// # }
|
||||
///
|
||||
/// # #[cfg(not(feature = "default"))]
|
||||
/// # fn main() { }
|
||||
/// ```
|
||||
///
|
||||
/// ## Provided Context Types
|
||||
@@ -1988,7 +1993,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,
|
||||
@@ -2004,40 +2010,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",
|
||||
|
||||
@@ -311,11 +311,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(());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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.8.0-alpha"
|
||||
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,7 +34,7 @@ log = "0.4.22"
|
||||
typed-builder = "0.20.0"
|
||||
trybuild = "1.0"
|
||||
leptos = { path = "../leptos" }
|
||||
leptos_router = { path = "../router", features= ["ssr"] }
|
||||
leptos_router = { path = "../router", features = ["ssr"] }
|
||||
server_fn = { path = "../server_fn", features = ["cbor"] }
|
||||
insta = "1.41"
|
||||
serde = "1.0"
|
||||
@@ -55,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]
|
||||
@@ -86,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-02-19", "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-02-19", "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");
|
||||
@@ -570,7 +568,7 @@ impl ToTokens for Model {
|
||||
#tracing_instrument_attr
|
||||
#vis fn #name #impl_generics (
|
||||
#props_arg
|
||||
) #ret #(+ #lifetimes)*
|
||||
) #ret
|
||||
#where_clause
|
||||
{
|
||||
#body
|
||||
|
||||
@@ -677,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`.
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -1192,8 +1197,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) => {
|
||||
@@ -1211,11 +1215,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()
|
||||
@@ -1228,15 +1238,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)
|
||||
@@ -1442,13 +1466,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
|
||||
@@ -1640,8 +1673,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())
|
||||
@@ -1657,7 +1699,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())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)'] }
|
||||
|
||||
@@ -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,38 +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,
|
||||
vec![],
|
||||
);
|
||||
_ = 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>
|
||||
@@ -392,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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -418,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),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -452,6 +427,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>(
|
||||
@@ -465,7 +460,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 }
|
||||
|
||||
@@ -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.7", features = ["csr"] }
|
||||
leptos_meta = { version = "0.7.7" }
|
||||
leptos_router = { version = "0.7.7" }
|
||||
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>
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "reactive_graph"
|
||||
version = "0.1.4"
|
||||
version = "0.1.7"
|
||||
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))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -388,9 +390,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);
|
||||
@@ -434,9 +437,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 +491,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);
|
||||
|
||||
|
||||
@@ -105,8 +105,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);
|
||||
|
||||
@@ -169,8 +171,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);
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -130,6 +130,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 +164,7 @@ impl Owner {
|
||||
children: Default::default(),
|
||||
#[cfg(feature = "sandboxed-arenas")]
|
||||
arena: Default::default(),
|
||||
paused: false,
|
||||
})),
|
||||
#[cfg(feature = "hydration")]
|
||||
shared_context,
|
||||
@@ -174,8 +176,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,15 +189,12 @@ 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
|
||||
}
|
||||
|
||||
@@ -349,6 +350,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)]
|
||||
@@ -375,6 +417,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 {
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
@@ -196,3 +196,62 @@ async fn recursive_effect_runs_recursively() {
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
#[cfg(feature = "effects")]
|
||||
#[tokio::test]
|
||||
async fn paused_effect_pauses() {
|
||||
use imports::*;
|
||||
use reactive_graph::owner::StoredValue;
|
||||
|
||||
_ = Executor::init_tokio();
|
||||
let owner = Owner::new();
|
||||
owner.set();
|
||||
|
||||
task::LocalSet::new()
|
||||
.run_until(async {
|
||||
let a = RwSignal::new(-1);
|
||||
|
||||
// simulate an arbitrary side effect
|
||||
let runs = StoredValue::new(0);
|
||||
|
||||
let owner = StoredValue::new(None);
|
||||
|
||||
Effect::new({
|
||||
move || {
|
||||
*owner.write_value() = Owner::current();
|
||||
|
||||
let _ = a.get();
|
||||
*runs.write_value() += 1;
|
||||
}
|
||||
});
|
||||
|
||||
Executor::tick().await;
|
||||
assert_eq!(runs.get_value(), 1);
|
||||
|
||||
println!("setting to 1");
|
||||
a.set(1);
|
||||
|
||||
Executor::tick().await;
|
||||
assert_eq!(runs.get_value(), 2);
|
||||
|
||||
println!("pausing");
|
||||
owner.get_value().unwrap().pause();
|
||||
|
||||
println!("setting to 2");
|
||||
a.set(2);
|
||||
|
||||
Executor::tick().await;
|
||||
assert_eq!(runs.get_value(), 2);
|
||||
|
||||
println!("resuming");
|
||||
owner.get_value().unwrap().resume();
|
||||
|
||||
println!("setting to 3");
|
||||
a.set(3);
|
||||
|
||||
Executor::tick().await;
|
||||
println!("checking value");
|
||||
assert_eq!(runs.get_value(), 3);
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "reactive_stores"
|
||||
version = "0.1.3"
|
||||
version = "0.1.7"
|
||||
authors = ["Greg Johnston"]
|
||||
license = "MIT"
|
||||
readme = "../README.md"
|
||||
@@ -11,7 +11,7 @@ edition.workspace = true
|
||||
|
||||
[dependencies]
|
||||
guardian = "1.2"
|
||||
itertools = "0.13.0"
|
||||
itertools = { workspace = true }
|
||||
or_poisoned = { workspace = true }
|
||||
paste = "1.0"
|
||||
reactive_graph = { workspace = true }
|
||||
@@ -19,7 +19,7 @@ rustc-hash = "2.0"
|
||||
reactive_stores_macro = { workspace = true }
|
||||
|
||||
[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"] }
|
||||
reactive_graph = { workspace = true, features = ["effects"] }
|
||||
|
||||
@@ -10,7 +10,6 @@ use reactive_graph::{
|
||||
DefinedAt, IsDisposed, Notify, ReadUntracked, Track, UntrackableGuard,
|
||||
Write,
|
||||
},
|
||||
unwrap_signal,
|
||||
};
|
||||
use std::{
|
||||
fmt::Debug,
|
||||
@@ -44,14 +43,14 @@ where
|
||||
self.inner
|
||||
.try_get_value()
|
||||
.map(|inner| inner.get_trigger(path))
|
||||
.unwrap_or_else(unwrap_signal!(self))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn path(&self) -> impl IntoIterator<Item = StorePathSegment> {
|
||||
self.inner
|
||||
.try_get_value()
|
||||
.map(|inner| inner.path().into_iter().collect::<Vec<_>>())
|
||||
.unwrap_or_else(unwrap_signal!(self))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn reader(&self) -> Option<Self::Reader> {
|
||||
@@ -82,6 +81,21 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S> From<ArcField<T>> for Field<T, S>
|
||||
where
|
||||
T: 'static,
|
||||
S: Storage<ArcField<T>>,
|
||||
{
|
||||
#[track_caller]
|
||||
fn from(value: ArcField<T>) -> Self {
|
||||
Field {
|
||||
#[cfg(any(debug_assertions, leptos_debuginfo))]
|
||||
defined_at: Location::caller(),
|
||||
inner: ArenaItem::new_with_storage(value),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S> From<ArcStore<T>> for Field<T, S>
|
||||
where
|
||||
T: Send + Sync + 'static,
|
||||
|
||||
@@ -148,11 +148,8 @@ where
|
||||
{
|
||||
fn latest_keys(&self) -> Vec<K> {
|
||||
self.reader()
|
||||
.expect("trying to update keys")
|
||||
.deref()
|
||||
.into_iter()
|
||||
.map(|n| (self.key_fn)(n))
|
||||
.collect()
|
||||
.map(|r| r.deref().into_iter().map(|n| (self.key_fn)(n)).collect())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -483,8 +480,7 @@ where
|
||||
|| self.inner.latest_keys(),
|
||||
)
|
||||
.flatten()
|
||||
.map(|(_, idx)| idx)
|
||||
.expect("reading from a keyed field that has not yet been created");
|
||||
.map(|(_, idx)| idx)?;
|
||||
|
||||
Some(WriteGuard::new(
|
||||
trigger.children,
|
||||
@@ -654,13 +650,15 @@ where
|
||||
self.track_field();
|
||||
|
||||
// get the current length of the field by accessing slice
|
||||
let reader = self
|
||||
.reader()
|
||||
.expect("creating iterator from unavailable store field");
|
||||
let reader = self.reader();
|
||||
|
||||
let keys = reader
|
||||
.into_iter()
|
||||
.map(|item| (self.key_fn)(item))
|
||||
.collect::<VecDeque<_>>();
|
||||
.map(|r| {
|
||||
r.into_iter()
|
||||
.map(|item| (self.key_fn)(item))
|
||||
.collect::<VecDeque<_>>()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
|
||||
// return the iterator
|
||||
StoreFieldKeyedIter { inner: self, keys }
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use crate::{StoreField, Subfield};
|
||||
use reactive_graph::traits::{Read, ReadUntracked};
|
||||
use reactive_graph::traits::{FlattenOptionRefOption, Read, ReadUntracked};
|
||||
use std::ops::Deref;
|
||||
|
||||
/// Extends optional store fields, with the ability to unwrap or map over them.
|
||||
@@ -13,6 +13,13 @@ where
|
||||
/// Provides access to the inner value, as a subfield, unwrapping the outer value.
|
||||
fn unwrap(self) -> Subfield<Self, Option<Self::Output>, Self::Output>;
|
||||
|
||||
/// Inverts a subfield of an `Option` to an `Option` of a subfield.
|
||||
fn invert(
|
||||
self,
|
||||
) -> Option<Subfield<Self, Option<Self::Output>, Self::Output>> {
|
||||
self.map(|f| f)
|
||||
}
|
||||
|
||||
/// Reactively maps over the field.
|
||||
///
|
||||
/// This returns `None` if the subfield is currently `None`,
|
||||
@@ -56,7 +63,7 @@ where
|
||||
self,
|
||||
map_fn: impl FnOnce(Subfield<S, Option<T>, T>) -> U,
|
||||
) -> Option<U> {
|
||||
if self.read().is_some() {
|
||||
if self.try_read().as_deref().flatten().is_some() {
|
||||
Some(map_fn(self.unwrap()))
|
||||
} else {
|
||||
None
|
||||
@@ -67,7 +74,7 @@ where
|
||||
self,
|
||||
map_fn: impl FnOnce(Subfield<S, Option<T>, T>) -> U,
|
||||
) -> Option<U> {
|
||||
if self.read_untracked().is_some() {
|
||||
if self.try_read_untracked().as_deref().flatten().is_some() {
|
||||
Some(map_fn(self.unwrap()))
|
||||
} else {
|
||||
None
|
||||
@@ -77,11 +84,12 @@ where
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::{self as reactive_stores, Store};
|
||||
use crate::{self as reactive_stores, Patch as _, Store};
|
||||
use reactive_graph::{
|
||||
effect::Effect,
|
||||
traits::{Get, Read, ReadUntracked, Set, Write},
|
||||
};
|
||||
use reactive_stores_macro::Patch;
|
||||
use std::sync::{
|
||||
atomic::{AtomicUsize, Ordering},
|
||||
Arc,
|
||||
@@ -237,4 +245,115 @@ mod tests {
|
||||
assert_eq!(parent_count.load(Ordering::Relaxed), 3);
|
||||
assert_eq!(inner_count.load(Ordering::Relaxed), 3);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn patch() {
|
||||
use crate::OptionStoreExt;
|
||||
|
||||
#[derive(Debug, Clone, Store, Patch)]
|
||||
struct Outer {
|
||||
inner: Option<Inner>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Store, Patch)]
|
||||
struct Inner {
|
||||
first: String,
|
||||
second: String,
|
||||
}
|
||||
|
||||
let store = Store::new(Outer {
|
||||
inner: Some(Inner {
|
||||
first: "A".to_owned(),
|
||||
second: "B".to_owned(),
|
||||
}),
|
||||
});
|
||||
|
||||
_ = any_spawner::Executor::init_tokio();
|
||||
|
||||
let parent_count = Arc::new(AtomicUsize::new(0));
|
||||
let inner_first_count = Arc::new(AtomicUsize::new(0));
|
||||
let inner_second_count = Arc::new(AtomicUsize::new(0));
|
||||
|
||||
Effect::new_sync({
|
||||
let parent_count = Arc::clone(&parent_count);
|
||||
move |prev: Option<()>| {
|
||||
if prev.is_none() {
|
||||
println!("parent: first run");
|
||||
} else {
|
||||
println!("parent: next run");
|
||||
}
|
||||
|
||||
println!(" value = {:?}", store.inner().get());
|
||||
parent_count.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
});
|
||||
Effect::new_sync({
|
||||
let inner_first_count = Arc::clone(&inner_first_count);
|
||||
move |prev: Option<()>| {
|
||||
if prev.is_none() {
|
||||
println!("inner_first: first run");
|
||||
} else {
|
||||
println!("inner_first: next run");
|
||||
}
|
||||
|
||||
println!(
|
||||
" value = {:?}",
|
||||
store.inner().map(|inner| inner.first().get())
|
||||
);
|
||||
inner_first_count.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
});
|
||||
Effect::new_sync({
|
||||
let inner_second_count = Arc::clone(&inner_second_count);
|
||||
move |prev: Option<()>| {
|
||||
if prev.is_none() {
|
||||
println!("inner_second: first run");
|
||||
} else {
|
||||
println!("inner_second: next run");
|
||||
}
|
||||
|
||||
println!(
|
||||
" value = {:?}",
|
||||
store.inner().map(|inner| inner.second().get())
|
||||
);
|
||||
inner_second_count.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
});
|
||||
|
||||
tick().await;
|
||||
assert_eq!(parent_count.load(Ordering::Relaxed), 1);
|
||||
assert_eq!(inner_first_count.load(Ordering::Relaxed), 1);
|
||||
assert_eq!(inner_second_count.load(Ordering::Relaxed), 1);
|
||||
|
||||
store.patch(Outer {
|
||||
inner: Some(Inner {
|
||||
first: "A".to_string(),
|
||||
second: "C".to_string(),
|
||||
}),
|
||||
});
|
||||
|
||||
tick().await;
|
||||
assert_eq!(parent_count.load(Ordering::Relaxed), 1);
|
||||
assert_eq!(inner_first_count.load(Ordering::Relaxed), 1);
|
||||
assert_eq!(inner_second_count.load(Ordering::Relaxed), 2);
|
||||
|
||||
store.patch(Outer { inner: None });
|
||||
|
||||
tick().await;
|
||||
assert_eq!(parent_count.load(Ordering::Relaxed), 2);
|
||||
assert_eq!(inner_first_count.load(Ordering::Relaxed), 2);
|
||||
assert_eq!(inner_second_count.load(Ordering::Relaxed), 3);
|
||||
|
||||
store.patch(Outer {
|
||||
inner: Some(Inner {
|
||||
first: "A".to_string(),
|
||||
second: "B".to_string(),
|
||||
}),
|
||||
});
|
||||
|
||||
tick().await;
|
||||
assert_eq!(parent_count.load(Ordering::Relaxed), 3);
|
||||
assert_eq!(inner_first_count.load(Ordering::Relaxed), 3);
|
||||
assert_eq!(inner_second_count.load(Ordering::Relaxed), 4);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -114,6 +114,35 @@ patch_primitives! {
|
||||
NonZeroUsize
|
||||
}
|
||||
|
||||
impl<T> PatchField for Option<T>
|
||||
where
|
||||
T: PatchField,
|
||||
{
|
||||
fn patch_field(
|
||||
&mut self,
|
||||
new: Self,
|
||||
path: &StorePath,
|
||||
notify: &mut dyn FnMut(&StorePath),
|
||||
) {
|
||||
match (self, new) {
|
||||
(None, None) => {}
|
||||
(old @ Some(_), None) => {
|
||||
old.take();
|
||||
notify(path);
|
||||
}
|
||||
(old @ None, new @ Some(_)) => {
|
||||
*old = new;
|
||||
notify(path);
|
||||
}
|
||||
(Some(old), Some(new)) => {
|
||||
let mut new_path = path.to_owned();
|
||||
new_path.push(0);
|
||||
old.patch_field(new, &new_path, notify);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> PatchField for Vec<T>
|
||||
where
|
||||
T: PatchField,
|
||||
|
||||
@@ -9,8 +9,7 @@ use reactive_graph::{
|
||||
guards::{Plain, UntrackedWriteGuard, WriteGuard},
|
||||
ArcTrigger,
|
||||
},
|
||||
traits::{DefinedAt, Track, UntrackableGuard},
|
||||
unwrap_signal,
|
||||
traits::{Track, UntrackableGuard},
|
||||
};
|
||||
use std::{iter, ops::Deref, sync::Arc};
|
||||
|
||||
@@ -105,7 +104,7 @@ where
|
||||
self.inner
|
||||
.try_get_value()
|
||||
.map(|n| n.get_trigger(path))
|
||||
.unwrap_or_else(unwrap_signal!(self))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
#[track_caller]
|
||||
@@ -113,7 +112,7 @@ where
|
||||
self.inner
|
||||
.try_get_value()
|
||||
.map(|n| n.path().into_iter().collect::<Vec<_>>())
|
||||
.unwrap_or_else(unwrap_signal!(self))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
#[track_caller]
|
||||
|
||||
@@ -9,9 +9,10 @@ use reactive_graph::{
|
||||
ArcTrigger,
|
||||
},
|
||||
traits::{
|
||||
DefinedAt, IsDisposed, Notify, ReadUntracked, Track, UntrackableGuard,
|
||||
Write,
|
||||
DefinedAt, Get as _, IsDisposed, Notify, ReadUntracked, Track,
|
||||
UntrackableGuard, Write,
|
||||
},
|
||||
wrappers::read::Signal,
|
||||
};
|
||||
use std::{iter, marker::PhantomData, ops::DerefMut, panic::Location};
|
||||
|
||||
@@ -223,3 +224,14 @@ where
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<Inner, Prev, T> From<Subfield<Inner, Prev, T>> for Signal<T>
|
||||
where
|
||||
Inner: StoreField<Value = Prev> + Track + Send + Sync + 'static,
|
||||
Prev: 'static,
|
||||
T: Send + Sync + Clone + 'static,
|
||||
{
|
||||
fn from(subfield: Subfield<Inner, Prev, T>) -> Self {
|
||||
Signal::derive(move || subfield.get())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "reactive_stores_macro"
|
||||
version = "0.1.0"
|
||||
version = "0.1.7"
|
||||
authors = ["Greg Johnston"]
|
||||
license = "MIT"
|
||||
readme = "../README.md"
|
||||
@@ -13,7 +13,7 @@ edition.workspace = true
|
||||
proc-macro = true
|
||||
|
||||
[dependencies]
|
||||
convert_case = "0.6"
|
||||
convert_case = "0.7"
|
||||
proc-macro-error2 = "2.0"
|
||||
proc-macro2 = "1.0"
|
||||
quote = "1.0"
|
||||
|
||||
@@ -87,15 +87,15 @@ impl Parse for SubfieldMode {
|
||||
fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
|
||||
let mode: Ident = input.parse()?;
|
||||
if mode == "key" {
|
||||
let _col: Token!(:) = input.parse()?;
|
||||
let _col: Token![:] = input.parse()?;
|
||||
let ty: Type = input.parse()?;
|
||||
let _eq: Token!(=) = input.parse()?;
|
||||
let ident: ExprClosure = input.parse()?;
|
||||
Ok(SubfieldMode::Keyed(ident, ty))
|
||||
let _eq: Token![=] = input.parse()?;
|
||||
let closure: ExprClosure = input.parse()?;
|
||||
Ok(SubfieldMode::Keyed(closure, ty))
|
||||
} else if mode == "skip" {
|
||||
Ok(SubfieldMode::Skip)
|
||||
} else {
|
||||
Err(input.error("expected `key = <ident>: <Type>`"))
|
||||
Err(input.error("expected `key: <Type> = <closure>`"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,7 +20,7 @@ tachys = { workspace = true, features = ["reactive_graph"] }
|
||||
futures = "0.3.31"
|
||||
url = "2.5"
|
||||
js-sys = { version = "0.3.74" }
|
||||
wasm-bindgen = { version = "0.2.97" }
|
||||
wasm-bindgen = { workspace = true }
|
||||
tracing = { version = "0.1.41", optional = true }
|
||||
once_cell = "1.20"
|
||||
send_wrapper = "0.6.0"
|
||||
@@ -71,4 +71,4 @@ denylist = ["tracing"]
|
||||
unexpected_cfgs = { level = "warn", check-cfg = [
|
||||
'cfg(leptos_debuginfo)',
|
||||
'cfg(erase_components)',
|
||||
] }
|
||||
] }
|
||||
|
||||
@@ -123,14 +123,20 @@ impl Url {
|
||||
|
||||
#[cfg(not(feature = "ssr"))]
|
||||
{
|
||||
js_sys::decode_uri_component(s).unwrap().into()
|
||||
match js_sys::decode_uri_component(s) {
|
||||
Ok(v) => v.into(),
|
||||
Err(_) => s.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn unescape_minimal(s: &str) -> String {
|
||||
#[cfg(not(feature = "ssr"))]
|
||||
{
|
||||
js_sys::decode_uri(s).unwrap().into()
|
||||
match js_sys::decode_uri(s) {
|
||||
Ok(v) => v.into(),
|
||||
Err(_) => s.into(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "ssr")]
|
||||
|
||||
@@ -43,7 +43,7 @@ multer = { version = "3.1", optional = true }
|
||||
|
||||
## output encodings
|
||||
# serde
|
||||
serde_json = "1.0"
|
||||
serde_json = { workspace = true }
|
||||
serde-lite = { version = "0.5.0", features = ["derive"], optional = true }
|
||||
futures = "0.3.31"
|
||||
http = { version = "1.1" }
|
||||
@@ -59,8 +59,8 @@ base64 = { version = "0.22.1" }
|
||||
# client
|
||||
gloo-net = { version = "0.6.0", optional = true }
|
||||
js-sys = { version = "0.3.74", optional = true }
|
||||
wasm-bindgen = { version = "0.2.97", optional = true }
|
||||
wasm-bindgen-futures = { version = "0.4.47", optional = true }
|
||||
wasm-bindgen = { version = "0.2.100", optional = true }
|
||||
wasm-bindgen-futures = { version = "0.4.50", optional = true }
|
||||
wasm-streams = { version = "0.4.2", optional = true }
|
||||
web-sys = { version = "0.3.72", optional = true, features = [
|
||||
"console",
|
||||
|
||||
@@ -28,7 +28,7 @@ use syn::__private::ToTokens;
|
||||
///
|
||||
/// You can any combination of the following named arguments:
|
||||
/// - `name`: sets the identifier for the server function’s type, which is a struct created
|
||||
/// to hold the arguments (defaults to the function identifier in PascalCase)
|
||||
/// to hold the arguments (defaults to the function identifier in PascalCase)
|
||||
/// - `prefix`: a prefix at which the server function handler will be mounted (defaults to `/api`)
|
||||
/// - `endpoint`: specifies the exact path at which the server function handler will be mounted,
|
||||
/// relative to the prefix (defaults to the function name followed by unique hash)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "tachys"
|
||||
version = "0.1.4"
|
||||
version = "0.1.7"
|
||||
authors = ["Greg Johnston"]
|
||||
license = "MIT"
|
||||
readme = "../README.md"
|
||||
@@ -24,7 +24,7 @@ async-trait = "0.1.81"
|
||||
once_cell = "1.20"
|
||||
paste = "1.0"
|
||||
erased = "0.1.2"
|
||||
wasm-bindgen = "0.2.97"
|
||||
wasm-bindgen = { workspace = true }
|
||||
html-escape = "0.2.13"
|
||||
js-sys = "0.3.74"
|
||||
web-sys = { version = "0.3.72", features = [
|
||||
@@ -154,7 +154,7 @@ indexmap = "2.6"
|
||||
rustc-hash = "2.0"
|
||||
futures = "0.3.31"
|
||||
parking_lot = "0.12.3"
|
||||
itertools = "0.13.0"
|
||||
itertools = { workspace = true }
|
||||
send_wrapper = "0.6.0"
|
||||
linear-map = "1.2"
|
||||
sledgehammer_bindgen = { version = "0.6.0", features = [
|
||||
@@ -165,7 +165,7 @@ tracing = { version = "0.1.41", optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
tokio-test = "0.4.4"
|
||||
tokio = { version = "1.41", features = ["rt", "macros"] }
|
||||
tokio = { version = "1.43", features = ["rt", "macros"] }
|
||||
|
||||
[features]
|
||||
default = ["testing"]
|
||||
@@ -204,4 +204,3 @@ unexpected_cfgs = { level = "warn", check-cfg = [
|
||||
'cfg(leptos_debuginfo)',
|
||||
'cfg(erase_components)',
|
||||
] }
|
||||
|
||||
|
||||
@@ -283,7 +283,7 @@ html_elements! {
|
||||
/// The `<em>` HTML element marks text that has stress emphasis. The `<em>` element can be nested, with each level of nesting indicating a greater degree of emphasis.
|
||||
em HtmlElement [] true,
|
||||
/// The `<fieldset>` HTML element is used to group several controls as well as labels (label) within a web form.
|
||||
fieldset HtmlFieldSetElement [] true,
|
||||
fieldset HtmlFieldSetElement [disabled, form, name] true,
|
||||
/// The `<figcaption>` HTML element represents a caption or legend describing the rest of the contents of its parent figure element.
|
||||
figcaption HtmlElement [] true,
|
||||
/// The `<figure>` HTML element represents self-contained content, potentially with an optional caption, which is specified using the figcaption element. The figure, its caption, and its contents are referenced as a single unit.
|
||||
|
||||
@@ -167,6 +167,9 @@ where
|
||||
el: &crate::renderer::types::Element,
|
||||
cb: Box<dyn FnMut(crate::renderer::types::Event)>,
|
||||
name: Cow<'static, str>,
|
||||
// TODO investigate: does passing this as an option
|
||||
// (rather than, say, having a const DELEGATED: bool)
|
||||
// add to binary size?
|
||||
delegation_key: Option<Cow<'static, str>>,
|
||||
) -> RemoveEventHandler<crate::renderer::types::Element> {
|
||||
match delegation_key {
|
||||
@@ -201,6 +204,39 @@ where
|
||||
.then(|| self.event.event_delegation_key()),
|
||||
)
|
||||
}
|
||||
|
||||
/// Attaches the event listener to the element as a listener that is triggered during the capture phase,
|
||||
/// meaning it will fire before any event listeners further down in the DOM.
|
||||
pub fn attach_capture(
|
||||
self,
|
||||
el: &crate::renderer::types::Element,
|
||||
) -> RemoveEventHandler<crate::renderer::types::Element> {
|
||||
fn attach_inner(
|
||||
el: &crate::renderer::types::Element,
|
||||
cb: Box<dyn FnMut(crate::renderer::types::Event)>,
|
||||
name: Cow<'static, str>,
|
||||
) -> RemoveEventHandler<crate::renderer::types::Element> {
|
||||
Rndr::add_event_listener_use_capture(el, &name, cb)
|
||||
}
|
||||
|
||||
let mut cb = self.cb.expect("callback removed before attaching").take();
|
||||
|
||||
#[cfg(feature = "tracing")]
|
||||
let span = tracing::Span::current();
|
||||
|
||||
let cb = Box::new(move |ev: crate::renderer::types::Event| {
|
||||
#[cfg(all(debug_assertions, feature = "reactive_graph"))]
|
||||
let _rx_guard =
|
||||
reactive_graph::diagnostics::SpecialNonReactiveZone::enter();
|
||||
#[cfg(feature = "tracing")]
|
||||
let _tracing_guard = span.enter();
|
||||
|
||||
let ev = E::EventType::from(ev);
|
||||
cb.invoke(ev);
|
||||
}) as Box<dyn FnMut(crate::renderer::types::Event)>;
|
||||
|
||||
attach_inner(el, cb, self.event.name())
|
||||
}
|
||||
}
|
||||
|
||||
impl<E, F> Debug for On<E, F>
|
||||
@@ -250,13 +286,21 @@ where
|
||||
self,
|
||||
el: &crate::renderer::types::Element,
|
||||
) -> Self::State {
|
||||
let cleanup = self.attach(el);
|
||||
let cleanup = if E::CAPTURE {
|
||||
self.attach_capture(el)
|
||||
} else {
|
||||
self.attach(el)
|
||||
};
|
||||
(el.clone(), Some(cleanup))
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn build(self, el: &crate::renderer::types::Element) -> Self::State {
|
||||
let cleanup = self.attach(el);
|
||||
let cleanup = if E::CAPTURE {
|
||||
self.attach_capture(el)
|
||||
} else {
|
||||
self.attach(el)
|
||||
};
|
||||
(el.clone(), Some(cleanup))
|
||||
}
|
||||
|
||||
@@ -266,7 +310,11 @@ where
|
||||
if let Some(prev) = prev_cleanup.take() {
|
||||
(prev.into_inner())(el);
|
||||
}
|
||||
*prev_cleanup = Some(self.attach(el));
|
||||
*prev_cleanup = Some(if E::CAPTURE {
|
||||
self.attach_capture(el)
|
||||
} else {
|
||||
self.attach(el)
|
||||
});
|
||||
}
|
||||
|
||||
fn into_cloneable(self) -> Self::Cloneable {
|
||||
@@ -334,10 +382,13 @@ pub trait EventDescriptor: Clone {
|
||||
/// Indicates if this event bubbles. For example, `click` bubbles,
|
||||
/// but `focus` does not.
|
||||
///
|
||||
/// If this is true, then the event will be delegated globally,
|
||||
/// otherwise, event listeners will be directly attached to the element.
|
||||
/// If this is true, then the event will be delegated globally if the `delegation`
|
||||
/// feature is enabled. Otherwise, event listeners will be directly attached to the element.
|
||||
const BUBBLES: bool;
|
||||
|
||||
/// Indicates if this event should be handled during the capture phase.
|
||||
const CAPTURE: bool = false;
|
||||
|
||||
/// The name of the event, such as `click` or `mouseover`.
|
||||
fn name(&self) -> Cow<'static, str>;
|
||||
|
||||
@@ -352,6 +403,32 @@ pub trait EventDescriptor: Clone {
|
||||
}
|
||||
}
|
||||
|
||||
/// A wrapper that tells the framework to handle an event during the capture phase.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Capture<E> {
|
||||
inner: E,
|
||||
}
|
||||
|
||||
/// Wraps an event to indicate that it should be handled during the capture phase.
|
||||
pub fn capture<E>(event: E) -> Capture<E> {
|
||||
Capture { inner: event }
|
||||
}
|
||||
|
||||
impl<E: EventDescriptor> EventDescriptor for Capture<E> {
|
||||
type EventType = E::EventType;
|
||||
|
||||
const CAPTURE: bool = true;
|
||||
const BUBBLES: bool = E::BUBBLES;
|
||||
|
||||
fn name(&self) -> Cow<'static, str> {
|
||||
self.inner.name()
|
||||
}
|
||||
|
||||
fn event_delegation_key(&self) -> Cow<'static, str> {
|
||||
self.inner.event_delegation_key()
|
||||
}
|
||||
}
|
||||
|
||||
/// A custom event.
|
||||
#[derive(Debug)]
|
||||
pub struct Custom<E: FromWasmAbi = web_sys::Event> {
|
||||
|
||||
@@ -13,7 +13,7 @@ use once_cell::unsync::Lazy;
|
||||
use rustc_hash::FxHashSet;
|
||||
use std::{any::TypeId, borrow::Cow, cell::RefCell};
|
||||
use wasm_bindgen::{intern, prelude::Closure, JsCast, JsValue};
|
||||
use web_sys::{Comment, HtmlTemplateElement};
|
||||
use web_sys::{AddEventListenerOptions, Comment, HtmlTemplateElement};
|
||||
|
||||
/// A [`Renderer`](crate::renderer::Renderer) that uses `web-sys` to manipulate DOM elements in the browser.
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||
@@ -245,6 +245,44 @@ impl Dom {
|
||||
})
|
||||
}
|
||||
|
||||
pub fn add_event_listener_use_capture(
|
||||
el: &Element,
|
||||
name: &str,
|
||||
cb: Box<dyn FnMut(Event)>,
|
||||
) -> RemoveEventHandler<Element> {
|
||||
let cb = wasm_bindgen::closure::Closure::wrap(cb);
|
||||
let name = intern(name);
|
||||
let options = AddEventListenerOptions::new();
|
||||
options.set_capture(true);
|
||||
or_debug!(
|
||||
el.add_event_listener_with_callback_and_add_event_listener_options(
|
||||
name,
|
||||
cb.as_ref().unchecked_ref(),
|
||||
&options
|
||||
),
|
||||
el,
|
||||
"addEventListenerUseCapture"
|
||||
);
|
||||
|
||||
// return the remover
|
||||
RemoveEventHandler::new({
|
||||
let name = name.to_owned();
|
||||
// safe to construct this here, because it will only run in the browser
|
||||
// so it will always be accessed or dropped from the main thread
|
||||
let cb = send_wrapper::SendWrapper::new(cb);
|
||||
move |el: &Element| {
|
||||
or_debug!(
|
||||
el.remove_event_listener_with_callback(
|
||||
intern(&name),
|
||||
cb.as_ref().unchecked_ref()
|
||||
),
|
||||
el,
|
||||
"removeEventListener"
|
||||
)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub fn event_target<T>(ev: &Event) -> T
|
||||
where
|
||||
T: CastFrom<Element>,
|
||||
|
||||
@@ -3,8 +3,10 @@ use super::{
|
||||
Render, RenderHtml,
|
||||
};
|
||||
use crate::{
|
||||
html::attribute::{any_attribute::AnyAttribute, Attribute},
|
||||
html::attribute::{any_attribute::Any{Attribute, Attribute},
|
||||
NextAttribute},
|
||||
hydration::Cursor,
|
||||
|
||||
ssr::StreamBuilder,
|
||||
};
|
||||
use either_of::*;
|
||||
@@ -123,6 +125,150 @@ const fn max_usize(vals: &[usize]) -> usize {
|
||||
max
|
||||
}
|
||||
|
||||
#[cfg(not(erase_components))]
|
||||
impl<A, B> NextAttribute for Either<A, B>
|
||||
where
|
||||
B: NextAttribute,
|
||||
A: NextAttribute,
|
||||
{
|
||||
type Output<NewAttr: Attribute> = Either<
|
||||
<A as NextAttribute>::Output<NewAttr>,
|
||||
<B as NextAttribute>::Output<NewAttr>,
|
||||
>;
|
||||
|
||||
fn add_any_attr<NewAttr: Attribute>(
|
||||
self,
|
||||
new_attr: NewAttr,
|
||||
) -> Self::Output<NewAttr> {
|
||||
match self {
|
||||
Either::Left(left) => Either::Left(left.add_any_attr(new_attr)),
|
||||
Either::Right(right) => Either::Right(right.add_any_attr(new_attr)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(erase_components)]
|
||||
use crate::html::attribute::any_attribute::{AnyAttribute, IntoAnyAttribute};
|
||||
|
||||
#[cfg(erase_components)]
|
||||
impl<A, B> NextAttribute for Either<A, B>
|
||||
where
|
||||
B: IntoAnyAttribute,
|
||||
A: IntoAnyAttribute,
|
||||
{
|
||||
type Output<NewAttr: Attribute> = Vec<AnyAttribute>;
|
||||
|
||||
fn add_any_attr<NewAttr: Attribute>(
|
||||
self,
|
||||
new_attr: NewAttr,
|
||||
) -> Self::Output<NewAttr> {
|
||||
vec![
|
||||
match self {
|
||||
Either::Left(left) => left.into_any_attr(),
|
||||
Either::Right(right) => right.into_any_attr(),
|
||||
},
|
||||
new_attr.into_any_attr(),
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, B> Attribute for Either<A, B>
|
||||
where
|
||||
B: Attribute,
|
||||
A: Attribute,
|
||||
{
|
||||
const MIN_LENGTH: usize = max_usize(&[A::MIN_LENGTH, B::MIN_LENGTH]);
|
||||
|
||||
type AsyncOutput = Either<A::AsyncOutput, B::AsyncOutput>;
|
||||
type State = Either<A::State, B::State>;
|
||||
type Cloneable = Either<A::Cloneable, B::Cloneable>;
|
||||
type CloneableOwned = Either<A::CloneableOwned, B::CloneableOwned>;
|
||||
|
||||
fn html_len(&self) -> usize {
|
||||
match self {
|
||||
Either::Left(left) => left.html_len(),
|
||||
Either::Right(right) => right.html_len(),
|
||||
}
|
||||
}
|
||||
|
||||
fn to_html(
|
||||
self,
|
||||
buf: &mut String,
|
||||
class: &mut String,
|
||||
style: &mut String,
|
||||
inner_html: &mut String,
|
||||
) {
|
||||
match self {
|
||||
Either::Left(left) => left.to_html(buf, class, style, inner_html),
|
||||
Either::Right(right) => {
|
||||
right.to_html(buf, class, style, inner_html)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn hydrate<const FROM_SERVER: bool>(
|
||||
self,
|
||||
el: &crate::renderer::types::Element,
|
||||
) -> Self::State {
|
||||
match self {
|
||||
Either::Left(left) => Either::Left(left.hydrate::<FROM_SERVER>(el)),
|
||||
Either::Right(right) => {
|
||||
Either::Right(right.hydrate::<FROM_SERVER>(el))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn build(self, el: &crate::renderer::types::Element) -> Self::State {
|
||||
match self {
|
||||
Either::Left(left) => Either::Left(left.build(el)),
|
||||
Either::Right(right) => Either::Right(right.build(el)),
|
||||
}
|
||||
}
|
||||
|
||||
fn rebuild(self, state: &mut Self::State) {
|
||||
match self {
|
||||
Either::Left(left) => {
|
||||
if let Some(state) = state.as_left_mut() {
|
||||
left.rebuild(state)
|
||||
}
|
||||
}
|
||||
Either::Right(right) => {
|
||||
if let Some(state) = state.as_right_mut() {
|
||||
right.rebuild(state)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn into_cloneable(self) -> Self::Cloneable {
|
||||
match self {
|
||||
Either::Left(left) => Either::Left(left.into_cloneable()),
|
||||
Either::Right(right) => Either::Right(right.into_cloneable()),
|
||||
}
|
||||
}
|
||||
|
||||
fn into_cloneable_owned(self) -> Self::CloneableOwned {
|
||||
match self {
|
||||
Either::Left(left) => Either::Left(left.into_cloneable_owned()),
|
||||
Either::Right(right) => Either::Right(right.into_cloneable_owned()),
|
||||
}
|
||||
}
|
||||
|
||||
fn dry_resolve(&mut self) {
|
||||
match self {
|
||||
Either::Left(left) => left.dry_resolve(),
|
||||
Either::Right(right) => right.dry_resolve(),
|
||||
}
|
||||
}
|
||||
|
||||
async fn resolve(self) -> Self::AsyncOutput {
|
||||
match self {
|
||||
Either::Left(left) => Either::Left(left.resolve().await),
|
||||
Either::Right(right) => Either::Right(right.resolve().await),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, B> RenderHtml for Either<A, B>
|
||||
where
|
||||
A: RenderHtml,
|
||||
|
||||
@@ -329,6 +329,7 @@ where
|
||||
}
|
||||
if escape {
|
||||
buf.push_str("<!>");
|
||||
*position = Position::NextChild;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -363,6 +364,7 @@ where
|
||||
}
|
||||
if escape {
|
||||
buf.push_sync("<!>");
|
||||
*position = Position::NextChild;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -377,6 +379,7 @@ where
|
||||
.collect();
|
||||
|
||||
let marker = cursor.next_placeholder(position);
|
||||
position.set(Position::NextChild);
|
||||
|
||||
VecState { states, marker }
|
||||
}
|
||||
|
||||
@@ -286,6 +286,7 @@ where
|
||||
rendered_items.push(Some((set_index, item)));
|
||||
}
|
||||
let marker = cursor.next_placeholder(position);
|
||||
position.set(Position::NextChild);
|
||||
KeyedState {
|
||||
parent: Some(parent),
|
||||
marker,
|
||||
|
||||
@@ -5,10 +5,15 @@ use super::{
|
||||
use crate::{
|
||||
html::attribute::{
|
||||
any_attribute::AnyAttribute,
|
||||
maybe_next_attr_erasure_macros::{
|
||||
next_attr_combine, next_attr_output_type,
|
||||
},
|
||||
|
||||
maybe_next_attr_erasure_macros::{
|
||||
next_attr_combine, next_attr_output_type,
|
||||
},
|
||||
Attribute, AttributeKey, AttributeValue, NextAttribute,
|
||||
,
|
||||
},
|
||||
hydration::Cursor,
|
||||
renderer::{CastFrom, Rndr},
|
||||
|
||||
@@ -47,7 +47,9 @@ impl RenderHtml for () {
|
||||
cursor: &Cursor,
|
||||
position: &PositionState,
|
||||
) -> Self::State {
|
||||
cursor.next_placeholder(position)
|
||||
let marker = cursor.next_placeholder(position);
|
||||
position.set(Position::NextChild);
|
||||
marker
|
||||
}
|
||||
|
||||
async fn resolve(self) -> Self::AsyncOutput {}
|
||||
|
||||
Reference in New Issue
Block a user