Compare commits

..

7 Commits

Author SHA1 Message Date
Greg Johnston
ebea3ec14d continue trying to remove EitherOf instances 2024-10-20 15:57:23 -04:00
Greg Johnston
ed3ca9eae1 clippy 2024-10-20 14:18:24 -04:00
Greg Johnston
ed8abcfbcd update to main 2024-10-20 14:18:24 -04:00
Greg Johnston
29a56af38c use .into_any() throughout the router 2024-10-20 14:18:24 -04:00
Greg Johnston
f9d6f7fd64 manually add .into_any() on pages 2024-10-20 14:18:24 -04:00
Greg Johnston
251a472cd5 erase types everywhere in route matching 2024-10-20 14:18:24 -04:00
Greg Johnston
3c76cb24d3 erase ChooseView only 2024-10-20 14:18:02 -04:00
169 changed files with 1668 additions and 9834 deletions

View File

@@ -7,6 +7,7 @@ updates:
- package-ecosystem: "cargo"
directories:
- "/"
- "/examples/*"
- "/benchmarks"
schedule:
interval: "daily"
open-pull-requests-limit: 10

View File

@@ -19,19 +19,6 @@ jobs:
name: Run ${{ inputs.cargo_make_task }} (${{ inputs.toolchain }})
runs-on: ubuntu-latest
steps:
- name: Free Disk Space
run: |
echo "Disk space before cleanup:"
df -h
sudo rm -rf /usr/local/.ghcup
sudo rm -rf /opt/hostedtoolcache/CodeQL
sudo rm -rf /usr/local/lib/android/sdk/ndk
sudo rm -rf /usr/share/dotnet
sudo rm -rf /opt/ghc
sudo rm -rf /usr/local/share/boost
sudo apt-get clean
echo "Disk space after cleanup:"
df -h
# Setup environment
- uses: actions/checkout@v4
- name: Setup Rust

6
.gitignore vendored
View File

@@ -3,9 +3,7 @@ dist
pkg
comparisons
blob.rs
**/projects/**/Cargo.lock
**/examples/**/Cargo.lock
**/benchmarks/**/Cargo.lock
Cargo.lock
**/*.rs.bk
.DS_Store
.idea
@@ -13,4 +11,4 @@ blob.rs
.envrc
.vscode
vendor
vendor

4474
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -40,36 +40,36 @@ members = [
exclude = ["benchmarks", "examples", "projects"]
[workspace.package]
version = "0.7.0-rc1"
version = "0.7.0-gamma3"
edition = "2021"
rust-version = "1.76"
[workspace.dependencies]
throw_error = { path = "./any_error/", version = "0.2.0-rc1" }
throw_error = { path = "./any_error/", version = "0.2.0-gamma3" }
any_spawner = { path = "./any_spawner/", version = "0.1.0" }
const_str_slice_concat = { path = "./const_str_slice_concat", version = "0.1.0" }
either_of = { path = "./either_of/", version = "0.1.0" }
hydration_context = { path = "./hydration_context", version = "0.2.0-rc1" }
leptos = { path = "./leptos", version = "0.7.0-rc1" }
leptos_config = { path = "./leptos_config", version = "0.7.0-rc1" }
leptos_dom = { path = "./leptos_dom", version = "0.7.0-rc1" }
leptos_hot_reload = { path = "./leptos_hot_reload", version = "0.7.0-rc1" }
leptos_integration_utils = { path = "./integrations/utils", version = "0.7.0-rc1" }
leptos_macro = { path = "./leptos_macro", version = "0.7.0-rc1" }
leptos_router = { path = "./router", version = "0.7.0-rc1" }
leptos_router_macro = { path = "./router_macro", version = "0.7.0-rc1" }
leptos_server = { path = "./leptos_server", version = "0.7.0-rc1" }
leptos_meta = { path = "./meta", version = "0.7.0-rc1" }
next_tuple = { path = "./next_tuple", version = "0.1.0-rc1" }
hydration_context = { path = "./hydration_context", version = "0.2.0-gamma3" }
leptos = { path = "./leptos", version = "0.7.0-gamma3" }
leptos_config = { path = "./leptos_config", version = "0.7.0-gamma3" }
leptos_dom = { path = "./leptos_dom", version = "0.7.0-gamma3" }
leptos_hot_reload = { path = "./leptos_hot_reload", version = "0.7.0-gamma3" }
leptos_integration_utils = { path = "./integrations/utils", version = "0.7.0-gamma3" }
leptos_macro = { path = "./leptos_macro", version = "0.7.0-gamma3" }
leptos_router = { path = "./router", version = "0.7.0-gamma3" }
leptos_router_macro = { path = "./router_macro", version = "0.7.0-gamma3" }
leptos_server = { path = "./leptos_server", version = "0.7.0-gamma3" }
leptos_meta = { path = "./meta", version = "0.7.0-gamma3" }
next_tuple = { path = "./next_tuple", version = "0.1.0-gamma3" }
oco_ref = { path = "./oco", version = "0.2.0" }
or_poisoned = { path = "./or_poisoned", version = "0.1.0" }
reactive_graph = { path = "./reactive_graph", version = "0.1.0-rc1" }
reactive_stores = { path = "./reactive_stores", version = "0.1.0-rc1" }
reactive_stores_macro = { path = "./reactive_stores_macro", version = "0.1.0-rc1" }
server_fn = { path = "./server_fn", version = "0.7.0-rc1" }
server_fn_macro = { path = "./server_fn_macro", version = "0.7.0-rc1" }
server_fn_macro_default = { path = "./server_fn/server_fn_macro_default", version = "0.7.0-rc1" }
tachys = { path = "./tachys", version = "0.1.0-rc1" }
reactive_graph = { path = "./reactive_graph", version = "0.1.0-gamma3" }
reactive_stores = { path = "./reactive_stores", version = "0.1.0-gamma3" }
reactive_stores_macro = { path = "./reactive_stores_macro", version = "0.1.0-gamma3" }
server_fn = { path = "./server_fn", version = "0.7.0-gamma3" }
server_fn_macro = { path = "./server_fn_macro", version = "0.7.0-gamma3" }
server_fn_macro_default = { path = "./server_fn/server_fn_macro_default", version = "0.7.0-gamma3" }
tachys = { path = "./tachys", version = "0.1.0-gamma3" }
[profile.release]
codegen-units = 1

View File

@@ -159,7 +159,9 @@ Sure! Obviously the `view` macro is for generating DOM nodes but you can use the
- Use event listeners to update signals
- Create effects to update the UI
The 0.7 update originally set out to create a "generic rendering" approach that would allow us to reuse most of the same view logic to do all of the above. Unfortunately, this has had to be shelved for now due to difficulties encountered by the Rust compiler when building larger-scale applications with the number of generics spread throughout the codebase that this required. It's an approach I'm looking forward to exploring again in the future; feel free to reach out if you're interested in this kind of work.
I've put together a [very simple GTK example](https://github.com/leptos-rs/leptos/blob/main/examples/gtk/src/main.rs) so you can see what I mean.
The new rendering approach being developed for 0.7 supports “universal rendering,” i.e., it can use any rendering library that supports a small set of 6-8 functions. (This is intended as a layer over typical retained-mode, OOP-style GUI toolkits like the DOM, GTK, etc.) That future rendering work will allow creating native UI in a way that is much more similar to the declarative approach used by the web framework.
### How is this different from Yew?

View File

@@ -1,6 +1,6 @@
[package]
name = "throw_error"
version = "0.2.0-rc1"
version = "0.2.0-gamma3"
authors = ["Greg Johnston"]
license = "MIT"
readme = "../README.md"
@@ -10,4 +10,4 @@ rust-version.workspace = true
edition.workspace = true
[dependencies]
pin-project-lite = "0.2.15"
pin-project-lite = "0.2.14"

View File

@@ -10,14 +10,14 @@ edition.workspace = true
[dependencies]
async-executor = { version = "1.13.1", optional = true }
futures = "0.3.31"
glib = { version = "0.20.5", optional = true }
thiserror = "2.0"
tokio = { version = "1.41", optional = true, default-features = false, features = [
futures = "0.3.30"
glib = { version = "0.20.0", optional = true }
thiserror = "1.0"
tokio = { version = "1.39", optional = true, default-features = false, features = [
"rt",
] }
tracing = { version = "0.1.40", optional = true }
wasm-bindgen-futures = { version = "0.4.45", optional = true }
wasm-bindgen-futures = { version = "0.4.42", optional = true }
[features]
async-executor = ["dep:async-executor"]

View File

@@ -291,10 +291,9 @@ impl Executor {
///
/// Returns `Err(_)` if an executor has already been set.
pub fn init_custom_executor(
custom_executor: impl CustomExecutor + Send + Sync + 'static,
custom_executor: impl CustomExecutor + 'static,
) -> Result<(), ExecutorError> {
static EXECUTOR: OnceLock<Box<dyn CustomExecutor + Send + Sync>> =
OnceLock::new();
static EXECUTOR: OnceLock<Box<dyn CustomExecutor>> = OnceLock::new();
EXECUTOR
.set(Box::new(custom_executor))
.map_err(|_| ExecutorError::AlreadySet)?;
@@ -312,46 +311,13 @@ impl Executor {
.map_err(|_| ExecutorError::AlreadySet)?;
Ok(())
}
/// Locally sets a custom executor as the executor used to spawn tasks
/// in the current thread.
///
/// Returns `Err(_)` if an executor has already been set.
pub fn init_local_custom_executor(
custom_executor: impl CustomExecutor + 'static,
) -> Result<(), ExecutorError> {
thread_local! {
static EXECUTOR: OnceLock<Box<dyn CustomExecutor>> = OnceLock::new();
}
EXECUTOR.with(|this| {
this.set(Box::new(custom_executor))
.map_err(|_| ExecutorError::AlreadySet)
})?;
SPAWN
.set(|fut| {
EXECUTOR.with(|this| this.get().unwrap().spawn(fut));
})
.map_err(|_| ExecutorError::AlreadySet)?;
SPAWN_LOCAL
.set(|fut| {
EXECUTOR.with(|this| this.get().unwrap().spawn_local(fut));
})
.map_err(|_| ExecutorError::AlreadySet)?;
POLL_LOCAL
.set(|| {
EXECUTOR.with(|this| this.get().unwrap().poll_local());
})
.map_err(|_| ExecutorError::AlreadySet)?;
Ok(())
}
}
/// A trait for custom executors.
/// Custom executors can be used to integrate with any executor that supports spawning futures.
///
/// All methods can be called recursively.
pub trait CustomExecutor {
pub trait CustomExecutor: Send + Sync {
/// Spawns a future, usually on a thread pool.
fn spawn(&self, fut: PinnedFuture<()>);
/// Spawns a local future. May require calling `poll_local` to make progress.

View File

@@ -10,4 +10,4 @@ rust-version.workspace = true
edition.workspace = true
[dependencies]
pin-project-lite = "0.2.15"
pin-project-lite = "0.2.14"

View File

@@ -26,7 +26,6 @@ async fn main() {
};
use axum_js_ssr::app::*;
use http_body_util::BodyExt;
use leptos::logging::log;
use leptos::prelude::*;
use leptos_axum::{generate_route_list, LeptosRoutes};

View File

@@ -1,5 +1,3 @@
#![allow(dead_code)]
use counter::*;
use leptos::mount::mount_to;
use leptos::prelude::*;

View File

@@ -63,7 +63,7 @@ async fn main() -> std::io::Result<()> {
</html>
}
}})
.service(Files::new("/", site_root.as_ref()))
.service(Files::new("/", site_root))
})
.bind(&addr)?
.run()

View File

@@ -1,5 +1,3 @@
#![allow(dead_code)]
use counter_without_macros::counter;
use leptos::{prelude::*, task::tick};
use pretty_assertions::assert_eq;

View File

@@ -1,5 +1,3 @@
#![allow(dead_code)]
use wasm_bindgen::JsCast;
use wasm_bindgen_test::*;

View File

@@ -1,5 +1,3 @@
#![allow(dead_code)]
use directives::App;
use leptos::{prelude::*, task::tick};
use wasm_bindgen::JsCast;

View File

@@ -6,7 +6,9 @@ use leptos_axum::ResponseOptions;
// A basic function to display errors served by the error boundaries.
// Feel free to do more complicated things here than just displaying them.
#[component]
pub fn ErrorTemplate(#[prop(into)] errors: Signal<Errors>) -> impl IntoView {
pub fn ErrorTemplate(
#[prop(into)] errors: MaybeSignal<Errors>,
) -> impl IntoView {
// Get Errors from Signal
// Downcast lets us take a type that implements `std::error::Error`
let errors = Memo::new(move |_| {

View File

@@ -4,7 +4,7 @@ mod routes;
use leptos_meta::{provide_meta_context, Link, Meta, Stylesheet};
use leptos_router::{
components::{FlatRoutes, Route, Router, RoutingProgress},
OptionalParamSegment, ParamSegment, StaticSegment,
ParamSegment, StaticSegment,
};
use routes::{nav::*, stories::*, story::*, users::*};
use std::time::Duration;
@@ -28,7 +28,9 @@ pub fn App() -> impl IntoView {
<FlatRoutes fallback=|| "Not found.">
<Route path=(StaticSegment("users"), ParamSegment("id")) view=User/>
<Route path=(StaticSegment("stories"), ParamSegment("id")) view=Story/>
<Route path=OptionalParamSegment("stories") view=Stories/>
<Route path=ParamSegment("stories") view=Stories/>
// TODO allow optional params without duplication
<Route path=StaticSegment("") view=Stories/>
</FlatRoutes>
</main>
</Router>

View File

@@ -56,7 +56,7 @@ async fn main() -> std::io::Result<()> {
</html>
}
}})
.service(Files::new("/", site_root.as_ref()))
.service(Files::new("/", site_root))
//.wrap(middleware::Compress::default())
})
.bind(&addr)?

View File

@@ -4,7 +4,7 @@ mod routes;
use leptos_meta::{provide_meta_context, Link, Meta, MetaTags, Stylesheet};
use leptos_router::{
components::{FlatRoutes, Route, Router, RoutingProgress},
OptionalParamSegment, ParamSegment, StaticSegment,
ParamSegment, StaticSegment,
};
use routes::{nav::*, stories::*, story::*, users::*};
use std::time::Duration;
@@ -46,7 +46,9 @@ pub fn App() -> impl IntoView {
<FlatRoutes fallback=|| "Not found.">
<Route path=(StaticSegment("users"), ParamSegment("id")) view=User/>
<Route path=(StaticSegment("stories"), ParamSegment("id")) view=Story/>
<Route path=OptionalParamSegment("stories") view=Stories/>
<Route path=ParamSegment("stories") view=Stories/>
// TODO allow optional params without duplication
<Route path=StaticSegment("") view=Stories/>
</FlatRoutes>
</main>
</Router>

View File

@@ -4,7 +4,7 @@ mod routes;
use leptos_meta::{provide_meta_context, Link, Meta, MetaTags, Stylesheet};
use leptos_router::{
components::{FlatRoutes, Route, Router},
OptionalParamSegment, ParamSegment, StaticSegment,
ParamSegment, StaticSegment,
};
use routes::{nav::*, stories::*, story::*, users::*};
#[cfg(feature = "ssr")]
@@ -42,7 +42,9 @@ pub fn App() -> impl IntoView {
<FlatRoutes fallback=|| "Not found.">
<Route path=(StaticSegment("users"), ParamSegment("id")) view=User/>
<Route path=(StaticSegment("stories"), ParamSegment("id")) view=Story/>
<Route path=OptionalParamSegment("stories") view=Stories/>
<Route path=ParamSegment("stories") view=Stories/>
// TODO allow optional params without duplication
<Route path=StaticSegment("") view=Stories/>
</FlatRoutes>
</main>
</Router>

View File

@@ -4,7 +4,7 @@ mod routes;
use leptos_meta::{provide_meta_context, Link, Meta, MetaTags, Stylesheet};
use leptos_router::{
components::{FlatRoutes, Route, Router, RoutingProgress},
OptionalParamSegment, ParamSegment, StaticSegment,
ParamSegment, StaticSegment,
};
use routes::{nav::*, stories::*, story::*, users::*};
use std::time::Duration;
@@ -46,7 +46,9 @@ pub fn App() -> impl IntoView {
<FlatRoutes fallback=|| "Not found.">
<Route path=(StaticSegment("users"), ParamSegment("id")) view=User/>
<Route path=(StaticSegment("stories"), ParamSegment("id")) view=Story/>
<Route path=OptionalParamSegment("stories") view=Stories/>
<Route path=ParamSegment("stories") view=Stories/>
// TODO allow optional params without duplication
<Route path=StaticSegment("") view=Stories/>
</FlatRoutes>
</main>
</Router>

View File

@@ -44,8 +44,8 @@ window.addEventListener("click", async (ev) => {
// TODO parse from the request stream instead?
const doc = parser.parseFromString(htmlString, 'text/html');
// The 'doc' variable now contains the parsed DOM
const transition = async () => {
// The 'doc' variable now contains the parsed DOM
const transition = document.startViewTransition(async () => {
const oldDocWalker = document.createTreeWalker(document);
const newDocWalker = doc.createTreeWalker(doc);
let oldNode = oldDocWalker.currentNode;
@@ -128,13 +128,8 @@ window.addEventListener("click", async (ev) => {
}
} }
}
};
// Not all browsers support startViewTransition; see https://caniuse.com/?search=startViewTransition
if (document.startViewTransition) {
await document.startViewTransition(transition);
} else {
await transition()
}
});
await transition;
window.history.pushState(undefined, null, url);
});

View File

@@ -6,7 +6,7 @@ fn main() {
_ = console_log::init_with_level(log::Level::Debug);
console_error_panic_hook::set_once();
let handle = mount_to(
document()
helpers::document()
.get_element_by_id("app")
.unwrap()
.unchecked_into(),

View File

@@ -1,5 +1,3 @@
#![allow(dead_code)]
use portal::App;
use wasm_bindgen::JsCast;
use wasm_bindgen_test::*;

View File

@@ -10,7 +10,7 @@ struct Then {
// the type with Option<...> and marking the option as #[prop(optional)].
#[slot]
struct ElseIf {
cond: Signal<bool>,
cond: MaybeSignal<bool>,
children: ChildrenFn,
}
@@ -22,7 +22,7 @@ struct Fallback {
// Slots are added to components like any other prop.
#[component]
fn SlotIf(
cond: Signal<bool>,
cond: MaybeSignal<bool>,
then: Then,
#[prop(default=vec![])] else_if: Vec<ElseIf>,
#[prop(optional)] fallback: Option<Fallback>,
@@ -43,9 +43,9 @@ fn SlotIf(
#[component]
pub fn App() -> impl IntoView {
let (count, set_count) = signal(0);
let is_even = Signal::derive(move || count.get() % 2 == 0);
let is_div5 = Signal::derive(move || count.get() % 5 == 0);
let is_div7 = Signal::derive(move || count.get() % 7 == 0);
let is_even = MaybeSignal::derive(move || count.get() % 2 == 0);
let is_div5 = MaybeSignal::derive(move || count.get() % 5 == 0);
let is_div7 = MaybeSignal::derive(move || count.get() % 7 == 0);
view! {
<button on:click=move |_| set_count.update(|value| *value += 1)>"+1"</button>

View File

@@ -39,7 +39,7 @@ async fn main() -> std::io::Result<()> {
</html>
}
}})
.service(Files::new("/", site_root.as_ref()))
.service(Files::new("/", site_root))
//.wrap(middleware::Compress::default())
})
.bind(&addr)?

View File

@@ -2,7 +2,6 @@
#[tokio::main]
async fn main() {
use axum::Router;
use leptos::logging::log;
use leptos::prelude::*;
use leptos_axum::{generate_route_list, LeptosRoutes};
use ssr_modes_axum::app::*;

View File

@@ -2,7 +2,6 @@
#[tokio::main]
async fn main() {
use axum::Router;
use leptos::logging::log;
use leptos::prelude::*;
use leptos_axum::{generate_route_list_with_ssg, LeptosRoutes};
use static_routing::app::*;

View File

@@ -1,7 +1,6 @@
use std::sync::atomic::{AtomicUsize, Ordering};
use chrono::{Local, NaiveDate};
use leptos::logging::warn;
use leptos::prelude::*;
use reactive_stores::{Field, Patch, Store};
use serde::{Deserialize, Serialize};
@@ -110,7 +109,11 @@ pub fn App() -> impl IntoView {
// directly implements IntoIterator, so we can use it in <For/> and
// it will manage reactivity for the store fields correctly
<For
each=move || store.todos()
each=move || {
leptos::logging::log!("RERUNNING FOR CALCULATION");
store.todos()
}
key=|row| row.id().get()
let:todo
>

View File

@@ -10,7 +10,6 @@ crate-type = ["cdylib", "rlib"]
actix-files = { version = "0.6.6", optional = true }
actix-web = { version = "4.8", optional = true, features = ["macros"] }
console_error_panic_hook = "0.1.7"
js-sys = { version = "0.3.70", optional = true }
leptos = { path = "../../leptos" }
leptos_actix = { path = "../../integrations/actix", optional = true }
leptos_router = { path = "../../router" }
@@ -20,10 +19,7 @@ serde = "1.0"
tokio = { version = "1.39", features = ["time", "rt"], optional = true }
[features]
hydrate = [
"dep:js-sys",
"leptos/hydrate",
]
hydrate = ["leptos/hydrate"]
ssr = [
"dep:actix-files",
"dep:actix-web",

View File

@@ -1,94 +0,0 @@
@check_instrumented
Feature: Instrumented Counters showing the expected values
Scenario: I can fresh CSR instrumented counters
Given I see the app
When I access the instrumented counters via CSR
Then I see the following counters under section
| Suspend Calls | |
| item_listing | 0 |
| item_overview | 0 |
| item_inspect | 0 |
And the following counters under section
| Server Calls (CSR) | |
| list_items | 0 |
| get_item | 0 |
| inspect_item_root | 0 |
| inspect_item_field | 0 |
Scenario: I should see counter going up after viewing Item Listing
Given I see the app
When I select the following links
| Instrumented |
| Item Listing |
| Counters |
Then I see the following counters under section
| Suspend Calls | |
| item_listing | 1 |
| item_overview | 0 |
| item_inspect | 0 |
And the following counters under section
| Server Calls (CSR) | |
| list_items | 1 |
| get_item | 0 |
| inspect_item_root | 0 |
| inspect_item_field | 0 |
# the reload has happened in Item Listing, it follows a suspend
# will be called as hydration happens.
Scenario: Refreshing Item Listing should have only suspend counters
Given I see the app
When I access the instrumented counters via SSR
And I select the component Item Listing
And I reload the page
And I select the component Counters
Then I see the following counters under section
| Suspend Calls | |
| item_listing | 1 |
| item_overview | 0 |
| item_inspect | 0 |
And the following counters under section
| Server Calls (CSR) | |
| list_items | 0 |
| get_item | 0 |
| inspect_item_root | 0 |
| inspect_item_field | 0 |
Scenario: Reset CSR Counters work as expected.
Given I see the app
When I access the instrumented counters via SSR
And I select the component Item Listing
And I click on Reset CSR Counters
And I select the component Counters
Then I see the following counters under section
| Suspend Calls | |
| item_listing | 0 |
| item_overview | 0 |
| item_inspect | 0 |
And the following counters under section
| Server Calls (CSR) | |
| list_items | 0 |
| get_item | 0 |
| inspect_item_root | 0 |
| inspect_item_field | 0 |
Scenario: Standard usage of the instruments traversing down
Given I see the app
When I select the following links
| Instrumented |
| Item Listing |
| Item 2 |
| Inspect path3 |
| Inspect path3/field1 |
And I access the instrumented counters via CSR
Then I see the following counters under section
| Suspend Calls | |
| item_listing | 1 |
| item_overview | 1 |
| item_inspect | 2 |
And the following counters under section
| Server Calls (CSR) | |
| list_items | 1 |
| get_item | 1 |
| inspect_item_root | 1 |
| inspect_item_field | 1 |

View File

@@ -1,187 +0,0 @@
@check_instrumented_suspense_resource
Feature: Using instrumented counters for real
Check that the suspend/suspense and the underlying resources are
called with the expected number of times for CSR rendering.
Background:
Given I see the app
And I select the mode Instrumented
Scenario: Emulate steps 1 to 5 of issue #2961
Given I select the link Target 3##
And I refresh the page
When I select the following links
| Item Listing |
| Target 4## |
And I go check the Counters
Then I see the following counters under section
| Suspend Calls | |
| item_listing | 1 |
| item_overview | 2 |
| item_inspect | 0 |
And the following counters under section
| Server Calls (CSR) | |
| list_items | 0 |
| get_item | 1 |
| inspect_item_root | 0 |
| inspect_item_field | 0 |
Scenario: Emulate step 6 of issue #2961
Given I select the link Target 41#
And I refresh the page
When I select the following links
| Target 4## |
| Target 42# |
And I go check the Counters
Then I see the following counters under section
| Suspend Calls | |
| item_listing | 0 |
| item_overview | 1 |
| item_inspect | 2 |
And the following counters under section
| Server Calls (CSR) | |
| list_items | 0 |
| get_item | 0 |
| inspect_item_root | 1 |
| inspect_item_field | 0 |
Scenario: Emulate step 7 of issue #2961
Given I select the link Target 42#
And I refresh the page
When I select the following links
| Target 4## |
| Target 42# |
| Target 41# |
And I go check the Counters
Then I see the following counters under section
| Suspend Calls | |
| item_listing | 0 |
| item_overview | 1 |
| item_inspect | 3 |
And the following counters under section
| Server Calls (CSR) | |
| list_items | 0 |
| get_item | 0 |
| inspect_item_root | 2 |
| inspect_item_field | 0 |
Scenario: Emulate step 8, "not trigger double fetch".
Given I select the link Target 3##
And I refresh the page
When I select the following links
| Item Listing |
| Target 4## |
| Target 41# |
And I go check the Counters
Then I see the following counters under section
| Suspend Calls | |
| item_listing | 1 |
| item_overview | 2 |
| item_inspect | 1 |
And the following counters under section
| Server Calls (CSR) | |
| list_items | 0 |
| get_item | 1 |
| inspect_item_root | 1 |
| inspect_item_field | 0 |
Scenario: Like above, for the "double fetch" which shouldn't happen
Given I select the link Target 3##
And I refresh the page
When I select the following links
| Item Listing |
| Target 4## |
| Target 41# |
| Target 3## |
And I go check the Counters
Then I see the following counters under section
| Suspend Calls | |
| item_listing | 1 |
| item_overview | 3 |
| item_inspect | 1 |
And the following counters under section
| Server Calls (CSR) | |
| list_items | 0 |
| get_item | 2 |
| inspect_item_root | 1 |
| inspect_item_field | 0 |
Scenario: Like above, but using 4## instead
Given I select the link Target 3##
And I refresh the page
When I select the following links
| Item Listing |
| Target 4## |
| Target 41# |
| Target 4## |
And I go check the Counters
Then I see the following counters under section
| Suspend Calls | |
| item_listing | 1 |
| item_overview | 3 |
| item_inspect | 1 |
And the following counters under section
| Server Calls (CSR) | |
| list_items | 0 |
| get_item | 1 |
| inspect_item_root | 1 |
| inspect_item_field | 0 |
# The following tests previously showed the clear difference between
# hydration and CSR, where hydration resulting in extra server API
# calls via the resource while CSR did not suffer from the issue.
# With #3182 merged the issue is corrected, going up to components
# specified by the parent route should no longer result in the
# superfluous fetches for resources needed by component about to be
# unmounted.
Scenario: Emulate part of step 8 of issue #2961
Given I select the link Target 3##
And I refresh the page
When I select the link Item Listing
And I go check the Counters
Then I see the following counters under section
| Server Calls (CSR) | |
| list_items | 0 |
| get_item | 0 |
| inspect_item_root | 0 |
| inspect_item_field | 0 |
Scenario: Emulate above, instead of refresh page, reset csr counters
Given I select the link Target 3##
And I click on Reset CSR Counters
When I select the link Item Listing
And I go check the Counters
Then I see the following counters under section
| Server Calls (CSR) | |
| list_items | 0 |
| get_item | 0 |
| inspect_item_root | 0 |
| inspect_item_field | 0 |
# Further two sets for good measure.
Scenario: Start with hydration from Target 41# and go up
Given I select the link Target 41#
And I refresh the page
When I select the link Target 4##
And I select the link Item Listing
And I go check the Counters
Then I see the following counters under section
| Server Calls (CSR) | |
| list_items | 0 |
| get_item | 0 |
| inspect_item_root | 0 |
| inspect_item_field | 0 |
Scenario: Emulate the same csr counter reset, for Target 41#.
Given I select the link Target 41#
And I click on Reset CSR Counters
When I select the link Target 4##
And I select the link Item Listing
And I go check the Counters
Then I see the following counters under section
| Server Calls (CSR) | |
| list_items | 0 |
| get_item | 0 |
| inspect_item_root | 0 |
| inspect_item_field | 0 |

View File

@@ -37,19 +37,3 @@ pub async fn click_second_button(client: &Client) -> Result<()> {
Ok(())
}
pub async fn click_reset_counters_button(client: &Client) -> Result<()> {
let reset_counter = find::reset_counter(client).await?;
reset_counter.click().await?;
Ok(())
}
pub async fn click_reset_csr_counters_button(client: &Client) -> Result<()> {
let reset_counter = find::reset_csr_counter(client).await?;
reset_counter.click().await?;
Ok(())
}

View File

@@ -63,21 +63,3 @@ pub async fn second_count_is(client: &Client, expected: u32) -> Result<()> {
Ok(())
}
pub async fn instrumented_counts(
client: &Client,
expected: &[(&str, u32)],
) -> Result<()> {
let mut actual = Vec::<(&str, u32)>::new();
for (selector, _) in expected.iter() {
actual.push((
selector,
find::instrumented_count(client, selector).await?,
))
}
assert_eq!(actual, expected);
Ok(())
}

View File

@@ -77,43 +77,6 @@ pub async fn second_button(client: &Client) -> Result<Element> {
Ok(counter_button)
}
pub async fn instrumented_count(
client: &Client,
selector: &str,
) -> Result<u32> {
let element = client
.wait()
.for_element(Locator::Id(selector))
.await
.expect(format!("Element #{selector} not found.")
.as_str());
let text = element.text().await?;
let count = text.parse::<u32>()
.expect(format!("Element #{selector} does not contain a number.")
.as_str());
Ok(count)
}
pub async fn reset_counter(client: &Client) -> Result<Element> {
let reset_button = client
.wait()
.for_element(Locator::Id("reset-counters"))
.await
.expect("Reset counter input not found");
Ok(reset_button)
}
pub async fn reset_csr_counter(client: &Client) -> Result<Element> {
let reset_button = client
.wait()
.for_element(Locator::Id("reset-csr-counters"))
.await
.expect("Reset CSR counter input not found");
Ok(reset_button)
}
async fn component_message(client: &Client, id: &str) -> Result<String> {
let element =
client.wait().for_element(Locator::Id(id)).await.expect(

View File

@@ -1,6 +1,6 @@
use crate::fixtures::{action, world::AppWorld};
use anyhow::{Ok, Result};
use cucumber::{given, when, gherkin::Step};
use cucumber::{given, when};
#[given("I see the app")]
#[when("I open the app")]
@@ -12,13 +12,19 @@ async fn i_open_the_app(world: &mut AppWorld) -> Result<()> {
}
#[given(regex = r"^I select the mode (.*)$")]
async fn i_select_the_mode(world: &mut AppWorld, text: String) -> Result<()> {
let client = &world.client;
action::click_link(client, &text).await?;
Ok(())
}
#[given(regex = r"^I select the component (.*)$")]
#[when(regex = "^I select the component (.*)$")]
#[given(regex = "^I select the link (.*)$")]
#[when(regex = "^I select the link (.*)$")]
#[when(regex = "^I click on the link (.*)$")]
#[when(regex = "^I go check the (.*)$")]
async fn i_select_the_link(world: &mut AppWorld, text: String) -> Result<()> {
async fn i_select_the_component(
world: &mut AppWorld,
text: String,
) -> Result<()> {
let client = &world.client;
action::click_link(client, &text).await?;
@@ -53,69 +59,3 @@ async fn i_click_the_second_button_n_times(
Ok(())
}
#[given(regex = "^I (refresh|reload) the (browser|page)$")]
#[when(regex = "^I (refresh|reload) the (browser|page)$")]
async fn i_refresh_the_browser(world: &mut AppWorld) -> Result<()> {
let client = &world.client;
client.refresh().await?;
Ok(())
}
#[when(expr = "I click on Reset Counters")]
async fn i_click_on_reset_counters(world: &mut AppWorld) -> Result<()> {
let client = &world.client;
action::click_reset_counters_button(client).await?;
Ok(())
}
#[given(expr = "I click on Reset CSR Counters")]
#[when(expr = "I click on Reset CSR Counters")]
async fn i_click_on_reset_csr_counters(world: &mut AppWorld) -> Result<()> {
let client = &world.client;
action::click_reset_csr_counters_button(client).await?;
Ok(())
}
#[when(expr = "I access the instrumented counters via SSR")]
async fn i_access_the_instrumented_counters_page_via_ssr(
world: &mut AppWorld,
) -> Result<()> {
let client = &world.client;
action::click_link(client, "Instrumented").await?;
action::click_link(client, "Counters").await?;
client.refresh().await?;
Ok(())
}
#[when(expr = "I access the instrumented counters via CSR")]
async fn i_access_the_instrumented_counters_page_via_csr(
world: &mut AppWorld,
) -> Result<()> {
let client = &world.client;
action::click_link(client, "Instrumented").await?;
action::click_link(client, "Counters").await?;
Ok(())
}
#[given(expr = "I select the following links")]
#[when(expr = "I select the following links")]
async fn i_select_the_following_links(
world: &mut AppWorld,
step: &Step,
) -> Result<()> {
let client = &world.client;
if let Some(table) = step.table.as_ref() {
for row in table.rows.iter() {
action::click_link(client, &row[0]).await?;
}
}
Ok(())
}

View File

@@ -1,6 +1,6 @@
use crate::fixtures::{check, world::AppWorld};
use anyhow::{Ok, Result};
use cucumber::{then, gherkin::Step};
use cucumber::then;
#[then(regex = r"^I see the page title is (.*)$")]
async fn i_see_the_page_title_is(
@@ -79,23 +79,3 @@ async fn i_see_the_second_count_is(
Ok(())
}
#[then(expr = "I see the following counters under section")]
#[then(expr = "the following counters under section")]
async fn i_see_the_following_counters_under_section(
world: &mut AppWorld,
step: &Step,
) -> Result<()> {
// FIXME ideally check the mode; for now leave it because effort
let client = &world.client;
if let Some(table) = step.table.as_ref() {
let expected = table.rows
.iter()
.skip(1)
.map(|row| (row[0].as_str(), row[1].parse::<u32>().unwrap()))
.collect::<Vec<_>>();
check::instrumented_counts(client, &expected).await?;
}
Ok(())
}

View File

@@ -1,4 +1,3 @@
use crate::instrumented::InstrumentedRoutes;
use leptos::prelude::*;
use leptos_router::{
components::{Outlet, ParentRoute, Redirect, Route, Router, Routes, A},
@@ -42,7 +41,6 @@ pub fn App() -> impl IntoView {
<A href="/out-of-order">"Out-of-Order"</A>
<A href="/in-order">"In-Order"</A>
<A href="/async">"Async"</A>
<A href="/instrumented/">"Instrumented"</A>
</nav>
<main>
<Routes fallback=|| "Page not found.">
@@ -112,7 +110,6 @@ pub fn App() -> impl IntoView {
<Route path=StaticSegment("local") view=LocalResource/>
<Route path=StaticSegment("none") view=None/>
</ParentRoute>
<InstrumentedRoutes/>
</Routes>
</main>
</Router>

View File

@@ -1,667 +0,0 @@
use leptos::prelude::*;
use leptos_router::{
components::{ParentRoute, Route, A},
hooks::use_params,
nested_router::Outlet,
params::Params,
MatchNestedRoutes, ParamSegment, SsrMode, StaticSegment, WildcardSegment,
};
#[cfg(feature = "ssr")]
pub(super) mod counter {
use std::{
collections::HashMap,
sync::{
atomic::{AtomicU32, Ordering},
LazyLock, Mutex,
},
};
#[derive(Default)]
pub struct Counter(AtomicU32);
impl Counter {
pub const fn new() -> Self {
Self(AtomicU32::new(0))
}
pub fn get(&self) -> u32 {
self.0.load(Ordering::SeqCst)
}
pub fn inc(&self) -> u32 {
self.0.fetch_add(1, Ordering::SeqCst)
}
pub fn reset(&self) {
self.0.store(0, Ordering::SeqCst);
}
}
#[derive(Default)]
pub struct Counters {
pub list_items: Counter,
pub get_item: Counter,
pub inspect_item_root: Counter,
pub inspect_item_field: Counter,
}
impl From<&mut Counters> for super::Counters {
fn from(counter: &mut Counters) -> Self {
Self {
get_item: counter.get_item.get(),
inspect_item_root: counter.inspect_item_root.get(),
inspect_item_field: counter.inspect_item_field.get(),
list_items: counter.list_items.get(),
}
}
}
impl Counters {
pub fn reset(&self) {
self.get_item.reset();
self.inspect_item_root.reset();
self.inspect_item_field.reset();
self.list_items.reset();
}
}
pub static COUNTERS: LazyLock<Mutex<HashMap<u64, Counters>>> =
LazyLock::new(|| Mutex::new(HashMap::new()));
}
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
pub struct Item {
id: i64,
name: Option<String>,
field: Option<String>,
}
#[server]
async fn list_items(ticket: u64) -> Result<Vec<i64>, ServerFnError> {
// emulate database query overhead
tokio::time::sleep(std::time::Duration::from_millis(25)).await;
(*counter::COUNTERS)
.lock()
.expect("somehow panicked elsewhere")
.entry(ticket)
.or_default()
.list_items
.inc();
Ok(vec![1, 2, 3, 4])
}
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
pub struct GetItemResult(pub Item, pub Vec<String>);
#[server]
async fn get_item(
ticket: u64,
id: i64,
) -> Result<GetItemResult, ServerFnError> {
// emulate database query overhead
tokio::time::sleep(std::time::Duration::from_millis(25)).await;
(*counter::COUNTERS)
.lock()
.expect("somehow panicked elsewhere")
.entry(ticket)
.or_default()
.get_item
.inc();
let name = None::<String>;
let field = None::<String>;
Ok(GetItemResult(
Item { id, name, field },
["path1", "path2", "path3"]
.into_iter()
.map(str::to_string)
.collect::<Vec<_>>(),
))
}
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
pub struct InspectItemResult(pub Item, pub String, pub Vec<String>);
#[server]
async fn inspect_item(
ticket: u64,
id: i64,
path: String,
) -> Result<InspectItemResult, ServerFnError> {
// emulate database query overhead
tokio::time::sleep(std::time::Duration::from_millis(25)).await;
let mut split = path.split('/');
let name = split.next().map(str::to_string);
let path = name
.clone()
.expect("name should have been defined at this point");
let field = split
.next()
.and_then(|s| (!s.is_empty()).then(|| s.to_string()));
if field.is_none() {
(*counter::COUNTERS)
.lock()
.expect("somehow panicked elsewhere")
.entry(ticket)
.or_default()
.inspect_item_root
.inc();
} else {
(*counter::COUNTERS)
.lock()
.expect("somehow panicked elsewhere")
.entry(ticket)
.or_default()
.inspect_item_field
.inc();
}
Ok(InspectItemResult(
Item { id, name, field },
path,
["field1", "field2", "field3"]
.into_iter()
.map(str::to_string)
.collect::<Vec<_>>(),
))
}
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
pub struct Counters {
pub get_item: u32,
pub inspect_item_root: u32,
pub inspect_item_field: u32,
pub list_items: u32,
}
#[server]
async fn get_counters(ticket: u64) -> Result<Counters, ServerFnError> {
Ok((*counter::COUNTERS)
.lock()
.expect("somehow panicked elsewhere")
.entry(ticket)
.or_default()
.into())
}
#[server(ResetCounters)]
async fn reset_counters(ticket: u64) -> Result<(), ServerFnError> {
(*counter::COUNTERS)
.lock()
.expect("somehow panicked elsewhere")
.entry(ticket)
.or_default()
.reset();
// leptos::logging::log!("counters for ticket {ticket} have been reset");
Ok(())
}
#[derive(Clone, Default)]
pub struct SuspenseCounters {
item_overview: u32,
item_inspect: u32,
item_listing: u32,
}
#[component]
pub fn InstrumentedRoutes() -> impl 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/>
<ParentRoute path=StaticSegment("item") view=ItemRoot>
<Route path=StaticSegment("/") view=ItemListing/>
<ParentRoute path=ParamSegment("id") view=ItemTop>
<Route path=StaticSegment("/") view=ItemOverview/>
<Route path=WildcardSegment("path") view=ItemInspect/>
</ParentRoute>
</ParentRoute>
<Route path=StaticSegment("counters") view=ShowCounters/>
</ParentRoute>
}
.into_inner()
}
#[derive(Copy, Clone)]
pub struct Ticket(pub u64);
#[derive(Copy, Clone)]
pub struct CSRTicket(pub u64);
#[cfg(feature = "ssr")]
fn inst_ticket() -> u64 {
// SSR will always use 0 for the ticket
0
}
#[cfg(not(feature = "ssr"))]
fn inst_ticket() -> u64 {
// CSR will use a random number for the ticket
(js_sys::Math::random() * ((u64::MAX - 1) as f64) + 1f64) as u64
}
#[component]
fn InstrumentedRoot() -> impl IntoView {
let counters = RwSignal::new(SuspenseCounters::default());
provide_context(counters);
provide_field_nav_portlet_context();
// Generate a ID directly on this component. Rather than relying on
// additional server functions, doing it this way emulates more
// standard workflows better and to avoid having to add another
// thing to instrument/interfere with the typical use case.
// Downside is that randomness has a chance to conflict.
//
// Furthermore, this approach **will** result in unintuitive
// behavior when it isn't accounted for - specifically, the reason
// for this design is that when SSR it will guarantee usage of `0`
// as the ticket, while CSR it will be of some other value as the
// version it uses will be random. However, when trying to get back
// the counters associated with the ticket, rendering using SSR will
// always produce the SSR version and this quirk will need to be
// accounted for.
let ticket = inst_ticket();
// leptos::logging::log!(
// "Ticket for this InstrumentedRoot instance: {ticket}"
// );
provide_context(Ticket(ticket));
let csr_ticket = RwSignal::<Option<CSRTicket>>::new(None);
let reset_counters = ServerAction::<ResetCounters>::new();
Effect::new(move |_| {
let ticket = expect_context::<Ticket>().0;
csr_ticket.set(Some(CSRTicket(ticket)));
});
view! {
<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>
</nav>
<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>
<footer>
<nav>
<A href="item/3/">"Target 3##"</A>
<A href="item/4/">"Target 4##"</A>
<A href="item/4/path1/">"Target 41#"</A>
<A href="item/4/path2/">"Target 42#"</A>
<A href="item/4/path2/field1">"Target 421"</A>
<A href="item/1/path2/field3">"Target 123"</A>
</nav>
</footer>
</section>
}
}
#[component]
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>
<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>
</ul>
}
}
#[component]
fn ItemRoot() -> impl IntoView {
let ticket = expect_context::<Ticket>().0;
provide_context(Resource::new_blocking(
move || (),
move |_| async move { list_items(ticket).await },
));
view! {
<h2>"<ItemRoot/>"</h2>
<Outlet/>
}
}
#[component]
fn ItemListing() -> impl IntoView {
let suspense_counters = expect_context::<RwSignal<SuspenseCounters>>();
let resource =
expect_context::<Resource<Result<Vec<i64>, ServerFnError>>>();
let item_listing = move || {
Suspend::new(async move {
let result = resource.await.map(|items| items
.into_iter()
.map(move |item|
// FIXME seems like relative link isn't working, it is currently
// 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>
}
)
.collect_view()
);
suspense_counters.update_untracked(|c| c.item_listing += 1);
result
})
};
view! {
<h3>"<ItemListing/>"</h3>
<ul>
<Suspense>
{item_listing}
</Suspense>
</ul>
}
}
#[derive(Params, PartialEq, Clone, Debug)]
struct ItemTopParams {
id: Option<i64>,
}
#[component]
fn ItemTop() -> impl IntoView {
let ticket = expect_context::<Ticket>().0;
let params = use_params::<ItemTopParams>();
// map result to an option as the focus isn't error rendering
provide_context(Resource::new_blocking(
move || params.get().map(|p| p.id),
move |id| async move {
match id {
Err(_) => None,
Ok(Some(id)) => get_item(ticket, id).await.ok(),
_ => None,
}
},
));
view! {
<h4>"<ItemTop/>"</h4>
<Outlet/>
}
}
#[component]
fn ItemOverview() -> impl IntoView {
let suspense_counters = expect_context::<RwSignal<SuspenseCounters>>();
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>
});
suspense_counters.update_untracked(|c| c.item_overview += 1);
result
})
};
view! {
<h5>"<ItemOverview/>"</h5>
<Suspense>
{item_view}
</Suspense>
}
}
#[derive(Params, PartialEq, Clone, Debug)]
struct ItemInspectParams {
path: Option<String>,
}
#[component]
fn ItemInspect() -> impl IntoView {
let ticket = expect_context::<Ticket>().0;
let suspense_counters = expect_context::<RwSignal<SuspenseCounters>>();
let params = use_params::<ItemInspectParams>();
let res_overview = expect_context::<Resource<Option<GetItemResult>>>();
let res_inspect = Resource::new_blocking(
move || params.get().map(|p| p.path),
move |p| async move {
// leptos::logging::log!("res_inspect: res_overview.await");
let overview = res_overview.await;
// leptos::logging::log!("res_inspect: resolved res_overview.await");
// let result =
match (overview, p) {
(Some(item), Ok(Some(path))) => {
// leptos::logging::log!("res_inspect: inspect_item().await");
inspect_item(ticket, item.0.id, path.clone()).await.ok()
}
_ => None,
}
// ;
// leptos::logging::log!("res_inspect: resolved inspect_item().await");
// result
},
);
on_cleanup(|| {
if let Some(c) = use_context::<WriteSignal<Option<FieldNavCtx>>>() {
c.set(None);
}
});
let inspect_view = move || {
// leptos::logging::log!("inspect_view closure invoked");
Suspend::new(async move {
// leptos::logging::log!("inspect_view Suspend::new() called");
let result = res_inspect.await.map(|InspectItemResult(item, name, fields)| {
// leptos::logging::log!("inspect_view res_inspect awaited");
let id = item.id;
expect_context::<WriteSignal<Option<FieldNavCtx>>>().set(Some(
fields.iter()
.map(|field| FieldNavItem {
href: format!("/instrumented/item/{id}/{name}/{field}"),
text: field.to_string(),
})
.collect::<Vec<_>>()
.into()
));
view! {
<p>{format!("Inspecting {item:?}")}</p>
<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>
// }
view! {
<li><a href=format!("/instrumented/item/{id}/{name}/{field}")>{
format!("Inspect {name}/{field}")
}</a></li>
}
})
.collect_view()
}</ul>
}
});
suspense_counters.update_untracked(|c| c.item_inspect += 1);
// leptos::logging::log!(
// "returning result, result.is_some() = {}, count = {}",
// result.is_some(),
// suspense_counters.get().item_inspect,
// );
result
})
};
view! {
<h5>"<ItemInspect/>"</h5>
<Suspense>
{inspect_view}
</Suspense>
}
}
#[component]
fn ShowCounters() -> impl IntoView {
// There is _weirdness_ in this view. The `Server Calls` counters
// will be acquired via the expected mode and be rendered as such.
//
// However, upon `Reset Counters`, the mode from which the reset
// was issued will result in the rendering be reflected as such, so
// if the intial state was SSR, resetting under CSR will result in
// the CSR counters be rendered after. However for the intents and
// purpose for the testing only the CSR is cared for.
//
// At the end of the day, it is possible to have both these be
// separated out, but for the purpose of this test the focus is not
// on the SSR side of things (at least until further regression is
// discovered that affects SSR directly).
let ticket = expect_context::<Ticket>().0;
let suspense_counters = expect_context::<RwSignal<SuspenseCounters>>();
let reset_counters = ServerAction::<ResetCounters>::new();
let res_counter = Resource::new(
move || reset_counters.version().get(),
move |_| async move {
(
get_counters(ticket).await,
if ticket == 0 { "SSR" } else { "CSR" }.to_string(),
ticket,
)
},
);
let counter_view = move || {
Suspend::new(async move {
// ensure current mode and ticket are both updated
let (counters, mode, ticket) = res_counter.await;
counters.map(|counters| {
let clear_suspense_counters = move |_| {
suspense_counters.update(|c| {
// leptos::logging::log!("resetting suspense counters");
*c = SuspenseCounters::default();
});
};
view! {
<h3 id="server-calls">"Server Calls ("{mode}")"</h3>
<dl>
<dt>"list_items"</dt>
<dd id="list_items">{counters.list_items}</dd>
<dt>"get_item"</dt>
<dd id="get_item">{counters.get_item}</dd>
<dt>"inspect_item_root"</dt>
<dd id="inspect_item_root">{counters.inspect_item_root}</dd>
<dt>"inspect_item_field"</dt>
<dd id="inspect_item_field">{counters.inspect_item_field}</dd>
</dl>
<ActionForm action=reset_counters>
<input type="hidden" name="ticket" value=format!("{ticket}") />
<input
id="reset-counters"
type="submit"
value="Reset Counters"
on:click=clear_suspense_counters/>
</ActionForm>
}
})
})
};
view! {
<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>
})}
<Suspense>
{counter_view}
</Suspense>
}
}
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug, PartialEq)]
pub struct FieldNavItem {
pub href: String,
pub text: String,
}
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug, PartialEq)]
pub struct FieldNavCtx(pub Option<Vec<FieldNavItem>>);
impl From<Vec<FieldNavItem>> for FieldNavCtx {
fn from(item: Vec<FieldNavItem>) -> Self {
Self(Some(item))
}
}
#[component]
pub fn FieldNavPortlet() -> impl IntoView {
let ctx = expect_context::<ReadSignal<Option<FieldNavCtx>>>();
move || {
let ctx = ctx.get();
ctx.map(|ctx| {
view! {
<div id="FieldNavPortlet">
<span>"FieldNavPortlet:"</span>
<nav>{
ctx.0.map(|ctx| {
ctx.into_iter()
.map(|FieldNavItem { href, text }| {
view! {
<A href=href>{text}</A>
}
})
.collect_view()
})
}</nav>
</div>
}
})
}
}
pub fn provide_field_nav_portlet_context() {
// wrapping the Ctx in an Option allows better ergonomics whenever it isn't needed
let (ctx, set_ctx) = signal(None::<FieldNavCtx>);
provide_context(ctx);
provide_context(set_ctx);
}

View File

@@ -1,5 +1,4 @@
pub mod app;
mod instrumented;
#[cfg(feature = "hydrate")]
#[wasm_bindgen::prelude::wasm_bindgen]

View File

@@ -41,7 +41,7 @@ async fn main() -> std::io::Result<()> {
</html>
}
}})
.service(Files::new("/", site_root.as_ref()))
.service(Files::new("/", site_root))
})
.bind(addr)?
.workers(1)

View File

@@ -1,7 +1,7 @@
import { test, expect } from "@playwright/test";
test("homepage has title 'Leptos + Tailwindcss'", async ({ page }) => {
test("should see the welcome message", async ({ page }) => {
await page.goto("http://localhost:3000/");
await expect(page).toHaveTitle("Leptos + Tailwindcss");
await expect(page.locator("h2")).toHaveText("Welcome to Leptos with Tailwind");
});

View File

@@ -22,29 +22,24 @@ pub fn App() -> impl IntoView {
#[component]
fn Home() -> impl IntoView {
let (value, set_value) = signal(0);
let (count, set_count) = signal(0);
// thanks to https://tailwindcomponents.com/component/blue-buttons-example for the showcase layout
view! {
<Title text="Leptos + Tailwindcss"/>
<main>
<div class="bg-gradient-to-tl from-blue-800 to-blue-500 text-white font-mono flex flex-col min-h-screen">
<div class="flex flex-row-reverse flex-wrap m-auto">
<button on:click=move |_| set_value.update(|value| *value += 1) class="rounded px-3 py-2 m-1 border-b-4 border-l-2 shadow-lg bg-blue-700 border-blue-800 text-white">
"+"
</button>
<button class="rounded px-3 py-2 m-1 border-b-4 border-l-2 shadow-lg bg-blue-800 border-blue-900 text-white">
{value}
</button>
<button
on:click=move |_| set_value.update(|value| *value -= 1)
class="rounded px-3 py-2 m-1 border-b-4 border-l-2 shadow-lg bg-blue-700 border-blue-800 text-white"
class:invisible=move || {value.get() < 1}
>
"-"
</button>
</div>
</div>
<main class="my-0 mx-auto max-w-3xl text-center">
<h2 class="p-6 text-4xl">"Welcome to Leptos with Tailwind"</h2>
<p class="px-10 pb-10 text-left">"Tailwind will scan your Rust files for Tailwind class names and compile them into a CSS file."</p>
<button
class="bg-amber-600 hover:bg-sky-700 px-5 py-3 text-white rounded-lg"
on:click=move |_| set_count.update(|count| *count += 1)
>
"Something's here | "
{move || if count.get() == 0 {
"Click me!".to_string()
} else {
count.get().to_string()
}}
" | Some more text"
</button>
</main>
}
}

View File

@@ -40,7 +40,7 @@ async fn main() -> std::io::Result<()> {
</html>
}
}})
.service(Files::new("/", site_root.as_ref()))
.service(Files::new("/", site_root))
.wrap(middleware::Compress::default())
})
.bind(&addr)?

View File

@@ -1,10 +1,7 @@
/** @type {import('tailwindcss').Config} */
module.exports = {
content: {
content: {
files: ["*.html", "./src/**/*.rs"],
transform: {
rs: (content) => content.replace(/(?:^|\s)class:/g, ' '),
},
},
theme: {
extend: {},

View File

@@ -1,7 +1,9 @@
import { test, expect } from "@playwright/test";
test("homepage has title 'Leptos + Tailwindcss'", async ({ page }) => {
test("homepage has title and links to intro page", async ({ page }) => {
await page.goto("http://localhost:3000/");
await expect(page).toHaveTitle("Leptos + Tailwindcss");
await expect(page).toHaveTitle("Welcome to Leptos");
await expect(page.locator("h1")).toHaveText("Welcome to Leptos!");
});

View File

@@ -54,11 +54,7 @@ fn Home() -> impl IntoView {
<button class="rounded px-3 py-2 m-1 border-b-4 border-l-2 shadow-lg bg-blue-800 border-blue-900 text-white">
{value}
</button>
<button
on:click=move |_| set_value.update(|value| *value -= 1)
class="rounded px-3 py-2 m-1 border-b-4 border-l-2 shadow-lg bg-blue-700 border-blue-800 text-white"
class:invisible=move || {value.get() < 1}
>
<button on:click=move |_| set_value.update(|value| *value -= 1) class="rounded px-3 py-2 m-1 border-b-4 border-l-2 shadow-lg bg-blue-700 border-blue-800 text-white">
"-"
</button>
</div>

View File

@@ -1,13 +1,9 @@
/** @type {import('tailwindcss').Config} */
module.exports = {
content: {
files: ["*.html", "./src/**/*.rs"],
transform: {
rs: (content) => content.replace(/(?:^|\s)class:/g, ' '),
},
},
content: ["*.html", "./src/**/*.rs",],
theme: {
extend: {},
},
plugins: [],
}

View File

@@ -1,7 +1,9 @@
import { test, expect } from "@playwright/test";
test("homepage has title 'Leptos + Tailwindcss'", async ({ page }) => {
test("homepage has title and links to intro page", async ({ page }) => {
await page.goto("http://localhost:8080/");
await expect(page).toHaveTitle("Leptos + Tailwindcss");
await expect(page).toHaveTitle("Leptos • Counter with Tailwind");
await expect(page.locator("h2")).toHaveText("Welcome to Leptos with Tailwind");
});

View File

@@ -22,29 +22,24 @@ pub fn App() -> impl IntoView {
#[component]
fn Home() -> impl IntoView {
let (value, set_value) = signal(0);
let (count, set_count) = signal(0);
// thanks to https://tailwindcomponents.com/component/blue-buttons-example for the showcase layout
view! {
<Title text="Leptos + Tailwindcss"/>
<main>
<div class="bg-gradient-to-tl from-blue-800 to-blue-500 text-white font-mono flex flex-col min-h-screen">
<div class="flex flex-row-reverse flex-wrap m-auto">
<button on:click=move |_| set_value.update(|value| *value += 1) class="rounded px-3 py-2 m-1 border-b-4 border-l-2 shadow-lg bg-blue-700 border-blue-800 text-white">
"+"
</button>
<button class="rounded px-3 py-2 m-1 border-b-4 border-l-2 shadow-lg bg-blue-800 border-blue-900 text-white">
{value}
</button>
<button
on:click=move |_| set_value.update(|value| *value -= 1)
class="rounded px-3 py-2 m-1 border-b-4 border-l-2 shadow-lg bg-blue-700 border-blue-800 text-white"
class:invisible=move || {value.get() < 1}
>
"-"
</button>
</div>
</div>
</main>
<div class="my-0 mx-auto max-w-3xl text-center">
<h2 class="p-6 text-4xl">"Welcome to Leptos with Tailwind"</h2>
<p class="px-10 pb-10 text-left">"Tailwind will scan your Rust files for Tailwind class names and compile them into a CSS file."</p>
<button
class="bg-amber-600 hover:bg-sky-700 px-5 py-3 text-white rounded-lg"
on:click=move |_| set_count.update(|count| *count += 1)
>
"Something's here | "
{move || if count.get() == 0 {
"Click me!".to_string()
} else {
count.get().to_string()
}}
" | Some more text"
</button>
</div>
}
}

View File

@@ -1,10 +1,7 @@
/** @type {import('tailwindcss').Config} */
module.exports = {
content: {
content: {
files: ["*.html", "./src/**/*.rs"],
transform: {
rs: (content) => content.replace(/(?:^|\s)class:/g, ' '),
},
},
theme: {
extend: {},

View File

@@ -38,7 +38,7 @@ pub fn TimerDemo() -> impl IntoView {
pub fn use_interval<T, F>(interval_millis: T, f: F)
where
F: Fn() + Clone + 'static,
T: Into<Signal<u64>> + 'static,
T: Into<MaybeSignal<u64>> + 'static,
{
let interval_millis = interval_millis.into();
Effect::new(move |prev_handle: Option<IntervalHandle>| {

View File

@@ -59,7 +59,7 @@ async fn main() -> std::io::Result<()> {
</html>
}
}})
.service(Files::new("/", site_root.as_ref()))
.service(Files::new("/", site_root))
//.wrap(middleware::Compress::default())
})
.bind(&addr)?

View File

@@ -16,15 +16,15 @@ leptos_router = { path = "../../router" }
leptos_integration_utils = { path = "../../integrations/utils", optional = true }
serde = { version = "1.0", features = ["derive"] }
axum = { version = "0.7.5", optional = true }
tower = { version = "0.5.1", features = ["util"], optional = true }
tower-http = { version = "0.6.1", features = ["fs"], optional = true }
tower = { version = "0.4.13", optional = true }
tower-http = { version = "0.5.2", features = ["fs"], optional = true }
tokio = { version = "1.39", features = ["full"], optional = true }
http = { version = "1.1" }
sqlx = { version = "0.8.0", features = [
"runtime-tokio-rustls",
"sqlite",
], optional = true }
thiserror = "2.0"
thiserror = "1.0"
wasm-bindgen = "0.2.93"
[features]

View File

@@ -9,7 +9,7 @@ use leptos::{
hydration::{AutoReload, HydrationScripts},
prelude::*,
};
use tower::util::ServiceExt;
use tower::ServiceExt;
use tower_http::services::ServeDir;
pub async fn file_or_index_handler(

View File

@@ -1,6 +1,6 @@
[package]
name = "hydration_context"
version = "0.2.0-rc1"
version = "0.2.0-gamma3"
authors = ["Greg Johnston"]
license = "MIT"
readme = "../README.md"
@@ -12,12 +12,12 @@ edition.workspace = true
[dependencies]
throw_error = { workspace = true }
or_poisoned = { workspace = true }
futures = "0.3.31"
futures = "0.3.30"
serde = { version = "1.0", features = ["derive"] }
wasm-bindgen = { version = "0.2.95", optional = true }
js-sys = { version = "0.3.72", optional = true }
once_cell = "1.20"
pin-project-lite = "0.2.15"
wasm-bindgen = { version = "0.2.93", optional = true }
js-sys = { version = "0.3.69", optional = true }
once_cell = "1.19"
pin-project-lite = "0.2.14"
[features]
browser = ["dep:wasm-bindgen", "dep:js-sys"]

View File

@@ -44,18 +44,6 @@ pub type PinnedStream<T> = Pin<Box<dyn Stream<Item = T> + Send + Sync>>;
/// from the server to the client.
pub struct SerializedDataId(usize);
impl SerializedDataId {
/// Create a new instance of [`SerializedDataId`].
pub fn new(id: usize) -> Self {
SerializedDataId(id)
}
/// Consume into the inner usize identifier.
pub fn into_inner(self) -> usize {
self.0
}
}
impl From<SerializedDataId> for ErrorId {
fn from(value: SerializedDataId) -> Self {
value.0.into()

View File

@@ -58,27 +58,6 @@ impl SsrSharedContext {
..Default::default()
}
}
/// Consume the data buffers, awaiting all async resources,
/// returning both sync and async buffers.
/// Useful to implement custom hydration contexts.
///
/// WARNING: this will clear the internal buffers, it should only be called once.
/// A second call would return an empty `vec![]`.
pub async fn consume_buffers(&self) -> Vec<(SerializedDataId, String)> {
let sync_data = mem::take(&mut *self.sync_buf.write().or_poisoned());
let async_data = mem::take(&mut *self.async_buf.write().or_poisoned());
let mut all_data = Vec::new();
for resolved in sync_data {
all_data.push((resolved.0, resolved.1));
}
for (id, fut) in async_data {
let data = fut.await;
all_data.push((id, data));
}
all_data
}
}
impl Debug for SsrSharedContext {

View File

@@ -9,10 +9,10 @@ rust-version.workspace = true
edition.workspace = true
[dependencies]
actix-http = "3.9"
actix-http = "3.8"
actix-files = "0.6"
actix-web = "4.9"
futures = "0.3.31"
actix-web = "4.8"
futures = "0.3.30"
any_spawner = { workspace = true, features = ["tokio"] }
hydration_context = { workspace = true }
leptos = { workspace = true, features = ["nonce", "ssr"] }
@@ -24,7 +24,7 @@ server_fn = { workspace = true, features = ["actix"] }
serde_json = "1.0"
parking_lot = "0.12.3"
tracing = { version = "0.1", optional = true }
tokio = { version = "1.41", features = ["rt", "fs"] }
tokio = { version = "1.39", features = ["rt", "fs"] }
send_wrapper = "0.6.0"
dashmap = "6"
once_cell = "1"

View File

@@ -1,5 +1,4 @@
#![forbid(unsafe_code)]
#![deny(missing_docs)]
//! Provides functions to easily integrate Leptos with Actix.
//!
@@ -10,6 +9,7 @@
use actix_files::NamedFile;
use actix_http::header::{HeaderName, HeaderValue, ACCEPT, LOCATION, REFERER};
use actix_web::{
body::BoxBody,
dev::{ServiceFactory, ServiceRequest},
http::header,
test,
@@ -35,7 +35,7 @@ use leptos_router::{
components::provide_server_redirect,
location::RequestUrl,
static_routes::{RegenerationFn, ResolvedStaticPath},
ExpandOptionals, Method, PathSegment, RouteList, RouteListing, SsrMode,
Method, PathSegment, RouteList, RouteListing, SsrMode,
};
use once_cell::sync::Lazy;
use parking_lot::RwLock;
@@ -44,7 +44,6 @@ use server_fn::{
redirect::REDIRECT_HEADER, request::actix::ActixRequest, ServerFnError,
};
use std::{
collections::HashSet,
fmt::{Debug, Display},
future::Future,
ops::{Deref, DerefMut},
@@ -56,10 +55,8 @@ use std::{
/// Typically contained inside of a ResponseOptions. Setting this is useful for cookies and custom responses.
#[derive(Debug, Clone, Default)]
pub struct ResponseParts {
/// If provided, this will overwrite any other status code for this response.
pub status: Option<StatusCode>,
/// The map of headers that should be added to the response.
pub headers: header::HeaderMap,
pub status: Option<StatusCode>,
}
impl ResponseParts {
@@ -88,12 +85,10 @@ impl ResponseParts {
pub struct Request(SendWrapper<HttpRequest>);
impl Request {
/// Wraps an existing Actix request.
pub fn new(req: &HttpRequest) -> Self {
Self(SendWrapper::new(req.clone()))
}
/// Consumes the wrapper and returns the inner Actix request.
pub fn into_inner(self) -> HttpRequest {
self.0.take()
}
@@ -303,7 +298,7 @@ pub fn redirect(path: &str) {
/// ## Provided Context Types
/// This function always provides context values including the following types:
/// - [ResponseOptions]
/// - [Request]
/// - [HttpRequest](actix_web::HttpRequest)
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "trace", fields(error), skip_all)
@@ -330,7 +325,7 @@ pub fn handle_server_fns() -> Route {
/// ## Provided Context Types
/// This function always provides context values including the following types:
/// - [ResponseOptions]
/// - [Request]
/// - [HttpRequest](actix_web::HttpRequest)
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "trace", fields(error), skip_all)
@@ -463,7 +458,7 @@ pub fn handle_server_fns_with_context(
/// ## Provided Context Types
/// This function always provides context values including the following types:
/// - [ResponseOptions]
/// - [Request]
/// - [HttpRequest](actix_web::HttpRequest)
/// - [MetaContext](leptos_meta::MetaContext)
/// - [RouterIntegrationContext](leptos_router::RouterIntegrationContext)
#[cfg_attr(
@@ -533,7 +528,8 @@ where
/// ## Provided Context Types
/// This function always provides context values including the following types:
/// - [ResponseOptions]
/// - [Request]
/// - [HttpRequest](actix_web::HttpRequest)
/// - [MetaContext](leptos_meta::MetaContext)
/// - [RouterIntegrationContext](leptos_router::RouterIntegrationContext)
#[cfg_attr(
feature = "tracing",
@@ -597,7 +593,9 @@ where
/// ## Provided Context Types
/// This function always provides context values including the following types:
/// - [ResponseOptions]
/// - [Request]
/// - [HttpRequest](actix_web::HttpRequest)
/// - [MetaContext](leptos_meta::MetaContext)
/// - [RouterIntegrationContext](leptos_router::RouterIntegrationContext)
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "trace", fields(error), skip_all)
@@ -621,7 +619,9 @@ where
/// ## Provided Context Types
/// This function always provides context values including the following types:
/// - [ResponseOptions]
/// - [Request]
/// - [HttpRequest](actix_web::HttpRequest)
/// - [MetaContext](leptos_meta::MetaContext)
/// - [RouterIntegrationContext](leptos_router::RouterIntegrationContext)
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "trace", fields(error), skip_all)
@@ -656,7 +656,9 @@ where
/// ## Provided Context Types
/// This function always provides context values including the following types:
/// - [ResponseOptions]
/// - [Request]
/// - [HttpRequest](actix_web::HttpRequest)
/// - [MetaContext](leptos_meta::MetaContext)
/// - [RouterIntegrationContext](leptos_router::RouterIntegrationContext)
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "trace", fields(error), skip_all)
@@ -688,7 +690,7 @@ where
/// ## Provided Context Types
/// This function always provides context values including the following types:
/// - [ResponseOptions]
/// - [Request]
/// - [HttpRequest](actix_web::HttpRequest)
/// - [MetaContext](leptos_meta::MetaContext)
/// - [RouterIntegrationContext](leptos_router::RouterIntegrationContext)
#[cfg_attr(
@@ -721,7 +723,9 @@ where
/// ## Provided Context Types
/// This function always provides context values including the following types:
/// - [ResponseOptions]
/// - [Request]
/// - [HttpRequest](actix_web::HttpRequest)
/// - [MetaContext](leptos_meta::MetaContext)
/// - [RouterIntegrationContext](leptos_router::RouterIntegrationContext)
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "trace", fields(error), skip_all)
@@ -896,7 +900,7 @@ trait ActixPath {
fn to_actix_path(&self) -> String;
}
impl ActixPath for Vec<PathSegment> {
impl ActixPath for &[PathSegment] {
fn to_actix_path(&self) -> String {
let mut path = String::new();
for segment in self.iter() {
@@ -918,14 +922,6 @@ impl ActixPath for Vec<PathSegment> {
path.push_str(":.*}");
}
PathSegment::Unit => {}
PathSegment::OptionalParam(_) => {
#[cfg(feature = "tracing")]
tracing::error!(
"to_axum_path should only be called on expanded \
paths, which do not have OptionalParam any longer"
);
Default::default()
}
}
}
path
@@ -939,38 +935,25 @@ pub struct ActixRouteListing {
mode: SsrMode,
methods: Vec<leptos_router::Method>,
regenerate: Vec<RegenerationFn>,
exclude: bool,
}
trait IntoRouteListing: Sized {
fn into_route_listing(self) -> Vec<ActixRouteListing>;
}
impl IntoRouteListing for RouteListing {
fn into_route_listing(self) -> Vec<ActixRouteListing> {
self.path()
.to_vec()
.expand_optionals()
.into_iter()
.map(|path| {
let path = path.to_actix_path();
let path = if path.is_empty() {
"/".to_string()
} else {
path
};
let mode = self.mode();
let methods = self.methods().collect();
let regenerate = self.regenerate().into();
ActixRouteListing {
path,
mode: mode.clone(),
methods,
regenerate,
exclude: false,
}
})
.collect()
impl From<RouteListing> for ActixRouteListing {
fn from(value: RouteListing) -> Self {
let path = value.path().to_actix_path();
let path = if path.is_empty() {
"/".to_string()
} else {
path
};
let mode = value.mode();
let methods = value.methods().collect();
let regenerate = value.regenerate().into();
Self {
path,
mode: mode.clone(),
methods,
regenerate,
}
}
}
@@ -987,7 +970,6 @@ impl ActixRouteListing {
mode,
methods: methods.into_iter().collect(),
regenerate: regenerate.into(),
exclude: false,
}
}
@@ -1045,37 +1027,27 @@ where
let mut routes = routes
.into_inner()
.into_iter()
.flat_map(IntoRouteListing::into_route_listing)
.map(ActixRouteListing::from)
.collect::<Vec<_>>();
let routes = if routes.is_empty() {
vec![ActixRouteListing::new(
"/".to_string(),
Default::default(),
[leptos_router::Method::Get],
vec![],
)]
} else {
// Routes to exclude from auto generation
if let Some(excluded_routes) = &excluded_routes {
routes.retain(|p| !excluded_routes.iter().any(|e| e == p.path()))
}
routes
};
let excluded =
excluded_routes
.into_iter()
.flatten()
.map(|path| ActixRouteListing {
path,
mode: Default::default(),
methods: Vec::new(),
regenerate: Vec::new(),
exclude: true,
});
(routes.into_iter().chain(excluded).collect(), generator)
(
if routes.is_empty() {
vec![ActixRouteListing::new(
"/".to_string(),
Default::default(),
[leptos_router::Method::Get],
vec![],
)]
} else {
// Routes to exclude from auto generation
if let Some(excluded_routes) = excluded_routes {
routes
.retain(|p| !excluded_routes.iter().any(|e| e == p.path()))
}
routes
},
generator,
)
}
/// Allows generating any prerendered routes.
@@ -1314,12 +1286,14 @@ where
web::get().to(handler)
}
pub enum DataResponse<T> {
Data(T),
Response(actix_web::dev::Response<BoxBody>),
}
/// This trait allows one to pass a list of routes and a render function to Actix's router, letting us avoid
/// having to use wildcards or manually define all routes in multiple places.
pub trait LeptosRoutes {
/// Adds routes to the Axum router that have either
/// 1) been generated by `leptos_router`, or
/// 2) handle a server function.
fn leptos_routes<IV>(
self,
paths: Vec<ActixRouteListing>,
@@ -1328,12 +1302,6 @@ pub trait LeptosRoutes {
where
IV: IntoView + 'static;
/// Adds routes to the Axum router that have either
/// 1) been generated by `leptos_router`, or
/// 2) handle a server function.
///
/// Runs `additional_context` to provide additional data to the reactive system via context,
/// when handling a route.
fn leptos_routes_with_context<IV>(
self,
paths: Vec<ActixRouteListing>,
@@ -1385,24 +1353,15 @@ where
{
let mut router = self;
let excluded = paths
.iter()
.filter(|&p| p.exclude)
.map(|p| p.path.as_str())
.collect::<HashSet<_>>();
// register server functions first to allow for wildcard route in Leptos's Router
for (path, _) in server_fn::actix::server_fn_paths() {
if !excluded.contains(path) {
let additional_context = additional_context.clone();
let handler =
handle_server_fns_with_context(additional_context);
router = router.route(path, handler);
}
let additional_context = additional_context.clone();
let handler = handle_server_fns_with_context(additional_context);
router = router.route(path, handler);
}
// register routes defined in Leptos's Router
for listing in paths.iter().filter(|p| !p.exclude) {
for listing in paths.iter() {
let path = listing.path();
let mode = listing.mode();
@@ -1498,24 +1457,15 @@ impl LeptosRoutes for &mut ServiceConfig {
{
let mut router = self;
let excluded = paths
.iter()
.filter(|&p| p.exclude)
.map(|p| p.path.as_str())
.collect::<HashSet<_>>();
// register server functions first to allow for wildcard route in Leptos's Router
for (path, _) in server_fn::actix::server_fn_paths() {
if !excluded.contains(path) {
let additional_context = additional_context.clone();
let handler =
handle_server_fns_with_context(additional_context);
router = router.route(path, handler);
}
let additional_context = additional_context.clone();
let handler = handle_server_fns_with_context(additional_context);
router = router.route(path, handler);
}
// register routes defined in Leptos's Router
for listing in paths.iter().filter(|p| !p.exclude) {
for listing in paths.iter() {
let path = listing.path();
let mode = listing.mode();
@@ -1604,10 +1554,7 @@ where
ServerFnError::new("HttpRequest should have been provided via context")
})?;
SendWrapper::new(async move {
T::extract(&req)
.await
.map_err(|e| ServerFnError::ServerError(e.to_string()))
})
.await
T::extract(&req)
.await
.map_err(|e| ServerFnError::ServerError(e.to_string()))
}

View File

@@ -11,11 +11,11 @@ edition.workspace = true
[dependencies]
any_spawner = { workspace = true, features = ["tokio"] }
hydration_context = { workspace = true }
axum = { version = "0.7.7", default-features = false, features = [
axum = { version = "0.7.5", default-features = false, features = [
"matched-path",
] }
dashmap = "6"
futures = "0.3.31"
futures = "0.3.30"
leptos = { workspace = true, features = ["nonce", "ssr"] }
server_fn = { workspace = true, features = ["axum-no-default"] }
leptos_macro = { workspace = true, features = ["axum"] }
@@ -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 }
tower = { version = "0.5.1", features = ["util"] }
tower-http = "0.6.1"
tokio = { version = "1.39", default-features = false }
tower = { version = "0.4.13", features = ["util"] }
tower-http = "0.5.2"
tracing = { version = "0.1.40", optional = true }
[dev-dependencies]
axum = "0.7.7"
tokio = { version = "1.41", features = ["net", "rt-multi-thread"] }
axum = "0.7.5"
tokio = { version = "1.39", features = ["net", "rt-multi-thread"] }
[features]
wasm = []

View File

@@ -1,6 +1,4 @@
#![forbid(unsafe_code)]
#![deny(missing_docs)]
//! Provides functions to easily integrate Leptos with Axum.
//!
//! ## JS Fetch Integration
@@ -65,9 +63,10 @@ use leptos_meta::ServerMetaContext;
#[cfg(feature = "default")]
use leptos_router::static_routes::ResolvedStaticPath;
use leptos_router::{
components::provide_server_redirect, location::RequestUrl,
static_routes::RegenerationFn, ExpandOptionals, PathSegment, RouteList,
RouteListing, SsrMode,
components::provide_server_redirect,
location::RequestUrl,
static_routes::{RegenerationFn, StaticParamsMap},
PathSegment, RouteList, RouteListing, SsrMode,
};
#[cfg(feature = "default")]
use once_cell::sync::Lazy;
@@ -75,7 +74,7 @@ use parking_lot::RwLock;
use server_fn::{redirect::REDIRECT_HEADER, ServerFnError};
#[cfg(feature = "default")]
use std::path::Path;
use std::{collections::HashSet, fmt::Debug, io, pin::Pin, sync::Arc};
use std::{fmt::Debug, io, pin::Pin, sync::Arc};
#[cfg(feature = "default")]
use tower::util::ServiceExt;
#[cfg(feature = "default")]
@@ -86,9 +85,7 @@ use tower_http::services::ServeDir;
/// Typically contained inside of a ResponseOptions. Setting this is useful for cookies and custom responses.
#[derive(Debug, Clone, Default)]
pub struct ResponseParts {
/// If provided, this will overwrite any other status code for this response.
pub status: Option<StatusCode>,
/// The map of headers that should be added to the response.
pub headers: HeaderMap,
}
@@ -435,7 +432,6 @@ async fn handle_server_fns_inner(
.expect("could not build Response")
}
/// A stream of bytes of HTML.
pub type PinnedHtmlStream =
Pin<Box<dyn Stream<Item = io::Result<Bytes>> + Send>>;
@@ -1211,6 +1207,32 @@ where
generate_route_list_with_exclusions_and_ssg(app_fn, excluded_routes).0
}
/// Builds all routes that have been defined using [`StaticRoute`].
#[allow(unused)]
pub async fn build_static_routes<IV>(
options: &LeptosOptions,
app_fn: impl Fn() -> IV + 'static + Send + Clone,
routes: &[RouteListing],
static_data_map: StaticParamsMap,
) where
IV: IntoView + 'static,
{
todo!()
/*
let options = options.clone();
let routes = routes.to_owned();
spawn_task!(async move {
leptos_router::build_static_routes(
&options,
app_fn,
&routes,
&static_data_map,
)
.await
.expect("could not build static routes")
});*/
}
/// Generates a list of all routes defined in Leptos's Router in your app. We can then use this to automatically
/// create routes in Axum's Router without having to use wildcard matching or fallbacks. Takes in your root app Element
/// as an argument so it can walk you app tree. This version is tailored to generate Axum compatible paths. Adding excluded_routes
@@ -1241,38 +1263,25 @@ pub struct AxumRouteListing {
methods: Vec<leptos_router::Method>,
#[allow(unused)]
regenerate: Vec<RegenerationFn>,
exclude: bool,
}
trait IntoRouteListing: Sized {
fn into_route_listing(self) -> Vec<AxumRouteListing>;
}
impl IntoRouteListing for RouteListing {
fn into_route_listing(self) -> Vec<AxumRouteListing> {
self.path()
.to_vec()
.expand_optionals()
.into_iter()
.map(|path| {
let path = path.to_axum_path();
let path = if path.is_empty() {
"/".to_string()
} else {
path
};
let mode = self.mode();
let methods = self.methods().collect();
let regenerate = self.regenerate().into();
AxumRouteListing {
path,
mode: mode.clone(),
methods,
regenerate,
exclude: false,
}
})
.collect()
impl From<RouteListing> for AxumRouteListing {
fn from(value: RouteListing) -> Self {
let path = value.path().to_axum_path();
let path = if path.is_empty() {
"/".to_string()
} else {
path
};
let mode = value.mode();
let methods = value.methods().collect();
let regenerate = value.regenerate().into();
Self {
path,
mode: mode.clone(),
methods,
regenerate,
}
}
}
@@ -1289,7 +1298,6 @@ impl AxumRouteListing {
mode,
methods: methods.into_iter().collect(),
regenerate: regenerate.into(),
exclude: false,
}
}
@@ -1352,36 +1360,27 @@ where
let mut routes = routes
.into_inner()
.into_iter()
.flat_map(IntoRouteListing::into_route_listing)
.map(AxumRouteListing::from)
.collect::<Vec<_>>();
let routes = if routes.is_empty() {
vec![AxumRouteListing::new(
"/".to_string(),
Default::default(),
[leptos_router::Method::Get],
vec![],
)]
} else {
// Routes to exclude from auto generation
if let Some(excluded_routes) = &excluded_routes {
routes.retain(|p| !excluded_routes.iter().any(|e| e == p.path()))
}
routes
};
let excluded =
excluded_routes
.into_iter()
.flatten()
.map(|path| AxumRouteListing {
path,
mode: Default::default(),
methods: Vec::new(),
regenerate: Vec::new(),
exclude: true,
});
(routes.into_iter().chain(excluded).collect(), generator)
(
if routes.is_empty() {
vec![AxumRouteListing::new(
"/".to_string(),
Default::default(),
[leptos_router::Method::Get],
vec![],
)]
} else {
// Routes to exclude from auto generation
if let Some(excluded_routes) = excluded_routes {
routes
.retain(|p| !excluded_routes.iter().any(|e| e == p.path()))
}
routes
},
generator,
)
}
/// Allows generating any prerendered routes.
@@ -1661,9 +1660,6 @@ where
S: Clone + Send + Sync + 'static,
LeptosOptions: FromRef<S>,
{
/// Adds routes to the Axum router that have either
/// 1) been generated by `leptos_router`, or
/// 2) handle a server function.
fn leptos_routes<IV>(
self,
options: &S,
@@ -1673,12 +1669,6 @@ where
where
IV: IntoView + 'static;
/// Adds routes to the Axum router that have either
/// 1) been generated by `leptos_router`, or
/// 2) handle a server function.
///
/// Runs `additional_context` to provide additional data to the reactive system via context,
/// when handling a route.
fn leptos_routes_with_context<IV>(
self,
options: &S,
@@ -1689,8 +1679,6 @@ where
where
IV: IntoView + 'static;
/// Extends the Axum router with the given paths, and handles the requests with the given
/// handler.
fn leptos_routes_with_handler<H, T>(
self,
paths: Vec<AxumRouteListing>,
@@ -1705,7 +1693,7 @@ trait AxumPath {
fn to_axum_path(&self) -> String;
}
impl AxumPath for Vec<PathSegment> {
impl AxumPath for &[PathSegment] {
fn to_axum_path(&self) -> String {
let mut path = String::new();
for segment in self.iter() {
@@ -1725,14 +1713,6 @@ impl AxumPath for Vec<PathSegment> {
path.push_str(s);
}
PathSegment::Unit => {}
PathSegment::OptionalParam(_) => {
#[cfg(feature = "tracing")]
tracing::error!(
"to_axum_path should only be called on expanded \
paths, which do not have OptionalParam any longer"
);
Default::default()
}
}
}
path
@@ -1788,41 +1768,32 @@ where
let mut router = self;
let excluded = paths
.iter()
.filter(|&p| p.exclude)
.map(|p| p.path.as_str())
.collect::<HashSet<_>>();
// register server functions
for (path, method) in server_fn::axum::server_fn_paths() {
let cx_with_state = cx_with_state.clone();
let handler = move |req: Request<Body>| async move {
handle_server_fns_with_context(cx_with_state, req).await
};
if !excluded.contains(path) {
router = router.route(
path,
match method {
Method::GET => get(handler),
Method::POST => post(handler),
Method::PUT => put(handler),
Method::DELETE => delete(handler),
Method::PATCH => patch(handler),
_ => {
panic!(
"Unsupported server function HTTP method: \
{method:?}"
);
}
},
);
}
router = router.route(
path,
match method {
Method::GET => get(handler),
Method::POST => post(handler),
Method::PUT => put(handler),
Method::DELETE => delete(handler),
Method::PATCH => patch(handler),
_ => {
panic!(
"Unsupported server function HTTP method: \
{method:?}"
);
}
},
);
}
// register router paths
for listing in paths.iter().filter(|p| !p.exclude) {
for listing in paths.iter() {
let path = listing.path();
for method in listing.methods() {
@@ -1931,7 +1902,7 @@ where
T: 'static,
{
let mut router = self;
for listing in paths.iter().filter(|p| !p.exclude) {
for listing in paths.iter() {
for method in listing.methods() {
router = router.route(
listing.path(),
@@ -2003,10 +1974,6 @@ where
.map_err(|e| ServerFnError::ServerError(format!("{e:?}")))
}
/// A reasonable handler for serving static files (like JS/WASM/CSS) and 404 errors.
///
/// This is provided as a convenience, but is a fairly simple function. If you need to adapt it,
/// simply reuse the source code of this function in your own application.
#[cfg(feature = "default")]
pub fn file_and_error_handler<S, IV>(
shell: fn(LeptosOptions) -> IV,

View File

@@ -9,7 +9,7 @@ rust-version.workspace = true
edition.workspace = true
[dependencies]
futures = "0.3.31"
futures = "0.3.30"
hydration_context = { workspace = true }
leptos = { workspace = true, features = ["nonce"] }
leptos_meta = { workspace = true, features = ["ssr"] }

View File

@@ -11,7 +11,7 @@ edition.workspace = true
[dependencies]
throw_error = { workspace = true }
any_spawner = { workspace = true, features = ["wasm-bindgen", "futures-executor"] }
any_spawner = { workspace = true, features = ["wasm-bindgen"] }
base64 = { version = "0.22.1", optional = true }
cfg-if = "1.0"
hydration_context = { workspace = true }
@@ -29,10 +29,10 @@ rand = { version = "0.8.5", optional = true }
reactive_graph = { workspace = true, features = ["serde"] }
rustc-hash = "2.0"
tachys = { workspace = true, features = ["reactive_graph", "reactive_stores", "oco"] }
thiserror = "2.0"
thiserror = "1.0"
tracing = { version = "0.1.40", optional = true }
typed-builder = "0.20.0"
typed-builder-macro = "0.20.0"
typed-builder = "0.19.1"
typed-builder-macro = "0.19.1"
serde = "1.0"
serde_json = { version = "1.0", optional = true }
server_fn = { workspace = true, features = [
@@ -40,15 +40,15 @@ server_fn = { workspace = true, features = [
"browser",
"url",
] }
web-sys = { version = "0.3.72", features = [
web-sys = { version = "0.3.70", features = [
"ShadowRoot",
"ShadowRootInit",
"ShadowRootMode",
] }
wasm-bindgen = "0.2.95"
wasm-bindgen = "=0.2.93"
serde_qs = "0.13.0"
slotmap = "1.0"
futures = "0.3.31"
futures = "0.3.30"
send_wrapper = "0.6.0"
[features]

View File

@@ -228,7 +228,6 @@ impl ViewFnOnce {
pub struct TypedChildren<T>(Box<dyn FnOnce() -> View<T> + Send>);
impl<T> TypedChildren<T> {
/// Extracts the inner `children` function.
pub fn into_inner(self) -> impl FnOnce() -> View<T> + Send {
self.0
}
@@ -257,7 +256,6 @@ impl<T> Debug for TypedChildrenMut<T> {
}
impl<T> TypedChildrenMut<T> {
/// Extracts the inner `children` function.
pub fn into_inner(self) -> impl FnMut() -> View<T> + Send {
self.0
}
@@ -286,7 +284,6 @@ impl<T> Debug for TypedChildrenFn<T> {
}
impl<T> TypedChildrenFn<T> {
/// Extracts the inner `children` function.
pub fn into_inner(self) -> Arc<dyn Fn() -> View<T> + Send + Sync> {
self.0
}

View File

@@ -251,16 +251,12 @@ where
) -> Result<Self, serde_qs::Error>;
}
/// Errors that can arise when coverting from an HTML event or form into a Rust data type.
#[derive(Error, Debug)]
pub enum FromFormDataError {
/// Could not find a `<form>` connected to the event.
#[error("Could not find <form> connected to event.")]
MissingForm(Event),
/// Could not create `FormData` from the form.
#[error("Could not create FormData from <form>: {0:?}")]
FormData(JsValue),
/// Failed to deserialize this Rust type from the form data.
#[error("Deserialization error: {0:?}")]
Deserialization(serde_qs::Error),
}

View File

@@ -1,7 +1,7 @@
(function (root, pkg_path, output_name, wasm_output_name) {
import(`${root}/${pkg_path}/${output_name}.js`)
.then(mod => {
mod.default({module_or_path: `${root}/${pkg_path}/${wasm_output_name}.wasm`}).then(() => {
mod.default(`${root}/${pkg_path}/${wasm_output_name}.wasm`).then(() => {
mod.hydrate();
});
})

View File

@@ -4,15 +4,9 @@ use crate::prelude::*;
use leptos_config::LeptosOptions;
use leptos_macro::{component, view};
/// Inserts auto-reloading code used in `cargo-leptos`.
///
/// This should be included in the `<head>` of your application shell during development.
#[component]
pub fn AutoReload(
/// Whether the file-watching feature should be disabled.
#[prop(optional)]
disable_watch: bool,
/// Configuration options for this project.
#[prop(optional)] disable_watch: bool,
options: LeptosOptions,
) -> impl IntoView {
(!disable_watch && std::env::var("LEPTOS_WATCH").is_ok()).then(|| {
@@ -40,16 +34,10 @@ pub fn AutoReload(
})
}
/// Inserts hydration scripts that add interactivity to your server-rendered HTML.
///
/// This should be included in the `<head>` of your application shell.
#[component]
pub fn HydrationScripts(
/// Configuration options for this project.
options: LeptosOptions,
/// Should be `true` to hydrate in `experimental-islands` mode.
#[prop(optional)]
islands: bool,
#[prop(optional)] islands: bool,
/// A base url, not including a trailing slash
#[prop(optional, into)]
root: Option<String>,
@@ -62,7 +50,7 @@ pub fn HydrationScripts(
path.parent().map(|p| p.to_path_buf()).unwrap_or_default()
})
.unwrap_or_default()
.join(options.hash_file.as_ref());
.join(&options.hash_file);
if hash_path.exists() {
let hashes = std::fs::read_to_string(&hash_path)
.expect("failed to read hash file");

View File

@@ -9,7 +9,6 @@ use tachys::{
},
};
/// A wrapper for any kind of view.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct View<T>
where
@@ -21,7 +20,6 @@ where
}
impl<T> View<T> {
/// Wraps the view.
pub fn new(inner: T) -> Self {
Self {
inner,
@@ -30,12 +28,10 @@ impl<T> View<T> {
}
}
/// Unwraps the view, returning the inner type.
pub fn into_inner(self) -> T {
self.inner
}
/// Adds a view marker, which is used for hot-reloading and debug purposes.
#[inline(always)]
pub fn with_view_marker(
#[allow(unused_mut)] // used in debug
@@ -51,12 +47,10 @@ impl<T> View<T> {
}
}
/// A trait that is implemented for types that can be rendered.
pub trait IntoView
where
Self: Sized + Render + RenderHtml + Send,
{
/// Wraps the inner type.
fn into_view(self) -> View<Self>;
}
@@ -194,15 +188,9 @@ impl<T: AddAnyAttr> AddAnyAttr for View<T> {
}
}
/// Collects some iterator of views into a list, so they can be rendered.
///
/// This is a shorthand for `.collect::<Vec<_>>()`, and allows any iterator of renderable
/// items to be collected into a renderable collection.
pub trait CollectView {
/// The inner view type.
type View: IntoView;
/// Collects the iterator into a list of views.
fn collect_view(self) -> Vec<Self::View>;
}

View File

@@ -1,6 +1,5 @@
#![deny(missing_docs)]
#!rdeny(missing_docs)]
#![forbid(unsafe_code)]
//! # About Leptos
//!
//! Leptos is a full-stack framework for building web applications in Rust. You can use it to build
@@ -164,7 +163,7 @@ pub mod prelude {
form::*, hydration::*, into_view::*, mount::*, suspense::*,
};
pub use leptos_config::*;
pub use leptos_dom::helpers::*;
pub use leptos_dom::{helpers::*, *};
pub use leptos_macro::*;
pub use leptos_server::*;
pub use oco_ref::*;
@@ -288,7 +287,6 @@ pub mod logging {
pub use leptos_dom::{debug_warn, error, log, warn};
}
/// Utilities for working with asynchronous tasks.
pub mod task {
pub use any_spawner::Executor;
use std::future::Future;

View File

@@ -87,12 +87,7 @@ use throw_error::ErrorHookFuture;
/// ```
#[component]
pub fn Suspense<Chil>(
/// A function that returns a fallback that will be shown while resources are still loading.
/// By default this is an empty view.
#[prop(optional, into)]
fallback: ViewFnOnce,
/// Children will be rendered once initially to catch any resource reads, then hidden until all
/// data have loaded.
#[prop(optional, into)] fallback: ViewFnOnce,
children: TypedChildren<Chil>,
) -> impl IntoView
where

View File

@@ -10,18 +10,18 @@ rust-version.workspace = true
edition.workspace = true
[dependencies]
config = { version = "0.14.1", default-features = false, features = [
config = { version = "0.14.0", default-features = false, features = [
"toml",
"convert-case",
] }
regex = "1.11"
serde = { version = "1.0", features = ["derive", "rc"] }
thiserror = "2.0"
typed-builder = "0.20.0"
regex = "1.10"
serde = { version = "1.0", features = ["derive"] }
thiserror = "1.0"
typed-builder = "0.19.1"
[dev-dependencies]
tokio = { version = "1.41", features = ["rt", "macros"] }
tempfile = "3.14"
tokio = { version = "1.39", features = ["rt", "macros"] }
tempfile = "3.12"
temp-env = { version = "0.3.6", features = ["async_closure"] }
[package.metadata.docs.rs]

View File

@@ -5,9 +5,7 @@ pub mod errors;
use crate::errors::LeptosConfigError;
use config::{Case, Config, File, FileFormat};
use regex::Regex;
use std::{
env::VarError, fs, net::SocketAddr, path::Path, str::FromStr, sync::Arc,
};
use std::{env::VarError, fs, net::SocketAddr, path::Path, str::FromStr};
use typed_builder::TypedBuilder;
/// A Struct to allow us to parse LeptosOptions from the file. Not really needed, most interactions should
@@ -27,17 +25,17 @@ pub struct ConfFile {
pub struct LeptosOptions {
/// The name of the WASM and JS files generated by wasm-bindgen. Defaults to the crate name with underscores instead of dashes
#[builder(setter(into), default=default_output_name())]
pub output_name: Arc<str>,
pub output_name: String,
/// The path of the all the files generated by cargo-leptos. This defaults to '.' for convenience when integrating with other
/// tools.
#[builder(setter(into), default=default_site_root())]
#[serde(default = "default_site_root")]
pub site_root: Arc<str>,
pub site_root: String,
/// The path of the WASM and JS files generated by wasm-bindgen from the root of your app
/// By default, wasm-bindgen puts them in `pkg`.
#[builder(setter(into), default=default_site_pkg_dir())]
#[serde(default = "default_site_pkg_dir")]
pub site_pkg_dir: Arc<str>,
pub site_pkg_dir: String,
/// Used to configure the running environment of Leptos. Can be used to load dev constants and keys v prod, or change
/// things based on the deployment environment
/// I recommend passing in the result of `env::var("LEPTOS_ENV")`
@@ -68,11 +66,11 @@ pub struct LeptosOptions {
/// The path of a custom 404 Not Found page to display when statically serving content, defaults to `site_root/404.html`
#[builder(default = default_not_found_path())]
#[serde(default = "default_not_found_path")]
pub not_found_path: Arc<str>,
pub not_found_path: String,
/// The file name of the hash text file generated by cargo-leptos. Defaults to `hash.txt`.
#[builder(default = default_hash_file_name())]
#[serde(default = "default_hash_file_name")]
pub hash_file: Arc<str>,
pub hash_file: String,
/// If true, hashes will be generated for all files in the site_root and added to their file names.
/// Defaults to `true`.
#[builder(default = default_hash_files())]
@@ -98,9 +96,9 @@ impl LeptosOptions {
);
}
Ok(LeptosOptions {
output_name: output_name.into(),
site_root: env_w_default("LEPTOS_SITE_ROOT", "target/site")?.into(),
site_pkg_dir: env_w_default("LEPTOS_SITE_PKG_DIR", "pkg")?.into(),
output_name,
site_root: env_w_default("LEPTOS_SITE_ROOT", "target/site")?,
site_pkg_dir: env_w_default("LEPTOS_SITE_PKG_DIR", "pkg")?,
env: env_from_str(env_w_default("LEPTOS_ENV", "DEV")?.as_str())?,
site_addr: env_w_default("LEPTOS_SITE_ADDR", "127.0.0.1:3000")?
.parse()?,
@@ -115,10 +113,8 @@ impl LeptosOptions {
reload_ws_protocol: ws_from_str(
env_w_default("LEPTOS_RELOAD_WS_PROTOCOL", "ws")?.as_str(),
)?,
not_found_path: env_w_default("LEPTOS_NOT_FOUND_PATH", "/404")?
.into(),
hash_file: env_w_default("LEPTOS_HASH_FILE_NAME", "hash.txt")?
.into(),
not_found_path: env_w_default("LEPTOS_NOT_FOUND_PATH", "/404")?,
hash_file: env_w_default("LEPTOS_HASH_FILE_NAME", "hash.txt")?,
hash_files: env_w_default("LEPTOS_HASH_FILES", "false")?.parse()?,
})
}
@@ -130,16 +126,16 @@ impl Default for LeptosOptions {
}
}
fn default_output_name() -> Arc<str> {
env!("CARGO_CRATE_NAME").replace('-', "_").into()
fn default_output_name() -> String {
env!("CARGO_CRATE_NAME").replace('-', "_")
}
fn default_site_root() -> Arc<str> {
".".into()
fn default_site_root() -> String {
".".to_string()
}
fn default_site_pkg_dir() -> Arc<str> {
"pkg".into()
fn default_site_pkg_dir() -> String {
"pkg".to_string()
}
fn default_env() -> Env {
@@ -154,12 +150,12 @@ fn default_reload_port() -> u32 {
3001
}
fn default_not_found_path() -> Arc<str> {
"/404".into()
fn default_not_found_path() -> String {
"/404".to_string()
}
fn default_hash_file_name() -> Arc<str> {
"hash.txt".into()
fn default_hash_file_name() -> String {
"hash.txt".to_string()
}
fn default_hash_files() -> bool {

View File

@@ -76,9 +76,9 @@ fn try_from_env_test() {
|| LeptosOptions::try_from_env().unwrap(),
);
assert_eq!(config.output_name.as_ref(), "app_test");
assert_eq!(config.site_root.as_ref(), "my_target/site");
assert_eq!(config.site_pkg_dir.as_ref(), "my_pkg");
assert_eq!(config.output_name, "app_test");
assert_eq!(config.site_root, "my_target/site");
assert_eq!(config.site_pkg_dir, "my_pkg");
assert_eq!(
config.site_addr,
SocketAddr::from_str("0.0.0.0:80").unwrap()

View File

@@ -50,9 +50,9 @@ async fn get_configuration_from_file_ok() {
)
.await;
assert_eq!(config.output_name.as_ref(), "app-test");
assert_eq!(config.site_root.as_ref(), "my_target/site");
assert_eq!(config.site_pkg_dir.as_ref(), "my_pkg");
assert_eq!(config.output_name, "app-test");
assert_eq!(config.site_root, "my_target/site");
assert_eq!(config.site_pkg_dir, "my_pkg");
assert_eq!(
config.site_addr,
SocketAddr::from_str("0.0.0.0:80").unwrap()
@@ -106,9 +106,9 @@ async fn get_config_from_file_ok() {
)
.await;
assert_eq!(config.output_name.as_ref(), "app-test");
assert_eq!(config.site_root.as_ref(), "my_target/site");
assert_eq!(config.site_pkg_dir.as_ref(), "my_pkg");
assert_eq!(config.output_name, "app-test");
assert_eq!(config.site_root, "my_target/site");
assert_eq!(config.site_pkg_dir, "my_pkg");
assert_eq!(
config.site_addr,
SocketAddr::from_str("0.0.0.0:80").unwrap()
@@ -151,9 +151,9 @@ fn get_config_from_str_content() {
|| get_config_from_str(CARGO_TOML_CONTENT_OK).unwrap(),
);
assert_eq!(config.output_name.as_ref(), "app-test");
assert_eq!(config.site_root.as_ref(), "my_target/site");
assert_eq!(config.site_pkg_dir.as_ref(), "my_pkg");
assert_eq!(config.output_name, "app-test");
assert_eq!(config.site_root, "my_target/site");
assert_eq!(config.site_pkg_dir, "my_pkg");
assert_eq!(
config.site_addr,
SocketAddr::from_str("0.0.0.0:80").unwrap()
@@ -178,9 +178,9 @@ async fn get_config_from_env() {
)
.await;
assert_eq!(config.output_name.as_ref(), "app-test");
assert_eq!(config.site_root.as_ref(), "my_target/site");
assert_eq!(config.site_pkg_dir.as_ref(), "my_pkg");
assert_eq!(config.output_name, "app-test");
assert_eq!(config.site_root, "my_target/site");
assert_eq!(config.site_pkg_dir, "my_pkg");
assert_eq!(
config.site_addr,
SocketAddr::from_str("0.0.0.0:80").unwrap()
@@ -202,8 +202,8 @@ async fn get_config_from_env() {
)
.await;
assert_eq!(config.site_root.as_ref(), "target/site");
assert_eq!(config.site_pkg_dir.as_ref(), "pkg");
assert_eq!(config.site_root, "target/site");
assert_eq!(config.site_pkg_dir, "pkg");
assert_eq!(
config.site_addr,
SocketAddr::from_str("127.0.0.1:3000").unwrap()
@@ -215,10 +215,10 @@ async fn get_config_from_env() {
#[test]
fn leptos_options_builder_default() {
let conf = LeptosOptions::builder().output_name("app-test").build();
assert_eq!(conf.output_name.as_ref(), "app-test");
assert_eq!(conf.output_name, "app-test");
assert!(matches!(conf.env, Env::DEV));
assert_eq!(conf.site_pkg_dir.as_ref(), "pkg");
assert_eq!(conf.site_root.as_ref(), ".");
assert_eq!(conf.site_pkg_dir, "pkg");
assert_eq!(conf.site_root, ".");
assert_eq!(
conf.site_addr,
SocketAddr::from_str("127.0.0.1:3000").unwrap()
@@ -242,9 +242,9 @@ fn environment_variable_override() {
|| get_config_from_str(CARGO_TOML_CONTENT_OK).unwrap(),
);
assert_eq!(config.output_name.as_ref(), "app-test");
assert_eq!(config.site_root.as_ref(), "my_target/site");
assert_eq!(config.site_pkg_dir.as_ref(), "my_pkg");
assert_eq!(config.output_name, "app-test");
assert_eq!(config.site_root, "my_target/site");
assert_eq!(config.site_pkg_dir, "my_pkg");
assert_eq!(
config.site_addr,
SocketAddr::from_str("0.0.0.0:80").unwrap()
@@ -265,9 +265,9 @@ fn environment_variable_override() {
|| get_config_from_str(CARGO_TOML_CONTENT_OK).unwrap(),
);
assert_eq!(config.output_name.as_ref(), "app-test2");
assert_eq!(config.site_root.as_ref(), "my_target/site2");
assert_eq!(config.site_pkg_dir.as_ref(), "my_pkg2");
assert_eq!(config.output_name, "app-test2");
assert_eq!(config.site_root, "my_target/site2");
assert_eq!(config.site_pkg_dir, "my_pkg2");
assert_eq!(
config.site_addr,
SocketAddr::from_str("0.0.0.0:82").unwrap()

View File

@@ -12,10 +12,10 @@ edition.workspace = true
tachys = { workspace = true }
reactive_graph = { workspace = true }
or_poisoned = { workspace = true }
js-sys = "0.3.72"
js-sys = "0.3.69"
send_wrapper = "0.6.0"
tracing = { version = "0.1.40", optional = true }
wasm-bindgen = "0.2.95"
wasm-bindgen = "0.2.93"
serde_json = { version = "1.0", optional = true }
serde = { version = "1.0", optional = true }
@@ -23,7 +23,7 @@ serde = { version = "1.0", optional = true }
leptos = { path = "../leptos" }
[dependencies.web-sys]
version = "0.3.72"
version = "0.3.70"
features = ["Location"]
[features]

View File

@@ -4,11 +4,11 @@ version = "0.1.0"
edition = "2021"
[dependencies]
console_error_panic_hook = "0.1.7"
console_error_panic_hook = "0.1.0"
gloo = { version = "0.11.0", features = ["futures"] }
leptos = { path = "../../../leptos", features = ["nightly", "csr", "tracing"] }
tracing = "0.1.40"
tracing-subscriber = "0.3.18"
tracing = "0.1.0"
tracing-subscriber = "0.3.0"
tracing-subscriber-wasm = "0.1.0"
[workspace]

View File

@@ -8,4 +8,5 @@ pub mod helpers;
pub mod macro_helpers;
/// Utilities for simple isomorphic logging to the console or terminal.
#[macro_use]
pub mod logging;

View File

@@ -25,4 +25,4 @@ proc-macro2 = { version = "1.0", features = ["span-locations", "nightly"] }
parking_lot = "0.12.3"
walkdir = "2.5"
camino = "1.1"
indexmap = "2.6"
indexmap = "2.3"

View File

@@ -1,6 +1,6 @@
[package]
name = "leptos_macro"
version = "0.7.0-rc1"
version = "0.7.0-gamma3"
authors = ["Greg Johnston"]
license = "MIT"
repository = "https://github.com/leptos-rs/leptos"
@@ -13,11 +13,11 @@ edition.workspace = true
proc-macro = true
[dependencies]
attribute-derive = { version = "0.10.2", features = ["syn-full"] }
attribute-derive = { version = "0.9.2", features = ["syn-full"] }
cfg-if = "1.0"
html-escape = "0.2.13"
itertools = "0.13.0"
prettyplease = "0.2.25"
prettyplease = "0.2.20"
proc-macro-error2 = { version = "2.0", default-features = false }
proc-macro2 = "1.0"
quote = "1.0"
@@ -26,16 +26,16 @@ rstml = "0.12.0"
leptos_hot_reload = { workspace = true }
server_fn_macro = { workspace = true }
convert_case = "0.6.0"
uuid = { version = "1.11", features = ["v4"] }
uuid = { version = "1.10", features = ["v4"] }
tracing = { version = "0.1.40", optional = true }
[dev-dependencies]
log = "0.4.22"
typed-builder = "0.20.0"
typed-builder = "0.19.1"
trybuild = "1.0"
leptos = { path = "../leptos" }
server_fn = { path = "../server_fn", features = ["cbor"] }
insta = "1.41"
insta = "1.39"
serde = "1.0"
[features]
@@ -48,7 +48,6 @@ experimental-islands = []
trace-component-props = []
actix = ["server_fn_macro/actix"]
axum = ["server_fn_macro/axum"]
generic = ["server_fn_macro/generic"]
[package.metadata.cargo-all-features]
denylist = ["nightly", "tracing", "trace-component-props"]
@@ -69,14 +68,6 @@ skip_feature_sets = [
"actix",
"axum",
],
[
"actix",
"generic",
],
[
"generic",
"axum",
],
]
[package.metadata.docs.rs]

View File

@@ -1,5 +1,3 @@
//! Macros for use with the [`leptos`] framework.
#![cfg_attr(feature = "nightly", feature(proc_macro_span))]
#![forbid(unsafe_code)]
// to prevent warnings from popping up when a nightly feature is stabilized
@@ -7,7 +5,6 @@
// FIXME? every use of quote! {} is warning here -- false positive?
#![allow(unknown_lints)]
#![allow(private_macro_use)]
#![deny(missing_docs)]
#[macro_use]
extern crate proc_macro_error2;

View File

@@ -23,11 +23,8 @@ use std::{
collections::{HashMap, HashSet, VecDeque},
};
use syn::{
punctuated::Pair::{End, Punctuated},
spanned::Spanned,
Expr,
Expr::Tuple,
ExprArray, ExprLit, ExprRange, Lit, LitStr, RangeLimits, Stmt,
spanned::Spanned, Expr, Expr::Tuple, ExprLit, ExprRange, Lit, LitStr,
RangeLimits, Stmt,
};
#[derive(Clone, Copy, PartialEq, Eq)]
@@ -653,9 +650,6 @@ pub(crate) fn element_to_tokens(
_ => None,
};
match (key_a.as_deref(), key_b.as_deref()) {
(Some("class"), Some("class")) | (Some("style"), Some("style")) => {
Ordering::Equal
}
(Some("class"), _) | (Some("style"), _) => Ordering::Less,
(_, Some("class")) | (_, Some("style")) => Ordering::Greater,
_ => Ordering::Equal,
@@ -667,18 +661,9 @@ pub(crate) fn element_to_tokens(
for attr in node.attributes() {
if let NodeAttribute::Attribute(attr) = attr {
let mut name = attr.key.to_string();
match tuple_name(&name, attr) {
TupleName::None => {}
TupleName::Str(tuple_name) => {
name.push(':');
name.push_str(&tuple_name);
}
TupleName::Array(names) => {
for tuple_name in names {
name.push(':');
name.push_str(&tuple_name);
}
}
if let Some(tuple_name) = tuple_name(&name, attr) {
name.push(':');
name.push_str(&tuple_name);
}
if names.contains(&name) {
proc_macro_error2::emit_error!(
@@ -1001,14 +986,10 @@ pub(crate) fn attribute_absolute(
) -> Option<TokenStream> {
let key = node.key.to_string();
let contains_dash = key.contains('-');
let attr_colon = key.starts_with("attr:")
|| key.starts_with("style:")
|| key.starts_with("class:")
|| key.starts_with("prop:")
|| key.starts_with("use:");
let attr_aira = key.starts_with("attr:aria-");
// anything that follows the x:y pattern
match &node.key {
NodeName::Punctuated(parts) if !contains_dash || attr_colon => {
NodeName::Punctuated(parts) if !contains_dash || attr_aira => {
if parts.len() >= 2 {
let id = &parts[0];
match id {
@@ -1017,8 +998,7 @@ pub(crate) fn attribute_absolute(
if id == "let" || id == "clone" {
None
} else if id == "attr" {
let value = attribute_value(node, true);
let multipart = parts.len() > 2;
let value = attribute_value(node, true);
let key = &parts[1];
let key_name = key.to_string();
if key_name == "class" || key_name == "style" {
@@ -1034,15 +1014,6 @@ pub(crate) fn attribute_absolute(
Some(
quote! { ::leptos::tachys::html::attribute::#key(#value) },
)
} else if multipart {
// e.g., attr:data-foo="bar"
let key_name = parts.pairs().skip(1).map(|p| match p {
Punctuated(n, p) => format!("{n}{p}"),
End(n) => n.to_string(),
}).collect::<String>();
Some(
quote! { ::leptos::tachys::html::attribute::custom::custom_attribute(#key_name, #value) },
)
} else {
Some(
quote! { ::leptos::tachys::html::attribute::#key(#value) },
@@ -1212,32 +1183,6 @@ fn class_to_tokens(
class: TokenStream,
class_name: Option<&str>,
) -> TokenStream {
// case of class=(["foo", "bar"], /* something */)
// just expands to multiple uses of class:
if let Some(Tuple(tuple)) = node.value() {
if tuple.elems.len() == 2 {
let name = &tuple.elems[0];
let value = &tuple.elems[1];
if let Expr::Array(ExprArray { elems, .. }) = name {
return elems
.iter()
.map(|elem| match elem {
Expr::Lit(ExprLit {
lit: Lit::Str(s), ..
}) => quote! {
.#class((#s, #value))
},
_ => proc_macro_error2::abort!(
elem.span(),
"invalid name"
),
})
.collect();
}
}
}
// default case
let value = attribute_value(node, false);
if let Some(class_name) = class_name {
quote! {
@@ -1672,7 +1617,7 @@ pub(crate) fn directive_call_from_attribute_node(
quote! { .directive(#handler, #[allow(clippy::useless_conversion)] #param) }
}
fn tuple_name(name: &str, node: &KeyedAttribute) -> TupleName {
fn tuple_name(name: &str, node: &KeyedAttribute) -> Option<String> {
if name == "style" || name == "class" {
if let Some(Tuple(tuple)) = node.value() {
{
@@ -1682,37 +1627,12 @@ fn tuple_name(name: &str, node: &KeyedAttribute) -> TupleName {
lit: Lit::Str(s), ..
}) = style_name
{
return TupleName::Str(s.value());
} else if let Expr::Array(ExprArray { elems, .. }) =
style_name
{
return TupleName::Array(
elems
.iter()
.filter_map(|elem| match elem {
Expr::Lit(ExprLit {
lit: Lit::Str(s),
..
}) => Some(s.value()),
_ => proc_macro_error2::abort!(
elem.span(),
"invalid name"
),
})
.collect(),
);
return Some(s.value());
}
}
}
}
}
TupleName::None
}
#[derive(Debug)]
enum TupleName {
None,
Str(String),
Array(Vec<String>),
None
}

View File

@@ -16,7 +16,7 @@ hydration_context = { workspace = true }
reactive_graph = { workspace = true, features = ["hydration"] }
server_fn = { workspace = true }
tracing = { version = "0.1.40", optional = true }
futures = "0.3.31"
futures = "0.3.30"
any_spawner = { workspace = true }
or_poisoned = { workspace = true }
@@ -25,8 +25,8 @@ send_wrapper = "0.6"
# serialization formats
serde = { version = "1.0" }
js-sys = { version = "0.3.72", optional = true }
wasm-bindgen = { version = "0.2.95", optional = true }
js-sys = { version = "0.3.69", optional = true }
wasm-bindgen = { version = "0.2.93", optional = true }
serde_json = { version = "1.0" }
[features]

View File

@@ -6,10 +6,6 @@ use reactive_graph::{
use server_fn::{error::ServerFnErrorSerde, ServerFn, ServerFnError};
use std::{ops::Deref, panic::Location, sync::Arc};
/// An error that can be caused by a server action.
///
/// This is used for propagating errors from the server to the client when JS/WASM are not
/// supported.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ServerActionError {
path: Arc<str>,
@@ -17,7 +13,6 @@ pub struct ServerActionError {
}
impl ServerActionError {
/// Creates a new error associated with the given path.
pub fn new(path: &str, err: &str) -> Self {
Self {
path: path.into(),
@@ -25,18 +20,15 @@ impl ServerActionError {
}
}
/// The path with which this error is associated.
pub fn path(&self) -> &str {
&self.path
}
/// The error message.
pub fn err(&self) -> &str {
&self.err
}
}
/// An [`ArcAction`] that can be used to call a server function.
pub struct ArcServerAction<S>
where
S: ServerFn + 'static,
@@ -53,7 +45,6 @@ where
S::Output: Send + Sync + 'static,
S::Error: Send + Sync + 'static,
{
/// Creates a new [`ArcAction`] that will call the server function `S` when dispatched.
#[track_caller]
pub fn new() -> Self {
let err = use_context::<ServerActionError>().and_then(|error| {
@@ -125,7 +116,6 @@ where
}
}
/// An [`Action`] that can be used to call a server function.
pub struct ServerAction<S>
where
S: ServerFn + 'static,
@@ -142,7 +132,6 @@ where
S::Output: Send + Sync + 'static,
S::Error: Send + Sync + 'static,
{
/// Creates a new [`Action`] that will call the server function `S` when dispatched.
pub fn new() -> Self {
let err = use_context::<ServerActionError>().and_then(|error| {
(error.path() == S::PATH)

View File

@@ -1,6 +1,4 @@
//! Utilities for communicating between the server and the client with [`leptos`].
#![deny(missing_docs)]
//#![deny(missing_docs)]
#![forbid(unsafe_code)]
mod action;
@@ -15,25 +13,135 @@ pub use once_resource::*;
mod resource;
pub use resource::*;
mod shared;
////! # Leptos Server Functions
////!
////! This package is based on a simple idea: sometimes its useful to write functions
////! that will only run on the server, and call them from the client.
////!
////! If youre creating anything beyond a toy app, youll need to do this all the time:
////! reading from or writing to a database that only runs on the server, running expensive
////! computations using libraries you dont want to ship down to the client, accessing
////! APIs that need to be called from the server rather than the client for CORS reasons
////! or because you need a secret API key thats stored on the server and definitely
////! shouldnt be shipped down to a users browser.
////!
////! Traditionally, this is done by separating your server and client code, and by setting
////! up something like a REST API or GraphQL API to allow your client to fetch and mutate
////! data on the server. This is fine, but it requires you to write and maintain your code
////! in multiple separate places (client-side code for fetching, server-side functions to run),
////! as well as creating a third thing to manage, which is the API contract between the two.
////!
////! This package provides two simple primitives that allow you instead to write co-located,
////! isomorphic server functions. (*Co-located* means you can write them in your app code so
////! that they are “located alongside” the client code that calls them, rather than separating
////! the client and server sides. *Isomorphic* means you can call them from the client as if
////! you were simply calling a function; the function call has the “same shape” on the client
////! as it does on the server.)
////!
////! ### `#[server]`
////!
////! The [`#[server]`](https://docs.rs/leptos/latest/leptos/attr.server.html) macro allows you to annotate a function to
////! indicate that it should only run on the server (i.e., when you have an `ssr` feature in your
////! crate that is enabled).
////!
////! ```rust,ignore
////! use leptos::prelude::*;
////! #[server(ReadFromDB)]
////! async fn read_posts(how_many: usize, query: String) -> Result<Vec<Posts>, ServerFnError> {
////! // do some server-only work here to access the database
////! let posts = todo!();;
////! Ok(posts)
////! }
////!
////! // call the function
////! spawn_local(async {
////! let posts = read_posts(3, "my search".to_string()).await;
////! log::debug!("posts = {posts:#?}");
////! });
////! ```
////!
////! If you call this function from the client, it will serialize the function arguments and `POST`
////! them to the server as if they were the inputs in `<form method="POST">`.
////!
////! Heres what you need to remember:
////! - **Server functions must be `async`.** Even if the work being done inside the function body
////! can run synchronously on the server, from the clients perspective it involves an asynchronous
////! function call.
////! - **Server functions must return `Result<T, ServerFnError>`.** Even if the work being done
////! inside the function body cant fail, the processes of serialization/deserialization and the
////! network call are fallible.
////! - **Return types must be [Serializable](leptos_reactive::Serializable).**
////! This should be fairly obvious: we have to serialize arguments to send them to the server, and we
////! need to deserialize the result to return it to the client.
////! - **Arguments must be implement [serde::Serialize].** They are serialized as an `application/x-www-form-urlencoded`
////! form data using [`serde_qs`](https://docs.rs/serde_qs/latest/serde_qs/) or as `application/cbor`
////! using [`cbor`](https://docs.rs/cbor/latest/cbor/). **Note**: You should explicitly include `serde` with the
////! `derive` feature enabled in your `Cargo.toml`. You can do this by running `cargo add serde --features=derive`.
////! - Context comes from the server. [`use_context`](leptos_reactive::use_context) can be used to access specific
////! server-related data, as documented in the server integrations. This allows accessing things like HTTP request
////! headers as needed. However, server functions *not* have access to reactive state that exists in the client.
////!
////! ## Server Function Encodings
////!
////! By default, the server function call is a `POST` request that serializes the arguments as URL-encoded form data in the body
////! of the request. But there are a few other methods supported. Optionally, we can provide another argument to the `#[server]`
////! macro to specify an alternate encoding:
////!
////! ```rust,ignore
////! #[server(AddTodo, "/api", "Url")]
////! #[server(AddTodo, "/api", "GetJson")]
////! #[server(AddTodo, "/api", "Cbor")]
////! #[server(AddTodo, "/api", "GetCbor")]
////! ```
////!
////! The four options use different combinations of HTTP verbs and encoding methods:
////!
////! | Name | Method | Request | Response |
////! | ----------------- | ------ | ----------- | -------- |
////! | **Url** (default) | POST | URL encoded | JSON |
////! | **GetJson** | GET | URL encoded | JSON |
////! | **Cbor** | POST | CBOR | CBOR |
////! | **GetCbor** | GET | URL encoded | CBOR |
////!
////! In other words, you have two choices:
////!
////! - `GET` or `POST`? This has implications for things like browser or CDN caching; while `POST` requests should not be cached,
////! `GET` requests can be.
////! - Plain text (arguments sent with URL/form encoding, results sent as JSON) or a binary format (CBOR, encoded as a base64
////! string)?
////!
////! ## Why not `PUT` or `DELETE`? Why URL/form encoding, and not JSON?**
////!
////! These are reasonable questions. Much of the web is built on REST API patterns that encourage the use of semantic HTTP
////! methods like `DELETE` to delete an item from a database, and many devs are accustomed to sending data to APIs in the
////! JSON format.
////!
////! The reason we use `POST` or `GET` with URL-encoded data by default is the `<form>` support. For better or for worse,
////! HTML forms dont support `PUT` or `DELETE`, and they dont support sending JSON. This means that if you use anything
////! but a `GET` or `POST` request with URL-encoded data, it can only work once WASM has loaded.
////!
////! The CBOR encoding is supported for historical reasons; an earlier version of server functions used a URL encoding that
////! didnt support nested objects like structs or vectors as server function arguments, which CBOR did. But note that the
////! CBOR forms encounter the same issue as `PUT`, `DELETE`, or JSON: they do not degrade gracefully if the WASM version of
////! your app is not available.
//pub use server_fn::{error::ServerFnErrorErr, ServerFnError};
//mod action;
//mod multi_action;
//pub use action::*;
//pub use multi_action::*;
//extern crate tracing;
use base64::{engine::general_purpose::STANDARD_NO_PAD, DecodeError, Engine};
pub use shared::*;
/// Encodes data into a string.
pub trait IntoEncodedString {
/// Encodes the data.
fn into_encoded_string(self) -> String;
}
/// Decodes data from a string.
pub trait FromEncodedStr {
/// The decoded data.
type DecodedType<'a>: Borrow<Self>;
/// The type of an error encountered during decoding.
type DecodingError;
/// Decodes the string.
fn from_encoded_str(
data: &str,
) -> Result<Self::DecodedType<'_>, Self::DecodingError>;

View File

@@ -17,9 +17,8 @@ use std::{
panic::Location,
};
/// A reference-counted resource that only loads its data locally on the client.
pub struct ArcLocalResource<T> {
data: ArcAsyncDerived<SendWrapper<T>>,
data: ArcAsyncDerived<T>,
#[cfg(debug_assertions)]
defined_at: &'static Location<'static>,
}
@@ -35,10 +34,6 @@ impl<T> Clone for ArcLocalResource<T> {
}
impl<T> ArcLocalResource<T> {
/// Creates the resource.
///
/// This will only begin loading data if you are on the client (i.e., if you do not have the
/// `ssr` feature activated).
#[track_caller]
pub fn new<Fut>(fetcher: impl Fn() -> Fut + 'static) -> Self
where
@@ -64,12 +59,8 @@ impl<T> ArcLocalResource<T> {
}
}
};
let fetcher = SendWrapper::new(fetcher);
Self {
data: ArcAsyncDerived::new(move || {
let fut = fetcher();
SendWrapper::new(async move { SendWrapper::new(fut.await) })
}),
data: ArcAsyncDerived::new_unsync(fetcher),
#[cfg(debug_assertions)]
defined_at: Location::caller(),
}
@@ -81,14 +72,9 @@ where
T: Clone + 'static,
{
type Output = T;
type IntoFuture = futures::future::Map<
AsyncDerivedFuture<SendWrapper<T>>,
fn(SendWrapper<T>) -> T,
>;
type IntoFuture = AsyncDerivedFuture<T>;
fn into_future(self) -> Self::IntoFuture {
use futures::FutureExt;
if let Some(mut notifier) = use_context::<LocalResourceNotifier>() {
notifier.notify();
} else if cfg!(feature = "ssr") {
@@ -98,7 +84,7 @@ where
always pending on the server."
);
}
self.data.into_future().map(|value| (*value).clone())
self.data.into_future()
}
}
@@ -119,8 +105,7 @@ impl<T> ReadUntracked for ArcLocalResource<T>
where
T: 'static,
{
type Value =
ReadGuard<Option<SendWrapper<T>>, AsyncPlain<Option<SendWrapper<T>>>>;
type Value = ReadGuard<Option<T>, AsyncPlain<Option<T>>>;
fn try_read_untracked(&self) -> Option<Self::Value> {
if let Some(mut notifier) = use_context::<LocalResourceNotifier>() {
@@ -197,7 +182,6 @@ impl<T> Subscriber for ArcLocalResource<T> {
}
}
/// A resource that only loads its data locally on the client.
pub struct LocalResource<T> {
data: AsyncDerived<SendWrapper<T>>,
#[cfg(debug_assertions)]
@@ -213,10 +197,6 @@ impl<T> Clone for LocalResource<T> {
impl<T> Copy for LocalResource<T> {}
impl<T> LocalResource<T> {
/// Creates the resource.
///
/// This will only begin loading data if you are on the client (i.e., if you do not have the
/// `ssr` feature activated).
#[track_caller]
pub fn new<Fut>(fetcher: impl Fn() -> Fut + 'static) -> Self
where
@@ -393,23 +373,3 @@ where
self.data.clear_sources(subscriber);
}
}
impl<T: 'static> From<ArcLocalResource<T>> for LocalResource<T> {
fn from(arc: ArcLocalResource<T>) -> Self {
Self {
data: arc.data.into(),
#[cfg(debug_assertions)]
defined_at: arc.defined_at,
}
}
}
impl<T: 'static> From<LocalResource<T>> for ArcLocalResource<T> {
fn from(local: LocalResource<T>) -> Self {
Self {
data: local.data.into(),
#[cfg(debug_assertions)]
defined_at: local.defined_at,
}
}
}

View File

@@ -5,7 +5,6 @@ use reactive_graph::{
use server_fn::{ServerFn, ServerFnError};
use std::{ops::Deref, panic::Location};
/// An [`ArcMultiAction`] that can be used to call a server function.
pub struct ArcServerMultiAction<S>
where
S: ServerFn + 'static,
@@ -22,7 +21,6 @@ where
S::Output: Send + Sync + 'static,
S::Error: Send + Sync + 'static,
{
/// Creates a new [`ArcMultiAction`] which, when dispatched, will call the server function `S`.
#[track_caller]
pub fn new() -> Self {
Self {
@@ -89,7 +87,6 @@ where
}
}
/// A [`MultiAction`] that can be used to call a server function.
pub struct ServerMultiAction<S>
where
S: ServerFn + 'static,
@@ -117,7 +114,6 @@ where
S::Output: Send + Sync + 'static,
S::Error: Send + Sync + 'static,
{
/// Creates a new [`MultiAction`] which, when dispatched, will call the server function `S`.
pub fn new() -> Self {
Self {
inner: MultiAction::new(|input: &S| {

View File

@@ -0,0 +1,344 @@
use leptos_reactive::{
is_suppressing_resource_load, signal_prelude::*, spawn_local, store_value,
untrack, StoredValue,
};
use server_fn::{ServerFn, ServerFnError};
use std::{future::Future, pin::Pin, rc::Rc};
/// An action that synchronizes multiple imperative `async` calls to the reactive system,
/// tracking the progress of each one.
///
/// Where an [Action](crate::Action) fires a single call, a `MultiAction` allows you to
/// keep track of multiple in-flight actions.
///
/// If youre trying to load data by running an `async` function reactively, you probably
/// want to use a [Resource](leptos_reactive::Resource) instead. If youre trying to occasionally
/// run an `async` function in response to something like a user adding a task to a todo list,
/// youre in the right place.
///
/// ```rust
/// # use leptos::*;
/// # let runtime = create_runtime();
/// async fn send_new_todo_to_api(task: String) -> usize {
/// // do something...
/// // return a task id
/// 42
/// }
/// let add_todo = create_multi_action(|task: &String| {
/// // `task` is given as `&String` because its value is available in `input`
/// send_new_todo_to_api(task.clone())
/// });
///
/// # if false {
/// add_todo.dispatch("Buy milk".to_string());
/// add_todo.dispatch("???".to_string());
/// add_todo.dispatch("Profit!!!".to_string());
/// # }
///
/// # runtime.dispose();
/// ```
///
/// The input to the `async` function should always be a single value,
/// but it can be of any type. The argument is always passed by reference to the
/// function, because it is stored in [Submission::input] as well.
///
/// ```rust
/// # use leptos::*;
/// # let runtime = create_runtime();
/// // if there's a single argument, just use that
/// let action1 = create_multi_action(|input: &String| {
/// let input = input.clone();
/// async move { todo!() }
/// });
///
/// // if there are no arguments, use the unit type `()`
/// let action2 = create_multi_action(|input: &()| async { todo!() });
///
/// // if there are multiple arguments, use a tuple
/// let action3 =
/// create_multi_action(|input: &(usize, String)| async { todo!() });
/// # runtime.dispose();
/// ```
pub struct MultiAction<I, O>(StoredValue<MultiActionState<I, O>>)
where
I: 'static,
O: 'static;
impl<I, O> MultiAction<I, O>
where
I: 'static,
O: 'static,
{
}
impl<I, O> Clone for MultiAction<I, O>
where
I: 'static,
O: 'static,
{
fn clone(&self) -> Self {
*self
}
}
impl<I, O> Copy for MultiAction<I, O>
where
I: 'static,
O: 'static,
{
}
impl<I, O> MultiAction<I, O>
where
I: 'static,
O: 'static,
{
/// Calls the `async` function with a reference to the input type as its argument.
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "trace", skip_all)
)]
pub fn dispatch(&self, input: I) {
self.0.with_value(|a| a.dispatch(input))
}
/// The set of all submissions to this multi-action.
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "trace", skip_all)
)]
pub fn submissions(&self) -> ReadSignal<Vec<Submission<I, O>>> {
self.0.with_value(|a| a.submissions())
}
/// The URL associated with the action (typically as part of a server function.)
/// This enables integration with the `MultiActionForm` component in `leptos_router`.
pub fn url(&self) -> Option<String> {
self.0.with_value(|a| a.url.as_ref().cloned())
}
/// How many times an action has successfully resolved.
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "trace", skip_all)
)]
pub fn version(&self) -> RwSignal<usize> {
self.0.with_value(|a| a.version)
}
/// Associates the URL of the given server function with this action.
/// This enables integration with the `MultiActionForm` component in `leptos_router`.
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "trace", skip_all)
)]
pub fn using_server_fn<T: ServerFn>(self) -> Self {
self.0.update_value(|a| {
a.url = Some(T::url().to_string());
});
self
}
}
struct MultiActionState<I, O>
where
I: 'static,
O: 'static,
{
/// How many times an action has successfully resolved.
pub version: RwSignal<usize>,
submissions: RwSignal<Vec<Submission<I, O>>>,
url: Option<String>,
#[allow(clippy::complexity)]
action_fn: Rc<dyn Fn(&I) -> Pin<Box<dyn Future<Output = O>>>>,
}
/// An action that has been submitted by dispatching it to a [MultiAction](crate::MultiAction).
pub struct Submission<I, O>
where
I: 'static,
O: 'static,
{
/// The current argument that was dispatched to the `async` function.
/// `Some` while we are waiting for it to resolve, `None` if it has resolved.
pub input: RwSignal<Option<I>>,
/// The most recent return value of the `async` function.
pub value: RwSignal<Option<O>>,
pub(crate) pending: RwSignal<bool>,
/// Controls this submission has been canceled.
pub canceled: RwSignal<bool>,
}
impl<I, O> Clone for Submission<I, O> {
fn clone(&self) -> Self {
*self
}
}
impl<I, O> Copy for Submission<I, O> {}
impl<I, O> Submission<I, O>
where
I: 'static,
O: 'static,
{
/// Whether this submission is currently waiting to resolve.
pub fn pending(&self) -> ReadSignal<bool> {
self.pending.read_only()
}
/// Cancels the submission, preventing it from resolving.
pub fn cancel(&self) {
self.canceled.set(true);
}
}
impl<I, O> MultiActionState<I, O>
where
I: 'static,
O: 'static,
{
/// Calls the `async` function with a reference to the input type as its argument.
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "trace", skip_all)
)]
pub fn dispatch(&self, input: I) {
if !is_suppressing_resource_load() {
let fut = (self.action_fn)(&input);
let submission = Submission {
input: create_rw_signal(Some(input)),
value: create_rw_signal(None),
pending: create_rw_signal(true),
canceled: create_rw_signal(false),
};
self.submissions.update(|subs| subs.push(submission));
let canceled = submission.canceled;
let input = submission.input;
let pending = submission.pending;
let value = submission.value;
let version = self.version;
spawn_local(async move {
let new_value = fut.await;
let canceled = untrack(move || canceled.get());
if !canceled {
value.set(Some(new_value));
}
input.set(None);
pending.set(false);
version.update(|n| *n += 1);
})
}
}
/// The set of all submissions to this multi-action.
pub fn submissions(&self) -> ReadSignal<Vec<Submission<I, O>>> {
self.submissions.read_only()
}
}
/// Creates an [MultiAction] to synchronize an imperative `async` call to the synchronous reactive system.
///
/// If youre trying to load data by running an `async` function reactively, you probably
/// want to use a [create_resource](leptos_reactive::create_resource) instead. If youre trying
/// to occasionally run an `async` function in response to something like a user clicking a button,
/// you're in the right place.
///
/// ```rust
/// # use leptos::*;
/// # let runtime = create_runtime();
/// async fn send_new_todo_to_api(task: String) -> usize {
/// // do something...
/// // return a task id
/// 42
/// }
/// let add_todo = create_multi_action(|task: &String| {
/// // `task` is given as `&String` because its value is available in `input`
/// send_new_todo_to_api(task.clone())
/// });
/// # if false {
///
/// add_todo.dispatch("Buy milk".to_string());
/// add_todo.dispatch("???".to_string());
/// add_todo.dispatch("Profit!!!".to_string());
///
/// assert_eq!(add_todo.submissions().get().len(), 3);
/// # }
/// # runtime.dispose();
/// ```
///
/// The input to the `async` function should always be a single value,
/// but it can be of any type. The argument is always passed by reference to the
/// function, because it is stored in [Submission::input] as well.
///
/// ```rust
/// # use leptos::*;
/// # let runtime = create_runtime();
/// // if there's a single argument, just use that
/// let action1 = create_multi_action(|input: &String| {
/// let input = input.clone();
/// async move { todo!() }
/// });
///
/// // if there are no arguments, use the unit type `()`
/// let action2 = create_multi_action(|input: &()| async { todo!() });
///
/// // if there are multiple arguments, use a tuple
/// let action3 =
/// create_multi_action(|input: &(usize, String)| async { todo!() });
/// # runtime.dispose();
/// ```
#[cfg_attr(feature = "tracing", tracing::instrument(level = "trace", skip_all))]
pub fn create_multi_action<I, O, F, Fu>(action_fn: F) -> MultiAction<I, O>
where
I: 'static,
O: 'static,
F: Fn(&I) -> Fu + 'static,
Fu: Future<Output = O> + 'static,
{
let version = create_rw_signal(0);
let submissions = create_rw_signal(Vec::new());
let action_fn = Rc::new(move |input: &I| {
let fut = action_fn(input);
Box::pin(fut) as Pin<Box<dyn Future<Output = O>>>
});
MultiAction(store_value(MultiActionState {
version,
submissions,
url: None,
action_fn,
}))
}
/// Creates an [MultiAction] that can be used to call a server function.
///
/// ```rust,ignore
/// # use leptos::*;
///
/// #[server(MyServerFn)]
/// async fn my_server_fn() -> Result<(), ServerFnError> {
/// todo!()
/// }
///
/// # let runtime = create_runtime();
/// let my_server_multi_action = create_server_multi_action::<MyServerFn>();
/// # runtime.dispose();
/// ```
#[cfg_attr(feature = "tracing", tracing::instrument(level = "trace", skip_all))]
pub fn create_server_multi_action<S>(
) -> MultiAction<S, Result<S::Output, ServerFnError<S::Error>>>
where
S: Clone + ServerFn,
{
#[cfg(feature = "ssr")]
let c = move |args: &S| S::run_body(args.clone());
#[cfg(not(feature = "ssr"))]
let c = move |args: &S| S::run_on_client(args.clone());
create_multi_action(c).using_server_fn::<S>()
}

View File

@@ -43,15 +43,6 @@ use std::{
task::{Context, Poll, Waker},
};
/// A reference-counted resource that only loads once.
///
/// Resources allow asynchronously loading data and serializing it from the server to the client,
/// so that it loads on the server, and is then deserialized on the client. This improves
/// performance by beginning data loading on the server when the request is made, rather than
/// beginning it on the client after WASM has been loaded.
///
/// You can access the value of the resource either synchronously using `.get()` or asynchronously
/// using `.await`.
#[derive(Debug)]
pub struct ArcOnceResource<T, Ser = JsonSerdeCodec> {
trigger: ArcTrigger,
@@ -89,12 +80,6 @@ where
<Ser as Encoder<T>>::Encoded: IntoEncodedString,
<Ser as Decoder<T>>::Encoded: FromEncodedStr,
{
/// Creates a new resource with the encoding `Ser`. If `blocking` is `true`, this is a blocking
/// resource.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
#[track_caller]
pub fn new_with_options(
fut: impl Future<Output = T> + Send + 'static,
@@ -302,17 +287,11 @@ where
<JsonSerdeCodec as Encoder<T>>::Encoded: IntoEncodedString,
<JsonSerdeCodec as Decoder<T>>::Encoded: FromEncodedStr,
{
/// Creates a resource using [`JsonSerdeCodec`] for encoding/decoding the value.
#[track_caller]
pub fn new(fut: impl Future<Output = T> + Send + 'static) -> Self {
ArcOnceResource::new_with_options(fut, false)
}
/// Creates a blocking resource using [`JsonSerdeCodec`] for encoding/decoding the value.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
#[track_caller]
pub fn new_blocking(fut: impl Future<Output = T> + Send + 'static) -> Self {
ArcOnceResource::new_with_options(fut, true)
@@ -328,7 +307,6 @@ T: Send + Sync + 'static,
<FromToStringCodec as Encoder<T>>::Encoded: IntoEncodedString,
<FromToStringCodec as Decoder<T>>::Encoded: FromEncodedStr,
{
/// Creates a resource using [`FromToStringCodec`] for encoding/decoding the value.
pub fn new_str(
fut: impl Future<Output = T> + Send + 'static
) -> Self
@@ -336,11 +314,6 @@ T: Send + Sync + 'static,
ArcOnceResource::new_with_options(fut, false)
}
/// Creates a blocking resource using [`FromToStringCodec`] for encoding/decoding the value.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
pub fn new_str_blocking(
fut: impl Future<Output = T> + Send + 'static
) -> Self
@@ -359,7 +332,6 @@ T: Send + Sync + 'static,
<JsonSerdeWasmCodec as Encoder<T>>::Encoded: IntoEncodedString,
<JsonSerdeWasmCodec as Decoder<T>>::Encoded: FromEncodedStr,
{
/// Creates a resource using [`JsonSerdeWasmCodec`] for encoding/decoding the value.
#[track_caller]
pub fn new_serde_wb(
fut: impl Future<Output = T> + Send + 'static
@@ -368,11 +340,6 @@ fut: impl Future<Output = T> + Send + 'static
ArcOnceResource::new_with_options(fut, false)
}
/// Creates a blocking resource using [`JsonSerdeWasmCodec`] for encoding/decoding the value.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
#[track_caller]
pub fn new_serde_wb_blocking(
fut: impl Future<Output = T> + Send + 'static
@@ -393,7 +360,6 @@ where
<MiniserdeCodec as Encoder<T>>::Encoded: IntoEncodedString,
<MiniserdeCodec as Decoder<T>>::Encoded: FromEncodedStr,
{
/// Creates a resource using [`MiniserdeCodec`] for encoding/decoding the value.
#[track_caller]
pub fn new_miniserde(
fut: impl Future<Output = T> + Send + 'static,
@@ -401,11 +367,6 @@ where
ArcOnceResource::new_with_options(fut, false)
}
/// Creates a blocking resource using [`MiniserdeCodec`] for encoding/decoding the value.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
#[track_caller]
pub fn new_miniserde_blocking(
fut: impl Future<Output = T> + Send + 'static,
@@ -424,7 +385,6 @@ T: Send + Sync + 'static,
<SerdeLite<JsonSerdeCodec> as Encoder<T>>::Encoded: IntoEncodedString,
<SerdeLite<JsonSerdeCodec> as Decoder<T>>::Encoded: FromEncodedStr,
{
/// Creates a resource using [`SerdeLite`] for encoding/decoding the value.
#[track_caller]
pub fn new_serde_lite(
fut: impl Future<Output = T> + Send + 'static
@@ -433,11 +393,6 @@ fut: impl Future<Output = T> + Send + 'static
ArcOnceResource::new_with_options(fut, false)
}
/// Creates a blocking resource using [`SerdeLite`] for encoding/decoding the value.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
#[track_caller]
pub fn new_serde_lite_blocking(
fut: impl Future<Output = T> + Send + 'static
@@ -459,17 +414,11 @@ where
<RkyvCodec as Encoder<T>>::Encoded: IntoEncodedString,
<RkyvCodec as Decoder<T>>::Encoded: FromEncodedStr,
{
/// Creates a resource using [`RkyvCodec`] for encoding/decoding the value.
#[track_caller]
pub fn new_rkyv(fut: impl Future<Output = T> + Send + 'static) -> Self {
ArcOnceResource::new_with_options(fut, false)
}
/// Creates a blocking resource using [`RkyvCodec`] for encoding/decoding the value.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
#[track_caller]
pub fn new_rkyv_blocking(
fut: impl Future<Output = T> + Send + 'static,
@@ -478,15 +427,6 @@ where
}
}
/// A resource that only loads once.
///
/// Resources allow asynchronously loading data and serializing it from the server to the client,
/// so that it loads on the server, and is then deserialized on the client. This improves
/// performance by beginning data loading on the server when the request is made, rather than
/// beginning it on the client after WASM has been loaded.
///
/// You can access the value of the resource either synchronously using `.get()` or asynchronously
/// using `.await`.
#[derive(Debug)]
pub struct OnceResource<T, Ser = JsonSerdeCodec> {
inner: ArenaItem<ArcOnceResource<T, Ser>>,
@@ -512,12 +452,6 @@ where
<Ser as Encoder<T>>::Encoded: IntoEncodedString,
<Ser as Decoder<T>>::Encoded: FromEncodedStr,
{
/// Creates a new resource with the encoding `Ser`. If `blocking` is `true`, this is a blocking
/// resource.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
#[track_caller]
pub fn new_with_options(
fut: impl Future<Output = T> + Send + 'static,
@@ -633,17 +567,11 @@ where
<JsonSerdeCodec as Encoder<T>>::Encoded: IntoEncodedString,
<JsonSerdeCodec as Decoder<T>>::Encoded: FromEncodedStr,
{
/// Creates a resource using [`JsonSerdeCodec`] for encoding/decoding the value.
#[track_caller]
pub fn new(fut: impl Future<Output = T> + Send + 'static) -> Self {
OnceResource::new_with_options(fut, false)
}
/// Creates a blocking resource using [`JsonSerdeCodec`] for encoding/decoding the value.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
#[track_caller]
pub fn new_blocking(fut: impl Future<Output = T> + Send + 'static) -> Self {
OnceResource::new_with_options(fut, true)
@@ -659,7 +587,6 @@ T: Send + Sync + 'static,
<FromToStringCodec as Encoder<T>>::Encoded: IntoEncodedString,
<FromToStringCodec as Decoder<T>>::Encoded: FromEncodedStr,
{
/// Creates a resource using [`FromToStringCodec`] for encoding/decoding the value.
pub fn new_str(
fut: impl Future<Output = T> + Send + 'static
) -> Self
@@ -667,11 +594,6 @@ T: Send + Sync + 'static,
OnceResource::new_with_options(fut, false)
}
/// Creates a blocking resource using [`FromToStringCodec`] for encoding/decoding the value.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
pub fn new_str_blocking(
fut: impl Future<Output = T> + Send + 'static
) -> Self
@@ -690,7 +612,6 @@ T: Send + Sync + 'static,
<JsonSerdeWasmCodec as Encoder<T>>::Encoded: IntoEncodedString,
<JsonSerdeWasmCodec as Decoder<T>>::Encoded: FromEncodedStr,
{
/// Creates a resource using [`JsonSerdeWasmCodec`] for encoding/decoding the value.
#[track_caller]
pub fn new_serde_wb(
fut: impl Future<Output = T> + Send + 'static
@@ -699,11 +620,6 @@ fut: impl Future<Output = T> + Send + 'static
OnceResource::new_with_options(fut, false)
}
/// Creates a blocking resource using [`JsonSerdeWasmCodec`] for encoding/decoding the value.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
#[track_caller]
pub fn new_serde_wb_blocking(
fut: impl Future<Output = T> + Send + 'static
@@ -724,7 +640,6 @@ where
<MiniserdeCodec as Encoder<T>>::Encoded: IntoEncodedString,
<MiniserdeCodec as Decoder<T>>::Encoded: FromEncodedStr,
{
/// Creates a resource using [`MiniserdeCodec`] for encoding/decoding the value.
#[track_caller]
pub fn new_miniserde(
fut: impl Future<Output = T> + Send + 'static,
@@ -732,11 +647,6 @@ where
OnceResource::new_with_options(fut, false)
}
/// Creates a blocking resource using [`MiniserdeCodec`] for encoding/decoding the value.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
#[track_caller]
pub fn new_miniserde_blocking(
fut: impl Future<Output = T> + Send + 'static,
@@ -755,7 +665,6 @@ T: Send + Sync + 'static,
<SerdeLite<JsonSerdeCodec> as Encoder<T>>::Encoded: IntoEncodedString,
<SerdeLite<JsonSerdeCodec> as Decoder<T>>::Encoded: FromEncodedStr,
{
/// Creates a resource using [`SerdeLite`] for encoding/decoding the value.
#[track_caller]
pub fn new_serde_lite(
fut: impl Future<Output = T> + Send + 'static
@@ -764,11 +673,6 @@ fut: impl Future<Output = T> + Send + 'static
OnceResource::new_with_options(fut, false)
}
/// Creates a blocking resource using [`SerdeLite`] for encoding/decoding the value.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
#[track_caller]
pub fn new_serde_lite_blocking(
fut: impl Future<Output = T> + Send + 'static
@@ -790,17 +694,11 @@ where
<RkyvCodec as Encoder<T>>::Encoded: IntoEncodedString,
<RkyvCodec as Decoder<T>>::Encoded: FromEncodedStr,
{
/// Creates a resource using [`RkyvCodec`] for encoding/decoding the value.
#[track_caller]
pub fn new_rkyv(fut: impl Future<Output = T> + Send + 'static) -> Self {
OnceResource::new_with_options(fut, false)
}
/// Creates a blocking resource using [`RkyvCodec`] for encoding/decoding the value.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
#[track_caller]
pub fn new_rkyv_blocking(
fut: impl Future<Output = T> + Send + 'static,

View File

@@ -37,12 +37,9 @@ use std::{
pub(crate) static IS_SUPPRESSING_RESOURCE_LOAD: AtomicBool =
AtomicBool::new(false);
/// Used to prevent resources from actually loading, in environments (like server route generation)
/// where they are not needed.
pub struct SuppressResourceLoad;
impl SuppressResourceLoad {
/// Prevents resources from loading until this is dropped.
pub fn new() -> Self {
IS_SUPPRESSING_RESOURCE_LOAD.store(true, Ordering::Relaxed);
Self
@@ -61,15 +58,6 @@ impl Drop for SuppressResourceLoad {
}
}
/// A reference-counted asynchronous resource.
///
/// Resources allow asynchronously loading data and serializing it from the server to the client,
/// so that it loads on the server, and is then deserialized on the client. This improves
/// performance by beginning data loading on the server when the request is made, rather than
/// beginning it on the client after WASM has been loaded.
///
/// You can access the value of the resource either synchronously using `.get()` or asynchronously
/// using `.await`.
pub struct ArcResource<T, Ser = JsonSerdeCodec> {
ser: PhantomData<Ser>,
refetch: ArcRwSignal<usize>,
@@ -206,21 +194,6 @@ where
<Ser as Encoder<T>>::Encoded: IntoEncodedString,
<Ser as Decoder<T>>::Encoded: FromEncodedStr,
{
/// Creates a new resource with the encoding `Ser`.
///
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
/// generate a new [`Future`] to load data.
///
/// On creation, if you are on the server, this will run the `fetcher` once to generate
/// a `Future` whose value will be serialized from the server to the client. If you are on
/// the client, the initial value will be deserialized without re-running that async task.
///
/// If `blocking` is `true`, this is a blocking resource.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
#[track_caller]
pub fn new_with_options<S, Fut>(
source: impl Fn() -> S + Send + Sync + 'static,
@@ -305,8 +278,6 @@ where
}
}
/// 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
@@ -380,13 +351,6 @@ where
T: Send + Sync + 'static,
E: Send + Sync + Clone + 'static,
{
/// Applies the given function when a resource that returns `Result<T, E>`
/// has resolved and loaded an `Ok(_)`, rather than requiring nested `.map()`
/// calls over the `Option<Result<_, _>>` returned by the resource.
///
/// This is useful when used with features like server functions, in conjunction
/// with `<ErrorBoundary/>` and `<Suspense/>`, when these other components are
/// left to handle the `None` and `Err(_)` states.
#[track_caller]
pub fn and_then<U>(&self, f: impl FnOnce(&T) -> U) -> Option<Result<U, E>> {
self.map(|data| data.as_ref().map(f).map_err(|e| e.clone()))
@@ -403,15 +367,6 @@ where
<JsonSerdeCodec as Encoder<T>>::Encoded: IntoEncodedString,
<JsonSerdeCodec as Decoder<T>>::Encoded: FromEncodedStr,
{
/// Creates a new resource with the encoding [`JsonSerdeCodec`].
///
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
/// generate a new [`Future`] to load data.
///
/// On creation, if you are on the server, this will run the `fetcher` once to generate
/// a `Future` whose value will be serialized from the server to the client. If you are on
/// the client, the initial value will be deserialized without re-running that async task.
#[track_caller]
pub fn new<S, Fut>(
source: impl Fn() -> S + Send + Sync + 'static,
@@ -425,19 +380,6 @@ where
ArcResource::new_with_options(source, fetcher, false)
}
/// Creates a new blocking resource with the encoding [`JsonSerdeCodec`].
///
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
/// generate a new [`Future`] to load data.
///
/// On creation, if you are on the server, this will run the `fetcher` once to generate
/// a `Future` whose value will be serialized from the server to the client. If you are on
/// the client, the initial value will be deserialized without re-running that async task.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
#[track_caller]
pub fn new_blocking<S, Fut>(
source: impl Fn() -> S + Send + Sync + 'static,
@@ -460,15 +402,6 @@ where
<FromToStringCodec as Encoder<T>>::Encoded: IntoEncodedString,
<FromToStringCodec as Decoder<T>>::Encoded: FromEncodedStr,
{
/// Creates a new resource with the encoding [`FromToStringCodec`].
///
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
/// generate a new [`Future`] to load data.
///
/// On creation, if you are on the server, this will run the `fetcher` once to generate
/// a `Future` whose value will be serialized from the server to the client. If you are on
/// the client, the initial value will be deserialized without re-running that async task.
pub fn new_str<S, Fut>(
source: impl Fn() -> S + Send + Sync + 'static,
fetcher: impl Fn(S) -> Fut + Send + Sync + 'static,
@@ -481,19 +414,6 @@ where
ArcResource::new_with_options(source, fetcher, false)
}
/// Creates a new blocking resource with the encoding [`FromToStringCodec`].
///
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
/// generate a new [`Future`] to load data.
///
/// On creation, if you are on the server, this will run the `fetcher` once to generate
/// a `Future` whose value will be serialized from the server to the client. If you are on
/// the client, the initial value will be deserialized without re-running that async task.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
pub fn new_str_blocking<S, Fut>(
source: impl Fn() -> S + Send + Sync + 'static,
fetcher: impl Fn(S) -> Fut + Send + Sync + 'static,
@@ -516,15 +436,6 @@ where
<JsonSerdeWasmCodec as Encoder<T>>::Encoded: IntoEncodedString,
<JsonSerdeWasmCodec as Decoder<T>>::Encoded: FromEncodedStr,
{
/// Creates a new resource with the encoding [`JsonSerdeWasmCodec`].
///
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
/// generate a new [`Future`] to load data.
///
/// On creation, if you are on the server, this will run the `fetcher` once to generate
/// a `Future` whose value will be serialized from the server to the client. If you are on
/// the client, the initial value will be deserialized without re-running that async task.
#[track_caller]
pub fn new_serde_wb<S, Fut>(
source: impl Fn() -> S + Send + Sync + 'static,
@@ -538,19 +449,6 @@ where
ArcResource::new_with_options(source, fetcher, false)
}
/// Creates a new blocking resource with the encoding [`JsonSerdeWasmCodec`].
///
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
/// generate a new [`Future`] to load data.
///
/// On creation, if you are on the server, this will run the `fetcher` once to generate
/// a `Future` whose value will be serialized from the server to the client. If you are on
/// the client, the initial value will be deserialized without re-running that async task.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
#[track_caller]
pub fn new_serde_wb_blocking<S, Fut>(
source: impl Fn() -> S + Send + Sync + 'static,
@@ -575,15 +473,6 @@ where
<MiniserdeCodec as Encoder<T>>::Encoded: IntoEncodedString,
<MiniserdeCodec as Decoder<T>>::Encoded: FromEncodedStr,
{
/// Creates a new resource with the encoding [`MiniserdeCodec`].
///
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
/// generate a new [`Future`] to load data.
///
/// On creation, if you are on the server, this will run the `fetcher` once to generate
/// a `Future` whose value will be serialized from the server to the client. If you are on
/// the client, the initial value will be deserialized without re-running that async task.
#[track_caller]
pub fn new_miniserde<S, Fut>(
source: impl Fn() -> S + Send + Sync + 'static,
@@ -597,19 +486,6 @@ where
ArcResource::new_with_options(source, fetcher, false)
}
/// Creates a new blocking resource with the encoding [`MiniserdeCodec`].
///
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
/// generate a new [`Future`] to load data.
///
/// On creation, if you are on the server, this will run the `fetcher` once to generate
/// a `Future` whose value will be serialized from the server to the client. If you are on
/// the client, the initial value will be deserialized without re-running that async task.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
#[track_caller]
pub fn new_miniserde_blocking<S, Fut>(
source: impl Fn() -> S + Send + Sync + 'static,
@@ -633,15 +509,6 @@ where
<SerdeLite<JsonSerdeCodec> as Encoder<T>>::Encoded: IntoEncodedString,
<SerdeLite<JsonSerdeCodec> as Decoder<T>>::Encoded: FromEncodedStr,
{
/// Creates a new resource with the encoding [`SerdeLite`].
///
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
/// generate a new [`Future`] to load data.
///
/// On creation, if you are on the server, this will run the `fetcher` once to generate
/// a `Future` whose value will be serialized from the server to the client. If you are on
/// the client, the initial value will be deserialized without re-running that async task.
#[track_caller]
pub fn new_serde_lite<S, Fut>(
source: impl Fn() -> S + Send + Sync + 'static,
@@ -655,19 +522,6 @@ where
ArcResource::new_with_options(source, fetcher, false)
}
/// Creates a new blocking resource with the encoding [`SerdeLite`].
///
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
/// generate a new [`Future`] to load data.
///
/// On creation, if you are on the server, this will run the `fetcher` once to generate
/// a `Future` whose value will be serialized from the server to the client. If you are on
/// the client, the initial value will be deserialized without re-running that async task.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
#[track_caller]
pub fn new_serde_lite_blocking<S, Fut>(
source: impl Fn() -> S + Send + Sync + 'static,
@@ -693,15 +547,6 @@ where
<RkyvCodec as Encoder<T>>::Encoded: IntoEncodedString,
<RkyvCodec as Decoder<T>>::Encoded: FromEncodedStr,
{
/// Creates a new resource with the encoding [`RkyvCodec`].
///
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
/// generate a new [`Future`] to load data.
///
/// On creation, if you are on the server, this will run the `fetcher` once to generate
/// a `Future` whose value will be serialized from the server to the client. If you are on
/// the client, the initial value will be deserialized without re-running that async task.
#[track_caller]
pub fn new_rkyv<S, Fut>(
source: impl Fn() -> S + Send + Sync + 'static,
@@ -715,19 +560,6 @@ where
ArcResource::new_with_options(source, fetcher, false)
}
/// Creates a new blocking resource with the encoding [`RkyvCodec`].
///
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
/// generate a new [`Future`] to load data.
///
/// On creation, if you are on the server, this will run the `fetcher` once to generate
/// a `Future` whose value will be serialized from the server to the client. If you are on
/// the client, the initial value will be deserialized without re-running that async task.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
#[track_caller]
pub fn new_rkyv_blocking<S, Fut>(
source: impl Fn() -> S + Send + Sync + 'static,
@@ -758,22 +590,11 @@ impl<T, Ser> ArcResource<T, Ser>
where
T: 'static,
{
/// Returns a new [`Future`] that is ready when the resource has loaded, and accesses its inner
/// value by reference.
pub fn by_ref(&self) -> AsyncDerivedRefFuture<T> {
self.data.by_ref()
}
}
/// An asynchronous resource.
///
/// Resources allow asynchronously loading data and serializing it from the server to the client,
/// so that it loads on the server, and is then deserialized on the client. This improves
/// performance by beginning data loading on the server when the request is made, rather than
/// beginning it on the client after WASM has been loaded.
///
/// You can access the value of the resource either synchronously using `.get()` or asynchronously
/// using `.await`.
pub struct Resource<T, Ser = JsonSerdeCodec>
where
T: Send + Sync + 'static,
@@ -886,15 +707,6 @@ where
<FromToStringCodec as Decoder<T>>::Encoded: FromEncodedStr,
T: Send + Sync,
{
/// Creates a new resource with the encoding [`FromToStringCodec`].
///
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
/// generate a new [`Future`] to load data.
///
/// On creation, if you are on the server, this will run the `fetcher` once to generate
/// a `Future` whose value will be serialized from the server to the client. If you are on
/// the client, the initial value will be deserialized without re-running that async task.
#[track_caller]
pub fn new_str<S, Fut>(
source: impl Fn() -> S + Send + Sync + 'static,
@@ -908,19 +720,6 @@ where
Resource::new_with_options(source, fetcher, false)
}
/// Creates a new blocking resource with the encoding [`FromToStringCodec`].
///
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
/// generate a new [`Future`] to load data.
///
/// On creation, if you are on the server, this will run the `fetcher` once to generate
/// a `Future` whose value will be serialized from the server to the client. If you are on
/// the client, the initial value will be deserialized without re-running that async task.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
#[track_caller]
pub fn new_str_blocking<S, Fut>(
source: impl Fn() -> S + Send + Sync + 'static,
@@ -946,15 +745,6 @@ where
<JsonSerdeCodec as Decoder<T>>::Encoded: FromEncodedStr,
T: Send + Sync,
{
/// Creates a new resource with the encoding [`JsonSerdeCodec`].
///
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
/// generate a new [`Future`] to load data.
///
/// On creation, if you are on the server, this will run the `fetcher` once to generate
/// a `Future` whose value will be serialized from the server to the client. If you are on
/// the client, the initial value will be deserialized without re-running that async task.
#[track_caller]
pub fn new<S, Fut>(
source: impl Fn() -> S + Send + Sync + 'static,
@@ -968,19 +758,6 @@ where
Resource::new_with_options(source, fetcher, false)
}
/// Creates a new blocking resource with the encoding [`JsonSerdeCodec`].
///
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
/// generate a new [`Future`] to load data.
///
/// On creation, if you are on the server, this will run the `fetcher` once to generate
/// a `Future` whose value will be serialized from the server to the client. If you are on
/// the client, the initial value will be deserialized without re-running that async task.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
#[track_caller]
pub fn new_blocking<S, Fut>(
source: impl Fn() -> S + Send + Sync + 'static,
@@ -1005,15 +782,6 @@ where
<JsonSerdeWasmCodec as Decoder<T>>::Encoded: FromEncodedStr,
T: Send + Sync,
{
/// Creates a new resource with the encoding [`JsonSerdeWasmCodec`].
///
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
/// generate a new [`Future`] to load data.
///
/// On creation, if you are on the server, this will run the `fetcher` once to generate
/// a `Future` whose value will be serialized from the server to the client. If you are on
/// the client, the initial value will be deserialized without re-running that async task.
pub fn new_serde_wb<S, Fut>(
source: impl Fn() -> S + Send + Sync + 'static,
fetcher: impl Fn(S) -> Fut + Send + Sync + 'static,
@@ -1026,19 +794,6 @@ where
Resource::new_with_options(source, fetcher, false)
}
/// Creates a new blocking resource with the encoding [`JsonSerdeWasmCodec`].
///
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
/// generate a new [`Future`] to load data.
///
/// On creation, if you are on the server, this will run the `fetcher` once to generate
/// a `Future` whose value will be serialized from the server to the client. If you are on
/// the client, the initial value will be deserialized without re-running that async task.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
pub fn new_serde_wb_blocking<S, Fut>(
source: impl Fn() -> S + Send + Sync + 'static,
fetcher: impl Fn(S) -> Fut + Send + Sync + 'static,
@@ -1064,15 +819,6 @@ where
<MiniserdeCodec as Decoder<T>>::Encoded: FromEncodedStr,
T: Send + Sync,
{
/// Creates a new resource with the encoding [`MiniserdeCodec`].
///
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
/// generate a new [`Future`] to load data.
///
/// On creation, if you are on the server, this will run the `fetcher` once to generate
/// a `Future` whose value will be serialized from the server to the client. If you are on
/// the client, the initial value will be deserialized without re-running that async task.
pub fn new_miniserde<S, Fut>(
source: impl Fn() -> S + Send + Sync + 'static,
fetcher: impl Fn(S) -> Fut + Send + Sync + 'static,
@@ -1084,31 +830,6 @@ where
{
Resource::new_with_options(source, fetcher, false)
}
/// Creates a new blocking resource with the encoding [`MiniserdeCodec`].
///
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
/// generate a new [`Future`] to load data.
///
/// On creation, if you are on the server, this will run the `fetcher` once to generate
/// a `Future` whose value will be serialized from the server to the client. If you are on
/// the client, the initial value will be deserialized without re-running that async task.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
pub fn new_miniserde_blocking<S, Fut>(
source: impl Fn() -> S + Send + Sync + 'static,
fetcher: impl Fn(S) -> Fut + Send + Sync + 'static,
) -> Self
where
S: PartialEq + Clone + Send + Sync + 'static,
T: Send + Sync + 'static,
Fut: Future<Output = T> + Send + 'static,
{
Resource::new_with_options(source, fetcher, true)
}
}
#[cfg(feature = "serde-lite")]
@@ -1122,15 +843,6 @@ where
<SerdeLite<JsonSerdeCodec> as Decoder<T>>::Encoded: FromEncodedStr,
T: Send + Sync,
{
/// Creates a new resource with the encoding [`SerdeLite`].
///
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
/// generate a new [`Future`] to load data.
///
/// On creation, if you are on the server, this will run the `fetcher` once to generate
/// a `Future` whose value will be serialized from the server to the client. If you are on
/// the client, the initial value will be deserialized without re-running that async task.
pub fn new_serde_lite<S, Fut>(
source: impl Fn() -> S + Send + Sync + 'static,
fetcher: impl Fn(S) -> Fut + Send + Sync + 'static,
@@ -1143,19 +855,6 @@ where
Resource::new_with_options(source, fetcher, false)
}
/// Creates a new blocking resource with the encoding [`SerdeLite`].
///
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
/// generate a new [`Future`] to load data.
///
/// On creation, if you are on the server, this will run the `fetcher` once to generate
/// a `Future` whose value will be serialized from the server to the client. If you are on
/// the client, the initial value will be deserialized without re-running that async task.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
pub fn new_serde_lite_blocking<S, Fut>(
source: impl Fn() -> S + Send + Sync + 'static,
fetcher: impl Fn(S) -> Fut + Send + Sync + 'static,
@@ -1181,15 +880,6 @@ where
<RkyvCodec as Decoder<T>>::Encoded: FromEncodedStr,
T: Send + Sync,
{
/// Creates a new resource with the encoding [`RkyvCodec`].
///
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
/// generate a new [`Future`] to load data.
///
/// On creation, if you are on the server, this will run the `fetcher` once to generate
/// a `Future` whose value will be serialized from the server to the client. If you are on
/// the client, the initial value will be deserialized without re-running that async task.
pub fn new_rkyv<S, Fut>(
source: impl Fn() -> S + Send + Sync + 'static,
fetcher: impl Fn(S) -> Fut + Send + Sync + 'static,
@@ -1202,19 +892,6 @@ where
Resource::new_with_options(source, fetcher, false)
}
/// Creates a new blocking resource with the encoding [`RkyvCodec`].
///
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
/// generate a new [`Future`] to load data.
///
/// On creation, if you are on the server, this will run the `fetcher` once to generate
/// a `Future` whose value will be serialized from the server to the client. If you are on
/// the client, the initial value will be deserialized without re-running that async task.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
pub fn new_rkyv_blocking<S, Fut>(
source: impl Fn() -> S + Send + Sync + 'static,
fetcher: impl Fn(S) -> Fut + Send + Sync + 'static,
@@ -1238,21 +915,6 @@ where
<Ser as Decoder<T>>::Encoded: FromEncodedStr,
T: Send + Sync,
{
/// Creates a new resource with the encoding `Ser`.
///
/// This takes a `source` function and a `fetcher`. The resource memoizes and reactively tracks
/// the value returned by `source`. Whenever that value changes, it will run the `fetcher` to
/// generate a new [`Future`] to load data.
///
/// On creation, if you are on the server, this will run the `fetcher` once to generate
/// a `Future` whose value will be serialized from the server to the client. If you are on
/// the client, the initial value will be deserialized without re-running that async task.
///
/// If `blocking` is `true`, this is a blocking resource.
///
/// Blocking resources prevent any of the HTTP response from being sent until they have loaded.
/// This is useful if you need their data to set HTML document metadata or information that
/// needs to appear in HTTP headers.
#[track_caller]
pub fn new_with_options<S, Fut>(
source: impl Fn() -> S + Send + Sync + 'static,
@@ -1275,8 +937,6 @@ where
}
}
/// Synchronously, reactively reads the current value of the resource and applies the function
/// `f` to its value if it is `Some(_)`.
pub fn map<U>(&self, f: impl FnOnce(&T) -> U) -> Option<U> {
self.data
.try_with(|n| n.as_ref().map(|n| Some(f(n))))?
@@ -1301,13 +961,6 @@ where
T: Send + Sync,
E: Send + Sync + Clone,
{
/// Applies the given function when a resource that returns `Result<T, E>`
/// has resolved and loaded an `Ok(_)`, rather than requiring nested `.map()`
/// calls over the `Option<Result<_, _>>` returned by the resource.
///
/// This is useful when used with features like server functions, in conjunction
/// with `<ErrorBoundary/>` and `<Suspense/>`, when these other components are
/// left to handle the `None` and `Err(_)` states.
#[track_caller]
pub fn and_then<U>(&self, f: impl FnOnce(&T) -> U) -> Option<Result<U, E>> {
self.map(|data| data.as_ref().map(f).map_err(|e| e.clone()))
@@ -1331,8 +984,6 @@ impl<T, Ser> Resource<T, Ser>
where
T: Send + Sync + 'static,
{
/// Returns a new [`Future`] that is ready when the resource has loaded, and accesses its inner
/// value by reference.
pub fn by_ref(&self) -> AsyncDerivedRefFuture<T> {
self.data.by_ref()
}

View File

@@ -31,7 +31,6 @@ pub struct SharedValue<T, Ser = JsonSerdeCodec> {
}
impl<T, Ser> SharedValue<T, Ser> {
/// Returns the inner value.
pub fn into_inner(self) -> T {
self.value
}
@@ -47,12 +46,6 @@ where
<<JsonSerdeCodec as codee::Decoder<T>>::Encoded as FromEncodedStr>::DecodingError:
Debug,
{
/// Wraps the initial value.
///
/// If this is on the server, the function will be invoked and the value serialized. When it runs
/// on the client, it will be deserialized without running the function again.
///
/// This uses the [`JsonSerdeCodec`] encoding.
pub fn new(initial: impl FnOnce() -> T) -> Self {
SharedValue::new_with_encoding(initial)
}
@@ -68,12 +61,6 @@ where
<<FromToStringCodec as codee::Decoder<T>>::Encoded as FromEncodedStr>::DecodingError:
Debug,
{
/// Wraps the initial value.
///
/// If this is on the server, the function will be invoked and the value serialized. When it runs
/// on the client, it will be deserialized without running the function again.
///
/// This uses the [`FromToStringCodec`] encoding.
pub fn new_str(initial: impl FnOnce() -> T) -> Self {
SharedValue::new_with_encoding(initial)
}
@@ -90,13 +77,7 @@ where
<<SerdeLite<JsonSerdeCodec> as codee::Decoder<T>>::Encoded as FromEncodedStr>::DecodingError:
Debug,
{
/// Wraps the initial value.
///
/// If this is on the server, the function will be invoked and the value serialized. When it runs
/// on the client, it will be deserialized without running the function again.
///
/// This uses the [`SerdeLite`] encoding.
pub fn new_serde_lite(initial: impl FnOnce() -> T) -> Self {
pub fn new(initial: impl FnOnce() -> T) -> Self {
SharedValue::new_with_encoding(initial)
}
}
@@ -112,13 +93,7 @@ where
<<JsonSerdeWasmCodec as codee::Decoder<T>>::Encoded as FromEncodedStr>::DecodingError:
Debug,
{
/// Wraps the initial value.
///
/// If this is on the server, the function will be invoked and the value serialized. When it runs
/// on the client, it will be deserialized without running the function again.
///
/// This uses the [`JsonSerdeWasmCodec`] encoding.
pub fn new_serde_wb(initial: impl FnOnce() -> T) -> Self {
pub fn new(initial: impl FnOnce() -> T) -> Self {
SharedValue::new_with_encoding(initial)
}
}
@@ -134,13 +109,7 @@ where
<<MiniserdeCodec as codee::Decoder<T>>::Encoded as FromEncodedStr>::DecodingError:
Debug,
{
/// Wraps the initial value.
///
/// If this is on the server, the function will be invoked and the value serialized. When it runs
/// on the client, it will be deserialized without running the function again.
///
/// This uses the [`MiniserdeCodec`] encoding.
pub fn new_miniserde(initial: impl FnOnce() -> T) -> Self {
pub fn new(initial: impl FnOnce() -> T) -> Self {
SharedValue::new_with_encoding(initial)
}
}
@@ -156,13 +125,7 @@ where
<<RkyvCodec as codee::Decoder<T>>::Encoded as FromEncodedStr>::DecodingError:
Debug,
{
/// Wraps the initial value.
///
/// If this is on the server, the function will be invoked and the value serialized. When it runs
/// on the client, it will be deserialized without running the function again.
///
/// This uses the [`RkyvCodec`] encoding.
pub fn new_rkyv(initial: impl FnOnce() -> T) -> Self {
pub fn new(initial: impl FnOnce() -> T) -> Self {
SharedValue::new_with_encoding(initial)
}
}
@@ -177,12 +140,6 @@ where
<<Ser as codee::Decoder<T>>::Encoded as FromEncodedStr>::DecodingError:
Debug,
{
/// Wraps the initial value.
///
/// If this is on the server, the function will be invoked and the value serialized. When it runs
/// on the client, it will be deserialized without running the function again.
///
/// This uses `Ser` as an encoding.
pub fn new_with_encoding(initial: impl FnOnce() -> T) -> Self {
let value: T;
#[cfg(feature = "hydration")]

View File

@@ -1,6 +1,6 @@
[package]
name = "leptos_meta"
version = "0.7.0-rc1"
version = "0.7.0-gamma3"
authors = ["Greg Johnston"]
license = "MIT"
repository = "https://github.com/leptos-rs/leptos"
@@ -10,16 +10,16 @@ edition.workspace = true
[dependencies]
leptos = { workspace = true }
once_cell = "1.20"
once_cell = "1.19"
or_poisoned = { workspace = true }
indexmap = "2.6"
indexmap = "2.3"
send_wrapper = "0.6.0"
tracing = { version = "0.1.40", optional = true }
wasm-bindgen = "0.2.95"
futures = "0.3.31"
wasm-bindgen = "0.2.93"
futures = "0.3.30"
[dependencies.web-sys]
version = "0.3.72"
version = "0.3.70"
features = ["HtmlLinkElement", "HtmlMetaElement", "HtmlTitleElement"]
[features]

View File

@@ -54,7 +54,7 @@ pub fn HashedStylesheet(
path.parent().map(|p| p.to_path_buf()).unwrap_or_default()
})
.unwrap_or_default()
.join(options.hash_file.as_ref());
.join(&options.hash_file);
if hash_path.exists() {
let hashes = std::fs::read_to_string(&hash_path)
.expect("failed to read hash file");

View File

@@ -1,6 +1,6 @@
[package]
name = "next_tuple"
version = "0.1.0-rc1"
version = "0.1.0-gamma3"
authors = ["Greg Johnston"]
license = "MIT"
readme = "../README.md"

View File

@@ -1,10 +1,6 @@
//! Defines a trait that allows you to extend a tuple, by returning
//! a new tuple with an element of an arbitrary type added.
#![no_std]
#![allow(non_snake_case)]
#![forbid(unsafe_code)]
#![deny(missing_docs)]
/// Allows extending a tuple, or creating a new tuple, by adding the next value.
pub trait NextTuple {

View File

@@ -10,7 +10,7 @@ edition.workspace = true
[dependencies]
serde = "1.0"
thiserror = "2.0"
thiserror = "1.0"
[dev-dependencies]
serde_json = "1.0"

View File

@@ -1,6 +1,6 @@
[package]
name = "reactive_graph"
version = "0.1.0-rc1"
version = "0.1.0-gamma3"
authors = ["Greg Johnston"]
license = "MIT"
readme = "../README.md"
@@ -12,23 +12,23 @@ edition.workspace = true
[dependencies]
any_spawner = { workspace = true }
or_poisoned = { workspace = true }
futures = "0.3.31"
futures = "0.3.30"
hydration_context = { workspace = true, optional = true }
pin-project-lite = "0.2.15"
pin-project-lite = "0.2.14"
rustc-hash = "2.0"
serde = { version = "1.0", features = ["derive"], optional = true }
slotmap = "1.0"
thiserror = "2.0"
thiserror = "1.0"
tracing = { version = "0.1.40", optional = true }
guardian = "1.2"
async-lock = "3.4.0"
send_wrapper = { version = "0.6.0", features = ["futures"] }
[target.'cfg(all(target_arch = "wasm32", target_os = "unknown"))'.dependencies]
web-sys = "0.3.72"
web-sys = "0.3.70"
[dev-dependencies]
tokio = { version = "1.41", features = ["rt-multi-thread", "macros"] }
tokio = { version = "1.39", features = ["rt-multi-thread", "macros"] }
tokio-test = { version = "0.4.4" }
any_spawner = { workspace = true, features = ["futures-executor", "tokio"] }

View File

@@ -6,7 +6,7 @@ use crate::{
SyncStorage,
},
signal::{ArcRwSignal, RwSignal},
traits::{DefinedAt, Dispose, Get, GetUntracked, GetValue, Set, Update},
traits::{DefinedAt, Dispose, Get, GetUntracked, GetValue, Update},
unwrap_signal,
};
use any_spawner::Executor;
@@ -202,15 +202,6 @@ where
defined_at: Location::caller(),
}
}
/// Clears the value of the action, setting its current value to `None`.
///
/// This has no other effect: i.e., it will not cancel in-flight actions, set the
/// input, etc.
#[track_caller]
pub fn clear(&self) {
self.value.set(None);
}
}
/// A handle that allows aborting an in-flight action. It is returned from [`Action::dispatch`] or
@@ -687,22 +678,6 @@ where
}
}
impl<I, O, S> Action<I, O, S>
where
I: 'static,
O: 'static,
S: Storage<ArcAction<I, O>>,
{
/// Clears the value of the action, setting its current value to `None`.
///
/// This has no other effect: i.e., it will not cancel in-flight actions, set the
/// input, etc.
#[track_caller]
pub fn clear(&self) {
self.inner.try_with_value(|inner| inner.value.set(None));
}
}
impl<I, O> Action<I, O, LocalStorage>
where
I: 'static,

View File

@@ -286,15 +286,10 @@ macro_rules! spawn_derived {
let mut first_run = {
let (ready_tx, ready_rx) = oneshot::channel();
if !was_ready {
AsyncTransition::register(ready_rx);
}
AsyncTransition::register(ready_rx);
Some(ready_tx)
};
if was_ready {
first_run.take();
}
// begin loading eagerly but asynchronously, if not already loaded
if !was_ready {
any_subscriber.mark_dirty();
@@ -344,9 +339,7 @@ macro_rules! spawn_derived {
// register with global transition listener, if any
let ready_tx = first_run.take().unwrap_or_else(|| {
let (ready_tx, ready_rx) = oneshot::channel();
if !was_ready {
AsyncTransition::register(ready_rx);
}
AsyncTransition::register(ready_rx);
ready_tx
});

Some files were not shown because too many files have changed in this diff Show More