Compare commits

..

1 Commits

Author SHA1 Message Date
Greg Johnston
a74b3e2ddc Fix <option> and <use> top-level types in SSR 2023-01-30 19:15:06 -05:00
77 changed files with 593 additions and 1528 deletions

View File

@@ -8,7 +8,7 @@
default_to_workspace = false
[tasks.ci]
dependencies = ["build", "check-examples", "test"]
dependencies = ["build", "build-examples", "test"]
[tasks.build]
clear = true
@@ -19,24 +19,22 @@ command = "cargo"
args = ["+nightly", "build-all-features"]
install_crate = "cargo-all-features"
[tasks.check-examples]
[tasks.build-examples]
clear = true
dependencies = [
{ name = "check", path = "examples/counter" },
{ name = "check", path = "examples/counter_isomorphic" },
{ name = "check", path = "examples/counter_without_macros" },
{ name = "check", path = "examples/counters" },
{ name = "check", path = "examples/counters_stable" },
{ name = "check", path = "examples/errors_axum" },
{ name = "check", path = "examples/fetch" },
{ name = "check", path = "examples/hackernews" },
{ name = "check", path = "examples/hackernews_axum" },
{ name = "check", path = "examples/parent_child" },
{ name = "check", path = "examples/router" },
{ name = "check", path = "examples/tailwind" },
{ name = "check", path = "examples/todo_app_sqlite" },
{ name = "check", path = "examples/todo_app_sqlite_axum" },
{ name = "check", path = "examples/todomvc" },
{ name = "build", path = "examples/counter" },
{ name = "build", path = "examples/counter_isomorphic" },
{ name = "build", path = "examples/counters" },
{ name = "build", path = "examples/counters_stable" },
{ name = "build", path = "examples/fetch" },
{ name = "build", path = "examples/hackernews" },
{ name = "build", path = "examples/hackernews_axum" },
{ name = "build", path = "examples/parent_child" },
{ name = "build", path = "examples/router" },
{ name = "build", path = "examples/tailwind" },
{ name = "build", path = "examples/todo_app_sqlite" },
{ name = "build", path = "examples/todo_app_sqlite_axum" },
{ name = "build", path = "examples/todomvc" },
]
[tasks.test]

View File

@@ -2,8 +2,3 @@
command = "cargo"
args = ["+nightly", "build-all-features"]
install_crate = "cargo-all-features"
[tasks.check]
command = "cargo"
args = ["+nightly", "check-all-features"]
install_crate = "cargo-all-features"

View File

@@ -2,8 +2,3 @@
command = "cargo"
args = ["+nightly", "build-all-features"]
install_crate = "cargo-all-features"
[tasks.check]
command = "cargo"
args = ["+nightly", "check-all-features"]
install_crate = "cargo-all-features"

View File

@@ -1,9 +0,0 @@
[tasks.build]
command = "cargo"
args = ["+nightly", "build-all-features"]
install_crate = "cargo-all-features"
[tasks.check]
command = "cargo"
args = ["+nightly", "check-all-features"]
install_crate = "cargo-all-features"

View File

@@ -2,8 +2,3 @@
command = "cargo"
args = ["+nightly", "build-all-features"]
install_crate = "cargo-all-features"
[tasks.check]
command = "cargo"
args = ["+nightly", "check-all-features"]
install_crate = "cargo-all-features"

View File

@@ -1,94 +0,0 @@
[package]
name = "errors_axum"
version = "0.1.0"
edition = "2021"
[lib]
crate-type = ["cdylib", "rlib"]
[dependencies]
anyhow = "1.0.66"
console_log = "0.2.0"
console_error_panic_hook = "0.1.7"
futures = "0.3.25"
cfg-if = "1.0.0"
leptos = { path = "../../../leptos/leptos", default-features = false, features = [
"serde",
] }
leptos_axum = { path = "../../../leptos/integrations/axum", default-features = false, optional = true }
leptos_meta = { path = "../../../leptos/meta", default-features = false }
leptos_router = { path = "../../../leptos/router", default-features = false }
leptos_reactive = { path = "../../../leptos/leptos_reactive", default-features = false }
log = "0.4.17"
simple_logger = "4.0.0"
serde = { version = "1.0.148", features = ["derive"] }
serde_json = "1.0.89"
gloo-net = { version = "0.2.5", features = ["http"] }
reqwest = { version = "0.11.13", features = ["json"] }
axum = { version = "0.6.1", optional = true }
tower = { version = "0.4.13", optional = true }
tower-http = { version = "0.3.4", features = ["fs"], optional = true }
tokio = { version = "1.22.0", features = ["full"], optional = true }
http = { version = "0.2.8" }
thiserror = "1.0.38"
tracing = "0.1.37"
[features]
default = ["csr"]
csr = ["leptos/csr", "leptos_meta/csr", "leptos_router/csr"]
hydrate = ["leptos/hydrate", "leptos_meta/hydrate", "leptos_router/hydrate"]
ssr = ["dep:axum", "dep:tower", "dep:tower-http", "dep:tokio", "leptos/ssr", "leptos_meta/ssr", "leptos_router/ssr", "dep:leptos_axum"]
[package.metadata.cargo-all-features]
denylist = [
"axum",
"tower",
"tower-http",
"tokio",
"leptos_axum",
]
skip_feature_sets = [["csr", "ssr"], ["csr", "hydrate"], ["ssr", "hydrate"]]
[package.metadata.leptos]
# The name used by wasm-bindgen/cargo-leptos for the JS/WASM bundle. Defaults to the crate name
output-name = "errors_axum"
# The site root folder is where cargo-leptos generate all output. WARNING: all content of this folder will be erased on a rebuild. Use it in your server setup.
site-root = "target/site"
# The site-root relative folder where all compiled output (JS, WASM and CSS) is written
# Defaults to pkg
site-pkg-dir = "pkg"
# [Optional] The source CSS file. If it ends with .sass or .scss then it will be compiled by dart-sass into CSS. The CSS is optimized by Lightning CSS before being written to <site-root>/<site-pkg>/app.css
style-file = "./style.css"
# [Optional] Files in the asset-dir will be copied to the site-root directory
assets-dir = "public"
# The IP and port (ex: 127.0.0.1:3000) where the server serves the content. Use it in your server setup.
site-addr = "127.0.0.1:3000"
# The port to use for automatic reload monitoring
reload-port = 3001
# [Optional] Command to use when running end2end tests. It will run in the end2end dir.
end2end-cmd = "npx playwright test"
# The browserlist query used for optimizing the CSS.
browserquery = "defaults"
# Set by cargo-leptos watch when building with tha tool. Controls whether autoreload JS will be included in the head
watch = false
# The environment Leptos will run in, usually either "DEV" or "PROD"
env = "DEV"
# The features to use when compiling the bin target
#
# Optional. Can be over-ridden with the command line parameter --bin-features
bin-features = ["ssr"]
# If the --no-default-features flag should be used when compiling the bin target
#
# Optional. Defaults to false.
bin-default-features = false
# The features to use when compiling the lib target
#
# Optional. Can be over-ridden with the command line parameter --lib-features
lib-features = ["hydrate"]
# If the --no-default-features flag should be used when compiling the lib target
#
# Optional. Defaults to false.
lib-default-features = false

View File

@@ -1,21 +0,0 @@
MIT License
Copyright (c) 2022 Greg Johnston
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -1,9 +0,0 @@
[tasks.build]
command = "cargo"
args = ["+nightly", "build-all-features"]
install_crate = "cargo-all-features"
[tasks.check]
command = "cargo"
args = ["+nightly", "check-all-features"]
install_crate = "cargo-all-features"

View File

@@ -1,41 +0,0 @@
# Leptos Errors Demonstration with Axum
This example demonstrates how Leptos Errors can work with an Axum backend on a server.
## Client Side Rendering
This example cannot be built as a trunk standalone CSR-only app as it requires the server to send status codes.
## Server Side Rendering with cargo-leptos
cargo-leptos is now the easiest and most featureful way to build server side rendered apps with hydration. It provides automatic recompilation of client and server code, wasm optimisation, CSS minification, and more! Check out more about it [here](https://github.com/akesson/cargo-leptos)
1. Install cargo-leptos
```bash
cargo install --locked cargo-leptos
```
2. Build the site in watch mode, recompiling on file changes
```bash
cargo leptos watch
```
Open browser on [http://localhost:3000/](http://localhost:3000/)
3. When ready to deploy, run
```bash
cargo leptos build --release
```
## Server Side Rendering without cargo-leptos
To run it as a server side app with hydration, you'll need to have wasm-pack installed.
0. Edit the `[package.metadata.leptos]` section and set `site-root` to `"."`. You'll also want to change the path of the `<StyleSheet / >` component in the root component to point towards the CSS file in the root. This tells leptos that the WASM/JS files generated by wasm-pack are available at `./pkg` and that the CSS files are no longer processed by cargo-leptos. Building to alternative folders is not supported at this time. You'll also want to edit the call to `get_configuration()` to pass in `Some(Cargo.toml)`, so that Leptos will read the settings instead of cargo-leptos. If you do so, your file/folder names cannot include dashes.
1. Install wasm-pack
```bash
cargo install wasm-pack
```
2. Build the Webassembly used to hydrate the HTML from the server
```bash
wasm-pack build --target=web --debug --no-default-features --features=hydrate
```
3. Run the server to serve the Webassembly, JS, and HTML
```bash
cargo run --no-default-features --features=ssr
```

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

View File

@@ -1,62 +0,0 @@
use crate::errors::AppError;
use cfg_if::cfg_if;
use leptos::Errors;
use leptos::*;
#[cfg(feature = "ssr")]
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(
cx: Scope,
#[prop(optional)] outside_errors: Option<Errors>,
#[prop(optional)] errors: Option<RwSignal<Errors>>,
) -> impl IntoView {
let errors = match outside_errors {
Some(e) => create_rw_signal(cx, e),
None => match errors {
Some(e) => e,
None => panic!("No Errors found and we expected errors!"),
},
};
// Get Errors from Signal
let errors = errors.get().0;
// Downcast lets us take a type that implements `std::error::Error`
let errors: Vec<AppError> = errors
.into_iter()
.filter_map(|(_k, v)| v.downcast_ref::<AppError>().cloned())
.collect();
println!("Errors: {errors:#?}");
// Only the response code for the first error is actually sent from the server
// this may be customized by the specific application
cfg_if! { if #[cfg(feature="ssr")] {
let response = use_context::<ResponseOptions>(cx);
if let Some(response) = response {
response.set_status(errors[0].status_code());
}
}}
view! { cx,
<h1>{if errors.len() > 1 {"Errors"} else {"Error"}}</h1>
<For
// a function that returns the items we're iterating over; a signal is fine
each= move || {errors.clone().into_iter().enumerate()}
// a unique key for each item as a reference
key=|(index, _error)| *index
// renders each item to a view
view= move |error| {
let error_string = error.1.to_string();
let error_code= error.1.status_code();
view! { cx,
<h2>{error_code.to_string()}</h2>
<p>"Error: " {error_string}</p>
}
}
/>
}
}

View File

@@ -1,19 +0,0 @@
use http::status::StatusCode;
use thiserror::Error;
#[derive(Debug, Clone, Error)]
pub enum AppError {
#[error("Not Found")]
NotFound,
#[error("Internal Server Error")]
InternalServerError,
}
impl AppError {
pub fn status_code(&self) -> StatusCode {
match self {
AppError::NotFound => StatusCode::NOT_FOUND,
AppError::InternalServerError => StatusCode::INTERNAL_SERVER_ERROR,
}
}
}

View File

@@ -1,45 +0,0 @@
use cfg_if::cfg_if;
cfg_if! { if #[cfg(feature = "ssr")] {
use axum::{
body::{boxed, Body, BoxBody},
extract::Extension,
response::IntoResponse,
http::{Request, Response, StatusCode, Uri},
};
use axum::response::Response as AxumResponse;
use tower::ServiceExt;
use tower_http::services::ServeDir;
use std::sync::Arc;
use leptos::{LeptosOptions, Errors, view};
use crate::error_template::{ErrorTemplate, ErrorTemplateProps};
use crate::errors::AppError;
pub async fn file_and_error_handler(uri: Uri, Extension(options): Extension<Arc<LeptosOptions>>, req: Request<Body>) -> AxumResponse {
let options = &*options;
let root = options.site_root.clone();
let res = get_static_file(uri.clone(), &root).await.unwrap();
if res.status() == StatusCode::OK {
res.into_response()
} else{
let mut errors = Errors::default();
errors.insert_with_default_key(AppError::NotFound);
let handler = leptos_axum::render_app_to_stream(options.to_owned(), move |cx| view!{cx, <ErrorTemplate outside_errors=errors.clone()/>});
handler(req).await.into_response()
}
}
async fn get_static_file(uri: Uri, root: &str) -> Result<Response<BoxBody>, (StatusCode, String)> {
let req = Request::builder().uri(uri.clone()).body(Body::empty()).unwrap();
// `ServeDir` implements `tower::Service` so we can call it with `tower::ServiceExt::oneshot`
// This path is relative to the cargo root
match ServeDir::new(root).oneshot(req).await {
Ok(res) => Ok(res.map(boxed)),
Err(err) => Err((
StatusCode::INTERNAL_SERVER_ERROR,
format!("Something went wrong: {err}"),
)),
}
}
}}

View File

@@ -1,79 +0,0 @@
use crate::{
error_template::{ErrorTemplate, ErrorTemplateProps},
errors::AppError,
};
use leptos::*;
use leptos_meta::*;
use leptos_router::*;
#[cfg(feature = "ssr")]
pub fn register_server_functions() {
_ = CauseInternalServerError::register();
}
#[server(CauseInternalServerError, "/api")]
pub async fn cause_internal_server_error() -> Result<(), ServerFnError> {
// fake API delay
std::thread::sleep(std::time::Duration::from_millis(1250));
Err(ServerFnError::ServerError(
"Generic Server Error".to_string(),
))
}
#[component]
pub fn App(cx: Scope) -> impl IntoView {
//let id = use_context::<String>(cx);
provide_meta_context(cx);
view! {
cx,
<Link rel="shortcut icon" type_="image/ico" href="/favicon.ico"/>
<Stylesheet id="leptos" href="/pkg/errors_axum.css"/>
<Router>
<header>
<h1>"Error Examples:"</h1>
</header>
<main>
<Routes>
<Route path="" view=|cx| view! {
cx,
<ExampleErrors/>
}/>
</Routes>
</main>
</Router>
}
}
#[component]
pub fn ExampleErrors(cx: Scope) -> impl IntoView {
let generate_internal_error = create_server_action::<CauseInternalServerError>(cx);
view! { cx,
<p>
"These links will load 404 pages since they do not exist. Verify with browser development tools: " <br/>
<a href="/404">"This links to a page that does not exist"</a><br/>
<a href="/404" target="_blank">"Same link, but in a new tab"</a>
</p>
<p>
"After pressing this button check browser network tools. Can be used even when WASM is blocked:"
<ActionForm action=generate_internal_error>
<input name="error1" type="submit" value="Generate Internal Server Error"/>
</ActionForm>
</p>
<p>"The following <div> will always contain an error and cause this page to produce status 500. Check browser dev tools. "</p>
<div>
// note that the error boundries could be placed above in the Router or lower down
// in a particular route. The generated errors on the entire page contribue to the
// final status code sent by the server when producing ssr pages.
<ErrorBoundary fallback=|cx, errors| view!{cx, <ErrorTemplate errors=errors/>}>
<ReturnsError/>
</ErrorBoundary>
</div>
}
}
#[component]
pub fn ReturnsError(_cx: Scope) -> impl IntoView {
Err::<String, AppError>(AppError::InternalServerError)
}

View File

@@ -1,25 +0,0 @@
use cfg_if::cfg_if;
use leptos::*;
pub mod error_template;
pub mod errors;
pub mod fallback;
pub mod landing;
// Needs to be in lib.rs AFAIK because wasm-bindgen needs us to be compiling a lib. I may be wrong.
cfg_if! {
if #[cfg(feature = "hydrate")] {
use wasm_bindgen::prelude::wasm_bindgen;
use crate::landing::*;
#[wasm_bindgen]
pub fn hydrate() {
console_error_panic_hook::set_once();
_ = console_log::init_with_level(log::Level::Debug);
console_error_panic_hook::set_once();
leptos::mount_to_body(|cx| {
view! { cx, <App/> }
});
}
}
}

View File

@@ -1,72 +0,0 @@
use cfg_if::cfg_if;
cfg_if! { if #[cfg(feature = "ssr")] {
use crate::fallback::file_and_error_handler;
use crate::landing::*;
use axum::body::Body as AxumBody;
use axum::{
extract::{Extension, Path},
http::Request,
response::{IntoResponse, Response},
routing::{get, post},
Router,
};
use errors_axum::*;
use leptos::*;
use leptos_axum::{generate_route_list, LeptosRoutes};
use std::sync::Arc;
}}
//Define a handler to test extractor with state
#[cfg(feature = "ssr")]
async fn custom_handler(
Path(id): Path<String>,
Extension(options): Extension<Arc<LeptosOptions>>,
req: Request<AxumBody>,
) -> Response {
let handler = leptos_axum::render_app_to_stream_with_context(
(*options).clone(),
move |cx| {
provide_context(cx, id.clone());
},
|cx| view! { cx, <App/> },
);
handler(req).await.into_response()
}
#[cfg(feature = "ssr")]
#[tokio::main]
async fn main() {
simple_logger::init_with_level(log::Level::Debug).expect("couldn't initialize logging");
crate::landing::register_server_functions();
// Setting this to None means we'll be using cargo-leptos and its env vars
let conf = get_configuration(None).await.unwrap();
let leptos_options = conf.leptos_options;
let addr = leptos_options.site_address;
let routes = generate_route_list(|cx| view! { cx, <App/> }).await;
// build our application with a route
let app = Router::new()
.route("/api/*fn_name", post(leptos_axum::handle_server_fns))
.route("/special/:id", get(custom_handler))
.leptos_routes(leptos_options.clone(), routes, |cx| view! { cx, <App/> })
.fallback(file_and_error_handler)
.layer(Extension(Arc::new(leptos_options)));
// run our app with hyper
// `axum::Server` is a re-export of `hyper::Server`
log!("listening on http://{}", &addr);
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await
.unwrap();
}
// this is if we were using client-only rending with Trunk
#[cfg(not(feature = "ssr"))]
pub fn main() {
// This example cannot be built as a trunk standalone CSR-only app.
// The server is needed to demonstrate the error statuses.
}

View File

@@ -1,3 +0,0 @@
.pending {
color: purple;
}

View File

@@ -2,8 +2,3 @@
command = "cargo"
args = ["+nightly", "build-all-features"]
install_crate = "cargo-all-features"
[tasks.check]
command = "cargo"
args = ["+nightly", "check-all-features"]
install_crate = "cargo-all-features"

View File

@@ -2,8 +2,3 @@
command = "cargo"
args = ["+nightly", "build-all-features"]
install_crate = "cargo-all-features"
[tasks.check]
command = "cargo"
args = ["+nightly", "check-all-features"]
install_crate = "cargo-all-features"

View File

@@ -1,4 +1,4 @@
use leptos::{component, view, IntoView, Scope};
use leptos::{component, Scope, IntoView, view};
use leptos_router::*;
#[component]
@@ -6,7 +6,7 @@ pub fn Nav(cx: Scope) -> impl IntoView {
view! { cx,
<header class="header">
<nav class="inner">
<A href="/home">
<A href="/">
<strong>"HN"</strong>
</A>
<A href="/new">

View File

@@ -2,8 +2,3 @@
command = "cargo"
args = ["+nightly", "build-all-features"]
install_crate = "cargo-all-features"
[tasks.check]
command = "cargo"
args = ["+nightly", "check-all-features"]
install_crate = "cargo-all-features"

View File

@@ -2,8 +2,3 @@
command = "cargo"
args = ["+nightly", "build-all-features"]
install_crate = "cargo-all-features"
[tasks.check]
command = "cargo"
args = ["+nightly", "check-all-features"]
install_crate = "cargo-all-features"

View File

@@ -2,8 +2,3 @@
command = "cargo"
args = ["+nightly", "build-all-features"]
install_crate = "cargo-all-features"
[tasks.check]
command = "cargo"
args = ["+nightly", "check-all-features"]
install_crate = "cargo-all-features"

View File

@@ -20,7 +20,6 @@ pub fn RouterExample(cx: Scope) -> impl IntoView {
<A exact=true href="/">"Contacts"</A>
<A href="about">"About"</A>
<A href="settings">"Settings"</A>
<A href="redirect-home">"Redirect to Home"</A>
</nav>
<main>
<Routes>
@@ -45,10 +44,6 @@ pub fn RouterExample(cx: Scope) -> impl IntoView {
path="settings"
view=move |cx| view! { cx, <Settings/> }
/>
<Route
path="redirect-home"
view=move |cx| view! { cx, <Redirect path="/"/> }
/>
</Routes>
</main>
</Router>

View File

@@ -2,8 +2,3 @@
command = "cargo"
args = ["+nightly", "build-all-features"]
install_crate = "cargo-all-features"
[tasks.check]
command = "cargo"
args = ["+nightly", "check-all-features"]
install_crate = "cargo-all-features"

View File

@@ -2,8 +2,3 @@
command = "cargo"
args = ["+nightly", "build-all-features"]
install_crate = "cargo-all-features"
[tasks.check]
command = "cargo"
args = ["+nightly", "check-all-features"]
install_crate = "cargo-all-features"

View File

@@ -12,13 +12,13 @@ console_log = "0.2.0"
console_error_panic_hook = "0.1.7"
futures = "0.3.25"
cfg-if = "1.0.0"
leptos = { path = "../../leptos", default-features = false, features = [
leptos = { path = "../../../leptos/leptos", default-features = false, features = [
"serde",
] }
leptos_axum = { path = "../../integrations/axum", default-features = false, optional = true }
leptos_meta = { path = "../../meta", default-features = false }
leptos_router = { path = "../../router", default-features = false }
leptos_reactive = { path = "../../leptos_reactive", default-features = false }
leptos_axum = { path = "../../../leptos/integrations/axum", default-features = false, optional = true }
leptos_meta = { path = "../../../leptos/meta", default-features = false }
leptos_router = { path = "../../../leptos/router", default-features = false }
leptos_reactive = { path = "../../../leptos/leptos_reactive", default-features = false }
log = "0.4.17"
simple_logger = "4.0.0"
serde = { version = "1.0.148", features = ["derive"] }
@@ -34,14 +34,12 @@ sqlx = { version = "0.6.2", features = [
"runtime-tokio-rustls",
"sqlite",
], optional = true }
thiserror = "1.0.38"
tracing = "0.1.37"
[features]
default = ["csr"]
csr = ["leptos/csr", "leptos_meta/csr", "leptos_router/csr"]
hydrate = ["leptos/hydrate", "leptos_meta/hydrate", "leptos_router/hydrate"]
ssr = ["dep:axum", "dep:tower", "dep:tower-http", "dep:tokio", "dep:sqlx", "leptos/ssr", "leptos_meta/ssr", "leptos_router/ssr", "dep:leptos_axum"]
ssr = ["dep:axum", "dep:tower", "dep:tower-http", "dep:tokio", "dep:sqlx", "leptos/ssr", "leptos_meta/ssr", "leptos_router/ssr", "leptos_axum"]
[package.metadata.cargo-all-features]
denylist = [
@@ -55,27 +53,27 @@ denylist = [
skip_feature_sets = [["csr", "ssr"], ["csr", "hydrate"], ["ssr", "hydrate"]]
[package.metadata.leptos]
# The name used by wasm-bindgen/cargo-leptos for the JS/WASM bundle. Defaults to the crate name
output-name = "todo_app_sqlite_axum"
# The name used by wasm-bindgen/cargo-leptos for the JS/WASM bundle. Defaults to the crate name
output-name = "todo_app_sqlite_axum"
# The site root folder is where cargo-leptos generate all output. WARNING: all content of this folder will be erased on a rebuild. Use it in your server setup.
site-root = "target/site"
# The site-root relative folder where all compiled output (JS, WASM and CSS) is written
# Defaults to pkg
site-pkg-dir = "pkg"
# Defaults to pkg
site-pkg-dir = "pkg"
# [Optional] The source CSS file. If it ends with .sass or .scss then it will be compiled by dart-sass into CSS. The CSS is optimized by Lightning CSS before being written to <site-root>/<site-pkg>/app.css
style-file = "./style.css"
# [Optional] Files in the asset-dir will be copied to the site-root directory
assets-dir = "public"
# The IP and port (ex: 127.0.0.1:3000) where the server serves the content. Use it in your server setup.
site-addr = "127.0.0.1:3000"
site-addr = "127.0.0.1:3000"
# The port to use for automatic reload monitoring
reload-port = 3001
reload-port = 3001
# [Optional] Command to use when running end2end tests. It will run in the end2end dir.
end2end-cmd = "npx playwright test"
# The browserlist query used for optimizing the CSS.
browserquery = "defaults"
browserquery = "defaults"
# Set by cargo-leptos watch when building with tha tool. Controls whether autoreload JS will be included in the head
watch = false
watch = false
# The environment Leptos will run in, usually either "DEV" or "PROD"
env = "DEV"
# The features to use when compiling the bin target

View File

@@ -2,8 +2,3 @@
command = "cargo"
args = ["+nightly", "build-all-features"]
install_crate = "cargo-all-features"
[tasks.check]
command = "cargo"
args = ["+nightly", "check-all-features"]
install_crate = "cargo-all-features"

View File

@@ -3,7 +3,8 @@
This example creates a basic todo app with an Axum backend that uses Leptos' server functions to call sqlx from the client and seamlessly run it on the server.
## Client Side Rendering
This example cannot be built as a trunk standalone CSR-only app. Only the server may directly connect to the database.
To run it as a Client Side App, you can issue `trunk serve --open` in the root. This will build the entire
app into one CSR bundle. Make sure you have trunk installed with `cargo install trunk`.
## Server Side Rendering with cargo-leptos
cargo-leptos is now the easiest and most featureful way to build server side rendered apps with hydration. It provides automatic recompilation of client and server code, wasm optimisation, CSS minification, and more! Check out more about it [here](https://github.com/akesson/cargo-leptos)

View File

@@ -1,65 +1,28 @@
use crate::errors::TodoAppError;
use cfg_if::cfg_if;
use leptos::Errors;
use leptos::*;
#[cfg(feature = "ssr")]
use leptos_axum::ResponseOptions;
use leptos::{view, For, ForProps, IntoView, RwSignal, Scope, View};
// 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(
cx: Scope,
#[prop(optional)] outside_errors: Option<Errors>,
#[prop(optional)] errors: Option<RwSignal<Errors>>,
) -> impl IntoView {
let errors = match outside_errors {
Some(e) => create_rw_signal(cx, e),
None => match errors {
Some(e) => e,
None => panic!("No Errors found and we expected errors!"),
},
pub fn error_template(cx: Scope, errors: Option<RwSignal<Errors>>) -> View {
let Some(errors) = errors else {
panic!("No Errors found and we expected errors!");
};
// Get Errors from Signal
let errors = errors.get().0;
// Downcast lets us take a type that implements `std::error::Error`
let errors: Vec<TodoAppError> = errors
.into_iter()
.filter_map(|(_k, v)| v.downcast_ref::<TodoAppError>().cloned())
.collect();
println!("Errors: {errors:#?}");
// Only the response code for the first error is actually sent from the server
// this may be customized by the specific application
cfg_if! {
if #[cfg(feature="ssr")]{
let response = use_context::<ResponseOptions>(cx);
if let Some(response) = response{
response.set_status(errors[0].status_code());
}
}
}
view! {cx,
<h1>"Errors"</h1>
<For
<h1>"Errors"</h1>
<For
// a function that returns the items we're iterating over; a signal is fine
each= move || {errors.clone().into_iter().enumerate()}
each= move || {errors.get().0.into_iter()}
// a unique key for each item as a reference
key=|(index, _error)| *index
key=|error| error.0.clone()
// renders each item to a view
view= move |error| {
let error_string = error.1.to_string();
let error_code= error.1.status_code();
view! {
cx,
<h2>{error_code.to_string()}</h2>
<p>"Error: " {error_string}</p>
}
}
/>
}
.into_view(cx)
}

View File

@@ -1,19 +0,0 @@
use http::status::StatusCode;
use thiserror::Error;
#[derive(Debug, Clone, Error)]
pub enum TodoAppError {
#[error("Not Found")]
NotFound,
#[error("Internal Server Error")]
InternalServerError,
}
impl TodoAppError {
pub fn status_code(&self) -> StatusCode {
match self {
TodoAppError::NotFound => StatusCode::NOT_FOUND,
TodoAppError::InternalServerError => StatusCode::INTERNAL_SERVER_ERROR,
}
}
}

View File

@@ -12,9 +12,8 @@ if #[cfg(feature = "ssr")] {
use tower::ServiceExt;
use tower_http::services::ServeDir;
use std::sync::Arc;
use leptos::{LeptosOptions, Errors, view};
use crate::error_template::{ErrorTemplate, ErrorTemplateProps};
use crate::errors::TodoAppError;
use leptos::{LeptosOptions};
use crate::error_template::error_template;
pub async fn file_and_error_handler(uri: Uri, Extension(options): Extension<Arc<LeptosOptions>>, req: Request<Body>) -> AxumResponse {
let options = &*options;
@@ -24,22 +23,21 @@ if #[cfg(feature = "ssr")] {
if res.status() == StatusCode::OK {
res.into_response()
} else{
let mut errors = Errors::default();
errors.insert_with_default_key(TodoAppError::NotFound);
let handler = leptos_axum::render_app_to_stream(options.to_owned(), move |cx| view!{cx, <ErrorTemplate outside_errors=errors.clone()/>});
let handler = leptos_axum::render_app_to_stream(options.to_owned(), |cx| error_template(cx, None));
handler(req).await.into_response()
}
}
async fn get_static_file(uri: Uri, root: &str) -> Result<Response<BoxBody>, (StatusCode, String)> {
let req = Request::builder().uri(uri.clone()).body(Body::empty()).unwrap();
let root_path = format!("{root}");
// `ServeDir` implements `tower::Service` so we can call it with `tower::ServiceExt::oneshot`
// This path is relative to the cargo root
match ServeDir::new(root).oneshot(req).await {
match ServeDir::new(&root_path).oneshot(req).await {
Ok(res) => Ok(res.map(boxed)),
Err(err) => Err((
StatusCode::INTERNAL_SERVER_ERROR,
format!("Something went wrong: {err}"),
format!("Something went wrong: {}", err),
)),
}
}

View File

@@ -1,7 +1,6 @@
use cfg_if::cfg_if;
use leptos::*;
pub mod error_template;
pub mod errors;
pub mod fallback;
pub mod todo;

View File

@@ -7,6 +7,7 @@ if #[cfg(feature = "ssr")] {
routing::{post, get},
extract::{Extension, Path},
http::Request,
body::StreamBody,
response::{IntoResponse, Response},
Router,
};
@@ -16,6 +17,7 @@ if #[cfg(feature = "ssr")] {
use crate::fallback::file_and_error_handler;
use leptos_axum::{generate_route_list, LeptosRoutes};
use std::sync::Arc;
use leptos_reactive::run_scope;
//Define a handler to test extractor with state
async fn custom_handler(Path(id): Path<String>, Extension(options): Extension<Arc<LeptosOptions>>, req: Request<AxumBody>) -> Response{
@@ -43,7 +45,7 @@ if #[cfg(feature = "ssr")] {
// Setting this to None means we'll be using cargo-leptos and its env vars
let conf = get_configuration(None).await.unwrap();
let leptos_options = conf.leptos_options;
let addr = leptos_options.site_address;
let addr = leptos_options.site_address.clone();
let routes = generate_route_list(|cx| view! { cx, <TodoApp/> }).await;
// build our application with a route
@@ -56,7 +58,7 @@ if #[cfg(feature = "ssr")] {
// run our app with hyper
// `axum::Server` is a re-export of `hyper::Server`
log!("listening on http://{}", &addr);
log!("listening on {}", &addr);
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await
@@ -66,9 +68,15 @@ if #[cfg(feature = "ssr")] {
// client-only stuff for Trunk
else {
use todo_app_sqlite_axum::todo::*;
pub fn main() {
// This example cannot be built as a trunk standalone CSR-only app.
// Only the server may directly connect to the database.
console_error_panic_hook::set_once();
_ = console_log::init_with_level(log::Level::Debug);
console_error_panic_hook::set_once();
mount_to_body(|cx| {
view! { cx, <TodoApp/> }
});
}
}
}

View File

@@ -1,4 +1,3 @@
use crate::error_template::{ErrorTemplate, ErrorTemplateProps};
use cfg_if::cfg_if;
use leptos::*;
use leptos_meta::*;
@@ -11,7 +10,7 @@ cfg_if! {
// use http::{header::SET_COOKIE, HeaderMap, HeaderValue, StatusCode};
pub async fn db() -> Result<SqliteConnection, ServerFnError> {
SqliteConnection::connect("sqlite:Todos.db").await.map_err(|e| ServerFnError::ServerError(e.to_string()))
Ok(SqliteConnection::connect("sqlite:Todos.db").await.map_err(|e| ServerFnError::ServerError(e.to_string()))?)
}
pub fn register_server_functions() {
@@ -41,9 +40,9 @@ pub async fn get_todos(cx: Scope) -> Result<Vec<Todo>, ServerFnError> {
// this is just an example of how to access server context injected in the handlers
// http::Request doesn't implement Clone, so more work will be needed to do use_context() on this
let req_parts = use_context::<leptos_axum::RequestParts>(cx);
if let Some(req_parts) = req_parts {
println!("Uri = {:?}", req_parts.uri);
if let Some(req_parts) = req_parts{
println!("Uri = {:?}", req_parts.uri);
}
use futures::TryStreamExt;
@@ -108,7 +107,7 @@ pub async fn delete_todo(id: u16) -> Result<(), ServerFnError> {
#[component]
pub fn TodoApp(cx: Scope) -> impl IntoView {
//let id = use_context::<String>(cx);
let id = use_context::<String>(cx);
provide_meta_context(cx);
view! {
cx,
@@ -122,10 +121,8 @@ pub fn TodoApp(cx: Scope) -> impl IntoView {
<Routes>
<Route path="" view=|cx| view! {
cx,
<ErrorBoundary fallback=|cx, errors| view!{cx, <ErrorTemplate errors=errors/>}>
<Todos/>
</ErrorBoundary>
}/> //Route
}/>
</Routes>
</main>
</Router>

View File

@@ -2,8 +2,3 @@
command = "cargo"
args = ["+nightly", "build-all-features"]
install_crate = "cargo-all-features"
[tasks.check]
command = "cargo"
args = ["+nightly", "check-all-features"]
install_crate = "cargo-all-features"

View File

@@ -13,5 +13,5 @@ futures = "0.3"
leptos = { workspace = true, features = ["ssr"] }
leptos_meta = { workspace = true, features = ["ssr"] }
leptos_router = { workspace = true, features = ["ssr"] }
parking_lot = "0.12.1"
regex = "1.7.0"
tokio = "1.24.1"

View File

@@ -18,9 +18,9 @@ use http::StatusCode;
use leptos::*;
use leptos_meta::*;
use leptos_router::*;
use parking_lot::RwLock;
use regex::Regex;
use std::sync::Arc;
use tokio::sync::RwLock;
/// This struct lets you define headers and override the status of the Response from an Element or a Server Function
/// Typically contained inside of a ResponseOptions. Setting this is useful for cookies and custom responses.
@@ -49,25 +49,25 @@ pub struct ResponseOptions(pub Arc<RwLock<ResponseParts>>);
impl ResponseOptions {
/// A less boilerplatey way to overwrite the contents of `ResponseOptions` with a new `ResponseParts`
pub fn overwrite(&self, parts: ResponseParts) {
let mut writable = self.0.write();
pub async fn overwrite(&self, parts: ResponseParts) {
let mut writable = self.0.write().await;
*writable = parts
}
/// Set the status of the returned Response
pub fn set_status(&self, status: StatusCode) {
let mut writeable = self.0.write();
pub async fn set_status(&self, status: StatusCode) {
let mut writeable = self.0.write().await;
let res_parts = &mut *writeable;
res_parts.status = Some(status);
}
/// Insert a header, overwriting any previous value with the same key
pub fn insert_header(&self, key: header::HeaderName, value: header::HeaderValue) {
let mut writeable = self.0.write();
pub async fn insert_header(&self, key: header::HeaderName, value: header::HeaderValue) {
let mut writeable = self.0.write().await;
let res_parts = &mut *writeable;
res_parts.headers.insert(key, value);
}
/// Append a header, leaving any header with the same key intact
pub fn append_header(&self, key: header::HeaderName, value: header::HeaderValue) {
let mut writeable = self.0.write();
pub async fn append_header(&self, key: header::HeaderName, value: header::HeaderValue) {
let mut writeable = self.0.write().await;
let res_parts = &mut *writeable;
res_parts.headers.append(key, value);
}
@@ -76,13 +76,15 @@ impl ResponseOptions {
/// Provides an easy way to redirect the user from within a server function. Mimicing the Remix `redirect()`,
/// it sets a [StatusCode] of 302 and a [LOCATION](header::LOCATION) header with the provided value.
/// If looking to redirect from the client, `leptos_router::use_navigate()` should be used instead.
pub fn redirect(cx: leptos::Scope, path: &str) {
pub async fn redirect(cx: leptos::Scope, path: &str) {
let response_options = use_context::<ResponseOptions>(cx).unwrap();
response_options.set_status(StatusCode::FOUND);
response_options.insert_header(
header::LOCATION,
header::HeaderValue::from_str(path).expect("Failed to create HeaderValue"),
);
response_options.set_status(StatusCode::FOUND).await;
response_options
.insert_header(
header::LOCATION,
header::HeaderValue::from_str(path).expect("Failed to create HeaderValue"),
)
.await;
}
/// An Actix [Route](actix_web::Route) that listens for a `POST` request with
@@ -180,7 +182,7 @@ pub fn handle_server_fns_with_context(
runtime.dispose();
let mut res: HttpResponseBuilder;
let mut res_parts = res_options.0.write();
let mut res_parts = res_options.0.write().await;
if accept_header == Some("application/json")
|| accept_header == Some("application/x-www-form-urlencoded")
@@ -438,7 +440,6 @@ fn provide_contexts(cx: leptos::Scope, req: &HttpRequest, res_options: ResponseO
provide_context(cx, MetaContext::new());
provide_context(cx, res_options);
provide_context(cx, req.clone());
provide_server_redirect(cx, move |path| redirect(cx, path));
}
fn leptos_corrected_path(req: &HttpRequest) -> String {
@@ -492,7 +493,7 @@ async fn stream_app(
let second_chunk = stream.next().await;
let third_chunk = stream.next().await;
let res_options = res_options.0.read();
let res_options = res_options.0.read().await;
let (status, mut headers) = (res_options.status, res_options.headers.clone());
let status = status.unwrap_or_default();
@@ -647,16 +648,6 @@ pub trait LeptosRoutes {
Data: 'static,
Fut: Future<Output = Result<DataResponse<Data>, actix_web::Error>>,
IV: IntoView + 'static;
fn leptos_routes_with_context<IV>(
self,
options: LeptosOptions,
paths: Vec<String>,
additional_context: impl Fn(leptos::Scope) + 'static + Clone + Send,
app_fn: impl Fn(leptos::Scope) -> IV + Clone + Send + 'static,
) -> Self
where
IV: IntoView + 'static;
}
/// The default implementation of `LeptosRoutes` which takes in a list of paths, and dispatches GET requests
@@ -703,28 +694,4 @@ where
}
router
}
fn leptos_routes_with_context<IV>(
self,
options: LeptosOptions,
paths: Vec<String>,
additional_context: impl Fn(leptos::Scope) + 'static + Clone + Send,
app_fn: impl Fn(leptos::Scope) -> IV + Clone + Send + 'static,
) -> Self
where
IV: IntoView + 'static,
{
let mut router = self;
for path in paths.iter() {
router = router.route(
path,
render_app_to_stream_with_context(
options.clone(),
additional_context.clone(),
app_fn.clone(),
),
);
}
router
}
}

View File

@@ -16,5 +16,4 @@ leptos = { workspace = true, features = ["ssr"] }
leptos_meta = { workspace = true, features = ["ssr"] }
leptos_router = { workspace = true, features = ["ssr"] }
leptos_config = { workspace = true }
tokio = { version = "1", features = ["full"] }
parking_lot = "0.12.1"
tokio = { version = "1.0", features = ["full"] }

View File

@@ -19,9 +19,8 @@ use hyper::body;
use leptos::*;
use leptos_meta::MetaContext;
use leptos_router::*;
use parking_lot::RwLock;
use std::{io, pin::Pin, sync::Arc};
use tokio::{task::spawn_blocking, task::LocalSet};
use tokio::{sync::RwLock, task::spawn_blocking, task::LocalSet};
/// A struct to hold the parts of the incoming Request. Since `http::Request` isn't cloneable, we're forced
/// to construct this for Leptos to use in Axum
@@ -60,25 +59,25 @@ pub struct ResponseOptions(pub Arc<RwLock<ResponseParts>>);
impl ResponseOptions {
/// A less boilerplatey way to overwrite the contents of `ResponseOptions` with a new `ResponseParts`
pub fn overwrite(&self, parts: ResponseParts) {
let mut writable = self.0.write();
pub async fn overwrite(&self, parts: ResponseParts) {
let mut writable = self.0.write().await;
*writable = parts
}
/// Set the status of the returned Response
pub fn set_status(&self, status: StatusCode) {
let mut writeable = self.0.write();
pub async fn set_status(&self, status: StatusCode) {
let mut writeable = self.0.write().await;
let res_parts = &mut *writeable;
res_parts.status = Some(status);
}
/// Insert a header, overwriting any previous value with the same key
pub fn insert_header(&self, key: HeaderName, value: HeaderValue) {
let mut writeable = self.0.write();
pub async fn insert_header(&self, key: HeaderName, value: HeaderValue) {
let mut writeable = self.0.write().await;
let res_parts = &mut *writeable;
res_parts.headers.insert(key, value);
}
/// Append a header, leaving any header with the same key intact
pub fn append_header(&self, key: HeaderName, value: HeaderValue) {
let mut writeable = self.0.write();
pub async fn append_header(&self, key: HeaderName, value: HeaderValue) {
let mut writeable = self.0.write().await;
let res_parts = &mut *writeable;
res_parts.headers.append(key, value);
}
@@ -87,13 +86,15 @@ impl ResponseOptions {
/// Provides an easy way to redirect the user from within a server function. Mimicing the Remix `redirect()`,
/// it sets a StatusCode of 302 and a LOCATION header with the provided value.
/// If looking to redirect from the client, `leptos_router::use_navigate()` should be used instead
pub fn redirect(cx: leptos::Scope, path: &str) {
pub async fn redirect(cx: leptos::Scope, path: &str) {
let response_options = use_context::<ResponseOptions>(cx).unwrap();
response_options.set_status(StatusCode::FOUND);
response_options.insert_header(
header::LOCATION,
header::HeaderValue::from_str(path).expect("Failed to create HeaderValue"),
);
response_options.set_status(StatusCode::FOUND).await;
response_options
.insert_header(
header::LOCATION,
header::HeaderValue::from_str(path).expect("Failed to create HeaderValue"),
)
.await;
}
/// Decomposes an HTTP request into its parts, allowing you to read its headers
@@ -225,7 +226,7 @@ async fn handle_server_fns_inner(
// Add headers from ResponseParts if they exist. These should be added as long
// as the server function returns an OK response
let res_options_outer = res_options.unwrap().0;
let res_options_inner = res_options_outer.read();
let res_options_inner = res_options_outer.read().await;
let (status, mut res_headers) = (
res_options_inner.status,
res_options_inner.headers.clone(),
@@ -447,7 +448,6 @@ where
provide_context(cx, MetaContext::new());
provide_context(cx, req_parts);
provide_context(cx, default_res_options);
provide_server_redirect(cx, move |path| redirect(cx, path));
app_fn(cx).into_view(cx)
}
};
@@ -478,9 +478,9 @@ where
let res_options =
use_context::<ResponseOptions>(cx).unwrap();
let new_res_parts = res_options.0.read().clone();
let new_res_parts = res_options.0.read().await.clone();
let mut writable = res_options2.0.write();
let mut writable = res_options2.0.write().await;
*writable = new_res_parts;
runtime.dispose();
@@ -501,7 +501,7 @@ where
let third_chunk = stream.next().await;
// Extract the resources now that they've been rendered
let res_options = res_options3.0.read();
let res_options = res_options3.0.read().await;
let complete_stream = futures::stream::iter([
first_chunk.unwrap(),
@@ -605,7 +605,7 @@ where
.run_until(async move {
tokio::task::spawn_local(async move {
let routes = leptos_router::generate_route_list_inner(app_fn);
let mut writable = routes_inner.0.write();
let mut writable = routes_inner.0.write().await;
*writable = routes;
})
.await
@@ -613,7 +613,7 @@ where
})
.await;
let routes = routes.0.read().to_owned();
let routes = routes.0.read().await.to_owned();
// Axum's Router defines Root routes as "/" not ""
let routes: Vec<String> = routes
.into_iter()
@@ -638,21 +638,6 @@ pub trait LeptosRoutes {
) -> Self
where
IV: IntoView + 'static;
fn leptos_routes_with_context<IV>(
self,
options: LeptosOptions,
paths: Vec<String>,
additional_context: impl Fn(leptos::Scope) + 'static + Clone + Send,
app_fn: impl Fn(leptos::Scope) -> IV + Clone + Send + 'static,
) -> Self
where
IV: IntoView + 'static;
fn leptos_routes_with_handler<H, T>(self, paths: Vec<String>, handler: H) -> Self
where
H: axum::handler::Handler<T, (), axum::body::Body>,
T: 'static;
}
/// The default implementation of `LeptosRoutes` which takes in a list of paths, and dispatches GET requests
/// to those paths to Leptos's renderer.
@@ -675,40 +660,4 @@ impl LeptosRoutes for axum::Router {
}
router
}
fn leptos_routes_with_context<IV>(
self,
options: LeptosOptions,
paths: Vec<String>,
additional_context: impl Fn(leptos::Scope) + 'static + Clone + Send,
app_fn: impl Fn(leptos::Scope) -> IV + Clone + Send + 'static,
) -> Self
where
IV: IntoView + 'static,
{
let mut router = self;
for path in paths.iter() {
router = router.route(
path,
get(render_app_to_stream_with_context(
options.clone(),
additional_context.clone(),
app_fn.clone(),
)),
);
}
router
}
fn leptos_routes_with_handler<H, T>(self, paths: Vec<String>, handler: H) -> Self
where
H: axum::handler::Handler<T, (), axum::body::Body>,
T: 'static,
{
let mut router = self;
for path in paths.iter() {
router = router.route(path, get(handler.clone()));
}
router
}
}

View File

@@ -16,37 +16,18 @@ leptos_reactive = { workspace = true }
leptos_server = { workspace = true }
leptos_config = { workspace = true }
tracing = "0.1"
typed-builder = "0.12"
typed-builder = "0.11"
once_cell = "1.17.0"
[dev-dependencies]
leptos = { path = ".", default-features = false }
[features]
default = ["csr", "serde"]
csr = [
"leptos_dom/web",
"leptos_macro/csr",
"leptos_reactive/csr",
"leptos_server/csr",
]
hydrate = [
"leptos_dom/web",
"leptos_macro/hydrate",
"leptos_reactive/hydrate",
"leptos_server/hydrate",
]
ssr = [
"leptos_dom/ssr",
"leptos_macro/ssr",
"leptos_reactive/ssr",
"leptos_server/ssr",
]
stable = [
"leptos_dom/stable",
"leptos_macro/stable",
"leptos_reactive/stable",
"leptos_server/stable",
]
csr = ["leptos_dom/web", "leptos_macro/csr", "leptos_reactive/csr", "leptos_server/csr"]
hydrate = ["leptos_dom/web", "leptos_macro/hydrate", "leptos_reactive/hydrate", "leptos_server/hydrate"]
ssr = ["leptos_dom/ssr", "leptos_macro/ssr", "leptos_reactive/ssr", "leptos_server/ssr"]
stable = ["leptos_dom/stable", "leptos_macro/stable", "leptos_reactive/stable", "leptos_server/stable"]
serde = ["leptos_reactive/serde"]
serde-lite = ["leptos_reactive/serde-lite"]
miniserde = ["leptos_reactive/miniserde"]

View File

@@ -35,7 +35,7 @@ pub fn ErrorBoundary<F, IV>(
fallback: F,
) -> impl IntoView
where
F: Fn(Scope, RwSignal<Errors>) -> IV + 'static,
F: Fn(Scope, Option<RwSignal<Errors>>) -> IV + 'static,
IV: IntoView,
{
let errors: RwSignal<Errors> = create_rw_signal(cx, Errors::default());
@@ -47,6 +47,6 @@ where
move || match errors.get().0.is_empty() {
true => children.clone().into_view(cx),
false => fallback(cx, errors).into_view(cx),
false => fallback(cx, Some(errors)).into_view(cx),
}
}

View File

@@ -172,7 +172,3 @@ pub type Children = Box<dyn FnOnce(Scope) -> Fragment>;
/// A type for the `children` property on components that can be called
/// more than once.
pub type ChildrenFn = Box<dyn Fn(Scope) -> Fragment>;
/// A type for the `children` property on components that can be called
/// more than once, but may mutate the children.
pub type ChildrenFnMut = Box<dyn FnMut(Scope) -> Fragment>;

View File

@@ -1,16 +1,13 @@
use crate::Children;
use leptos::component;
use leptos_dom::{Fragment, IntoView};
use leptos_reactive::{create_memo, Scope};
use leptos_dom::IntoView;
use leptos_reactive::Scope;
use once_cell::sync::Lazy;
/// A component that will show its children when the `when` condition is `true`,
/// and show the fallback when it is `false`, without rerendering every time
/// the condition changes.
///
/// *Note*: Because of the nature of generic arguments, its not really possible
/// to make the `fallback` optional. If you want an empty fallback state—in other
/// words, if you want to show the children if `when` is true and noting otherwise—use
/// `fallback=|_| ()` (i.e., a fallback function that returns the unit type `()`).
///
/// ```rust
/// # use leptos_reactive::*;
/// # use leptos_macro::*;
@@ -33,7 +30,7 @@ pub fn Show<F, W, IV>(
/// The scope the component is running in
cx: Scope,
/// The components Show wraps
children: Box<dyn Fn(Scope) -> Fragment>,
children: Children,
/// A closure that returns a bool that determines whether this thing runs
when: W,
/// A closure that returns what gets rendered if the when statement is false
@@ -44,10 +41,12 @@ where
F: Fn(Scope) -> IV + 'static,
IV: IntoView,
{
let memoized_when = create_memo(cx, move |_| when());
// now you don't render until `when` is actually true
let children = Lazy::new(move || children(cx).into_view(cx));
let fallback = Lazy::new(move || fallback(cx).into_view(cx));
move || match memoized_when.get() {
true => children(cx).into_view(cx),
false => fallback(cx).into_view(cx),
move || match when() {
true => children.clone(),
false => fallback.clone(),
}
}

View File

@@ -5,7 +5,7 @@ edition = "2021"
authors = ["Greg Johnston"]
license = "MIT"
repository = "https://github.com/leptos-rs/leptos"
description = "Configuration for the Leptos web framework."
description = "Configuraiton for the Leptos web framework."
readme = "../README.md"
[dependencies]
@@ -14,4 +14,4 @@ fs = "0.0.5"
regex = "1.7.0"
serde = { version = "1.0.151", features = ["derive"] }
thiserror = "1.0.38"
typed-builder = "0.12"
typed-builder = "0.11"

View File

@@ -87,34 +87,50 @@ impl Default for Env {
}
}
fn from_str(input: &str) -> Result<Env, String> {
let sanitized = input.to_lowercase();
match sanitized.as_ref() {
"dev" | "development" => Ok(Env::DEV),
"prod" | "production" => Ok(Env::PROD),
_ => Err(format!(
"{input} is not a supported environment. Use either `dev` or `production`.",
)),
}
}
impl FromStr for Env {
type Err = ();
fn from_str(input: &str) -> Result<Self, Self::Err> {
from_str(input).or_else(|_| Ok(Self::default()))
let sanitized = input.to_lowercase();
match sanitized.as_ref() {
"dev" => Ok(Self::DEV),
"development" => Ok(Self::DEV),
"prod" => Ok(Self::PROD),
"production" => Ok(Self::PROD),
_ => Ok(Self::DEV),
}
}
}
impl From<&str> for Env {
fn from(str: &str) -> Self {
from_str(str).unwrap_or_else(|err| panic!("{}", err))
let sanitized = str.to_lowercase();
match sanitized.as_str() {
"dev" => Self::DEV,
"development" => Self::DEV,
"prod" => Self::PROD,
"production" => Self::PROD,
_ => {
panic!("Env var is not recognized. Maybe try `dev` or `prod`")
}
}
}
}
impl From<&Result<String, VarError>> for Env {
fn from(input: &Result<String, VarError>) -> Self {
match input {
Ok(str) => from_str(str).unwrap_or_else(|err| panic!("{}", err)),
Err(_) => Self::default(),
Ok(str) => {
let sanitized = str.to_lowercase();
match sanitized.as_ref() {
"dev" => Self::DEV,
"development" => Self::DEV,
"prod" => Self::PROD,
"production" => Self::PROD,
_ => {
panic!("Env var is not recognized. Maybe try `dev` or `prod`")
}
}
}
Err(_) => Self::DEV,
}
}
}
@@ -123,7 +139,15 @@ impl TryFrom<String> for Env {
type Error = String;
fn try_from(s: String) -> Result<Self, Self::Error> {
from_str(s.as_str())
match s.to_lowercase().as_str() {
"dev" => Ok(Self::DEV),
"development" => Ok(Self::DEV),
"prod" => Ok(Self::PROD),
"production" => Ok(Self::PROD),
other => Err(format!(
"{other} is not a supported environment. Use either `dev` or `production`."
)),
}
}
}

View File

@@ -1,7 +1,4 @@
use crate::{
hydration::{HydrationCtx, HydrationKey},
Comment, IntoView, View,
};
use crate::{hydration::HydrationCtx, Comment, IntoView, View};
use cfg_if::cfg_if;
use leptos_reactive::Scope;
use std::{borrow::Cow, cell::RefCell, fmt, ops::Deref, rc::Rc};
@@ -10,6 +7,8 @@ cfg_if! {
use crate::{mount_child, prepare_to_move, unmount_child, MountKind, Mountable};
use leptos_reactive::{create_effect, ScopeDisposer};
use wasm_bindgen::JsCast;
} else {
use crate::hydration::HydrationKey;
}
}
@@ -78,7 +77,9 @@ impl Mountable for DynChildRepr {
}
impl DynChildRepr {
fn new_with_id(id: HydrationKey) -> Self {
fn new() -> Self {
let id = HydrationCtx::id();
let markers = (
Comment::new(Cow::Borrowed("</DynChild>"), &id, true),
#[cfg(debug_assertions)]
@@ -123,7 +124,6 @@ where
CF: Fn() -> N + 'static,
N: IntoView,
{
id: crate::HydrationKey,
child_fn: CF,
}
@@ -135,12 +135,7 @@ where
/// Creates a new dynamic child which will re-render whenever it's
/// signal dependencies change.
pub fn new(child_fn: CF) -> Self {
Self::new_with_id(HydrationCtx::id(), child_fn)
}
#[doc(hidden)]
pub fn new_with_id(id: HydrationKey, child_fn: CF) -> Self {
Self { id, child_fn }
Self { child_fn }
}
}
@@ -154,182 +149,167 @@ where
instrument(level = "trace", name = "<DynChild />", skip_all)
)]
fn into_view(self, cx: Scope) -> View {
// concrete inner function
fn create_dyn_view(
cx: Scope,
component: DynChildRepr,
child_fn: Box<dyn Fn() -> View>,
) -> DynChildRepr {
#[cfg(all(target_arch = "wasm32", feature = "web"))]
let closing = component.closing.node.clone();
let Self { child_fn } = self;
let child = component.child.clone();
let component = DynChildRepr::new();
#[cfg(all(debug_assertions, target_arch = "wasm32", feature = "web"))]
let span = tracing::Span::current();
#[cfg(all(target_arch = "wasm32", feature = "web"))]
let closing = component.closing.node.clone();
#[cfg(all(target_arch = "wasm32", feature = "web"))]
create_effect(
cx,
move |prev_run: Option<(Option<web_sys::Node>, ScopeDisposer)>| {
#[cfg(debug_assertions)]
let _guard = span.enter();
let child = component.child.clone();
let (new_child, disposer) =
cx.run_child_scope(|cx| child_fn().into_view(cx));
#[cfg(all(debug_assertions, target_arch = "wasm32", feature = "web"))]
let span = tracing::Span::current();
let mut child_borrow = child.borrow_mut();
#[cfg(all(target_arch = "wasm32", feature = "web"))]
create_effect(
cx,
move |prev_run: Option<(Option<web_sys::Node>, ScopeDisposer)>| {
#[cfg(debug_assertions)]
let _guard = span.enter();
// Is this at least the second time we are loading a child?
if let Some((prev_t, prev_disposer)) = prev_run {
let child = child_borrow.take().unwrap();
let (new_child, disposer) =
cx.run_child_scope(|cx| child_fn().into_view(cx));
// Dispose of the scope
prev_disposer.dispose();
let mut child_borrow = child.borrow_mut();
// We need to know if our child wasn't moved elsewhere.
// If it was, `DynChild` no longer "owns" that child, and
// is therefore no longer sound to unmount it from the DOM
// or to reuse it in the case of a text node
// Is this at least the second time we are loading a child?
if let Some((prev_t, prev_disposer)) = prev_run {
let child = child_borrow.take().unwrap();
// TODO check does this still detect moves correctly?
let was_child_moved = prev_t.is_none()
&& child.get_closing_node().next_sibling().as_ref()
!= Some(&closing);
// Dispose of the scope
prev_disposer.dispose();
// If the previous child was a text node, we would like to
// make use of it again if our current child is also a text
// node
let ret = if let Some(prev_t) = prev_t {
// Here, our child is also a text node
if let Some(new_t) = new_child.get_text() {
if !was_child_moved && child != new_child {
prev_t
.unchecked_ref::<web_sys::Text>()
.set_data(&new_t.content);
// We need to know if our child wasn't moved elsewhere.
// If it was, `DynChild` no longer "owns" that child, and
// is therefore no longer sound to unmount it from the DOM
// or to reuse it in the case of a text node
**child_borrow = Some(new_child);
// TODO check does this still detect moves correctly?
let was_child_moved = prev_t.is_none()
&& child.get_closing_node().next_sibling().as_ref()
!= Some(&closing);
(Some(prev_t), disposer)
} else {
mount_child(MountKind::Before(&closing), &new_child);
**child_borrow = Some(new_child.clone());
(Some(new_t.node.clone()), disposer)
}
}
// Child is not a text node, so we can remove the previous
// text node
else {
if !was_child_moved && child != new_child {
// Remove the text
closing
.previous_sibling()
.unwrap()
.unchecked_into::<web_sys::Element>()
.remove();
}
// Mount the new child, and we're done
mount_child(MountKind::Before(&closing), &new_child);
// If the previous child was a text node, we would like to
// make use of it again if our current child is also a text
// node
let ret = if let Some(prev_t) = prev_t {
// Here, our child is also a text node
if let Some(new_t) = new_child.get_text() {
if !was_child_moved && child != new_child {
prev_t
.unchecked_ref::<web_sys::Text>()
.set_data(&new_t.content);
**child_borrow = Some(new_child);
(None, disposer)
(Some(prev_t), disposer)
} else {
mount_child(MountKind::Before(&closing), &new_child);
**child_borrow = Some(new_child.clone());
(Some(new_t.node.clone()), disposer)
}
}
// Otherwise, the new child can still be a text node,
// but we know the previous child was not, so no special
// treatment here
// Child is not a text node, so we can remove the previous
// text node
else {
// Technically, I think this check shouldn't be necessary, but
// I can imagine some edge case that the child changes while
// hydration is ongoing
if !HydrationCtx::is_hydrating() {
if !was_child_moved && child != new_child {
// Remove the child
let start = child.get_opening_node();
let end = &closing;
unmount_child(&start, end);
}
// Mount the new child
mount_child(MountKind::Before(&closing), &new_child);
}
// We want to reuse text nodes, so hold onto it if
// our child is one
let t = new_child.get_text().map(|t| t.node.clone());
**child_borrow = Some(new_child);
(t, disposer)
};
ret
}
// Otherwise, we know for sure this is our first time
else {
// We need to remove the text created from SSR
if HydrationCtx::is_hydrating() && new_child.get_text().is_some() {
let t = closing
.previous_sibling()
.unwrap()
.unchecked_into::<web_sys::Element>();
// See note on ssr.rs when matching on `DynChild`
// for more details on why we need to do this for
// release
if !cfg!(debug_assertions) {
t.previous_sibling()
if !was_child_moved && child != new_child {
// Remove the text
closing
.previous_sibling()
.unwrap()
.unchecked_into::<web_sys::Element>()
.remove();
}
t.remove();
// Mount the new child, and we're done
mount_child(MountKind::Before(&closing), &new_child);
}
// If we are not hydrating, we simply mount the child
**child_borrow = Some(new_child);
(None, disposer)
}
}
// Otherwise, the new child can still be a text node,
// but we know the previous child was not, so no special
// treatment here
else {
// Technically, I think this check shouldn't be necessary, but
// I can imagine some edge case that the child changes while
// hydration is ongoing
if !HydrationCtx::is_hydrating() {
if !was_child_moved && child != new_child {
// Remove the child
let start = child.get_opening_node();
let end = &closing;
unmount_child(&start, end);
}
// Mount the new child
mount_child(MountKind::Before(&closing), &new_child);
}
// We want to update text nodes, rather than replace them, so
// make sure to hold onto the text node
// We want to reuse text nodes, so hold onto it if
// our child is one
let t = new_child.get_text().map(|t| t.node.clone());
**child_borrow = Some(new_child);
(t, disposer)
};
ret
}
// Otherwise, we know for sure this is our first time
else {
// We need to remove the text created from SSR
if HydrationCtx::is_hydrating() && new_child.get_text().is_some() {
let t = closing
.previous_sibling()
.unwrap()
.unchecked_into::<web_sys::Element>();
// See note on ssr.rs when matching on `DynChild`
// for more details on why we need to do this for
// release
if !cfg!(debug_assertions) {
t.previous_sibling()
.unwrap()
.unchecked_into::<web_sys::Element>()
.remove();
}
t.remove();
mount_child(MountKind::Before(&closing), &new_child);
}
},
);
#[cfg(not(all(target_arch = "wasm32", feature = "web")))]
{
let new_child = child_fn().into_view(cx);
// If we are not hydrating, we simply mount the child
if !HydrationCtx::is_hydrating() {
mount_child(MountKind::Before(&closing), &new_child);
}
**child.borrow_mut() = Some(new_child);
}
// We want to update text nodes, rather than replace them, so
// make sure to hold onto the text node
let t = new_child.get_text().map(|t| t.node.clone());
component
}
**child_borrow = Some(new_child);
// monomorphized outer function
let Self { id, child_fn } = self;
let component = DynChildRepr::new_with_id(id);
let component = create_dyn_view(
cx,
component,
Box::new(move || child_fn().into_view(cx)),
(t, disposer)
}
},
);
#[cfg(not(all(target_arch = "wasm32", feature = "web")))]
{
let new_child = child_fn().into_view(cx);
**child.borrow_mut() = Some(new_child);
}
View::CoreComponent(crate::CoreComponent::DynChild(component))
}
}

View File

@@ -0,0 +1 @@

View File

@@ -5,12 +5,12 @@ use std::{collections::HashMap, error::Error, sync::Arc};
/// A struct to hold all the possible errors that could be provided by child Views
#[derive(Debug, Clone, Default)]
pub struct Errors(pub HashMap<HydrationKey, Arc<dyn Error + Send + Sync>>);
pub struct Errors(pub HashMap<HydrationKey, Arc<dyn Error>>);
impl<T, E> IntoView for Result<T, E>
where
T: IntoView + 'static,
E: Error + Send + Sync + 'static,
E: std::error::Error + Send + Sync + 'static,
{
fn into_view(self, cx: leptos_reactive::Scope) -> crate::View {
match self {
@@ -34,6 +34,7 @@ where
on_cleanup(cx, move || {
queue_microtask(move || {
errors.update(|errors: &mut Errors| {
crate::log!("removing error at {id}");
errors.remove::<E>(&id);
});
});
@@ -58,21 +59,14 @@ impl Errors {
/// Add an error to Errors that will be processed by `<ErrorBoundary/>`
pub fn insert<E>(&mut self, key: HydrationKey, error: E)
where
E: Error + Send + Sync + 'static,
E: Error + 'static,
{
self.0.insert(key, Arc::new(error));
}
/// Add an error with the default key for errors outside the reactive system
pub fn insert_with_default_key<E>(&mut self, error: E)
where
E: Error + Send + Sync + 'static,
{
self.0.insert(HydrationKey::default(), Arc::new(error));
}
/// Remove an error to Errors that will be processed by `<ErrorBoundary/>`
pub fn remove<E>(&mut self, key: &HydrationKey)
where
E: Error + Send + Sync + 'static,
E: Error + 'static,
{
self.0.remove(key);
}

View File

@@ -16,8 +16,7 @@ thread_local! {
pub fn add_event_listener<E>(
target: &web_sys::Element,
event_name: Cow<'static, str>,
#[cfg(debug_assertions)] mut cb: impl FnMut(E) + 'static,
#[cfg(not(debug_assertions))] cb: impl FnMut(E) + 'static,
mut cb: impl FnMut(E) + 'static,
) where
E: FromWasmAbi + 'static,
{

View File

@@ -150,7 +150,6 @@ generate_event_types! {
canplaythrough: Event,
change: Event,
click: MouseEvent,
#[does_not_bubble]
close: Event,
compositionend: CompositionEvent,
compositionstart: CompositionEvent,

View File

@@ -13,22 +13,25 @@ proc-macro = true
[dependencies]
cfg-if = "1"
html-escape = "0.2"
doc-comment = "0.3"
itertools = "0.10"
pad-adapter = "0.1"
prettyplease = "0.1"
proc-macro-error = "1"
proc-macro2 = "1"
quote = "1"
syn = { version = "1", features = ["full"] }
syn-rsx = "0.9"
uuid = { version = "1", features = ["v4"] }
leptos_dom = { workspace = true }
leptos_reactive = { workspace = true }
leptos_server = { workspace = true }
lazy_static = "1.4"
convert_case = "0.6.0"
[dev-dependencies]
log = "0.4"
typed-builder = "0.12"
typed-builder = "0.11"
leptos = { path = "../leptos" }
[features]

View File

@@ -4,7 +4,6 @@ use convert_case::{
};
use itertools::Itertools;
use proc_macro2::{Ident, TokenStream};
use proc_macro_error::ResultExt;
use quote::{format_ident, ToTokens, TokenStreamExt};
use std::collections::HashSet;
use syn::{
@@ -168,7 +167,7 @@ impl ToTokens for Model {
let component = if *is_transparent {
quote! {
#body_name(#scope_name, #prop_names)
#body_name(cx, #prop_names)
}
} else {
quote! {
@@ -288,8 +287,8 @@ impl Prop {
} else {
abort!(
typed.pat,
"only `prop: bool` style types are allowed within the `#[component]` \
macro"
"only `prop: bool` style types are allowed within the \
`#[component]` macro"
);
};
@@ -403,15 +402,17 @@ enum PropOpt {
impl PropOpt {
fn from_attribute(attr: &Attribute) -> Option<HashSet<Self>> {
const ABORT_OPT_MESSAGE: &str = "only `optional`, `optional_no_strip`, \
`strip_option`, `default` and `into` are \
allowed as arguments to `#[prop()]`";
const ABORT_OPT_MESSAGE: &str = "only `optional`, \
`optional_no_strip`, \
`strip_option`, \
`default` and `into` are \
allowed as arguments to `#[prop()]`";
if attr.path != parse_quote!(prop) {
return None;
}
if let Meta::List(MetaList { nested, .. }) = attr.parse_meta().unwrap_or_abort() {
if let Meta::List(MetaList { nested, .. }) = attr.parse_meta().ok()? {
Some(
nested
.iter()
@@ -612,9 +613,9 @@ fn is_option(ty: &Type) -> bool {
}
fn unwrap_option(ty: &Type) -> Option<Type> {
const STD_OPTION_MSG: &str =
"make sure you're not shadowing the `std::option::Option` type that is \
automatically imported from the standard prelude";
const STD_OPTION_MSG: &str = "make sure you're not shadowing the \
`std::option::Option` type that is automatically imported from the \
standard prelude";
if let Type::Path(TypePath {
path: Path { segments, .. },

View File

@@ -230,22 +230,6 @@ mod server;
/// # });
/// ```
///
/// 10. You can set any HTML elements `innerHTML` with the `inner_html` attribute on an
/// element. Be careful: this HTML will not be escaped, so you should ensure that it
/// only contains trusted input.
/// ```rust
/// # use leptos::*;
/// # run_scope(create_runtime(), |cx| {
/// # if !cfg!(any(feature = "csr", feature = "hydrate")) {
/// let html = "<p>This HTML will be injected.</p>";
/// view! { cx,
/// <div inner_html=html/>
/// }
/// # ;
/// # }
/// # });
/// ```
///
/// Heres a simple example that shows off several of these features, put together
/// ```rust
/// # use leptos::*;
@@ -457,14 +441,12 @@ pub fn view(tokens: TokenStream) -> TokenStream {
/// ```
///
/// 5. You can access the children passed into the component with the `children` property, which takes
/// an argument of the type `Children`. This is an alias for `Box<dyn FnOnce(Scope) -> Fragment>`.
/// If you need `children` to be a `Fn` or `FnMut`, you can use the `ChildrenFn` or `ChildrenFnMut`
/// type aliases.
/// an argument of the form `Box<dyn FnOnce(Scope) -> Fragment>`.
///
/// ```
/// # use leptos::*;
/// #[component]
/// fn ComponentWithChildren(cx: Scope, children: Children) -> impl IntoView {
/// fn ComponentWithChildren(cx: Scope, children: Box<dyn FnOnce(Scope) -> Fragment>) -> impl IntoView {
/// view! {
/// cx,
/// <ul>

View File

@@ -137,7 +137,7 @@ pub fn server_macro_impl(args: proc_macro::TokenStream, s: TokenStream2) -> Resu
};
Ok(quote::quote! {
#[derive(Clone, Debug, ::serde::Serialize, ::serde::Deserialize)]
#[derive(Clone, ::serde::Serialize, ::serde::Deserialize)]
pub struct #struct_name {
#(#fields),*
}

View File

@@ -171,7 +171,7 @@ pub(crate) fn render_view(
cx,
Span::call_site(),
nodes,
true,
false,
TagType::Unknown,
global_class,
)
@@ -219,7 +219,7 @@ fn fragment_to_tokens_ssr(
});
quote! {
{
leptos::Fragment::lazy(|| vec![
leptos::Fragment::new(vec![
#(#nodes),*
])
}
@@ -262,22 +262,11 @@ fn root_element_to_tokens_ssr(
};
let tag_name = node.name.to_string();
let typed_element_name = {
let camel_cased =
camel_case_tag_name(&tag_name.replace("svg::", "").replace("math::", ""));
Ident::new(&camel_cased, node.name.span())
};
let typed_element_name = if is_svg_element(&tag_name) {
quote! { svg::#typed_element_name }
} else if is_math_ml_element(&tag_name) {
quote! { math::#typed_element_name }
} else {
quote! { #typed_element_name }
};
let typed_element_name = Ident::new(&camel_case_tag_name(&tag_name), node.name.span());
quote! {
{
#(#exprs_for_compiler)*
::leptos::HtmlElement::from_html(cx, leptos::leptos_dom::#typed_element_name::default(), #template)
::leptos::HtmlElement::from_html(cx, leptos::#typed_element_name::default(), #template)
}
}
}
@@ -299,13 +288,8 @@ fn element_to_tokens_ssr(
{#component}.into_view(cx).render_to_string(cx),
})
} else {
let tag_name = node
.name
.to_string()
.replace("svg::", "")
.replace("math::", "");
template.push('<');
template.push_str(&tag_name);
template.push_str(&node.name.to_string());
for attr in &node.attributes {
if let Node::Attribute(attr) = attr {
@@ -352,7 +336,7 @@ fn element_to_tokens_ssr(
),
Node::Text(text) => {
if let Some(value) = value_to_string(&text.value) {
template.push_str(&html_escape::encode_safe(&value));
template.push_str(&value);
} else {
template.push_str("{}");
let value = text.value.as_ref();
@@ -406,10 +390,32 @@ fn attribute_to_tokens_ssr(
exprs_for_compiler: &mut Vec<TokenStream>,
) {
let name = node.key.to_string();
if name == "ref" || name == "_ref" || name == "node_ref" {
if name == "ref" || name == "_ref" {
// ignore refs on SSR
} else if name.strip_prefix("on:").is_some() {
let (event_type, handler) = event_from_attribute_node(node);
} else if let Some(name) = name.strip_prefix("on:") {
let handler = node
.value
.as_ref()
.expect("event listener attributes need a value")
.as_ref();
#[allow(unused_variables)]
let (name, is_force_undelegated) = parse_event(name);
let event_type = TYPED_EVENTS
.iter()
.find(|e| **e == name)
.copied()
.unwrap_or("Custom");
let event_type = event_type
.parse::<TokenStream>()
.expect("couldn't parse event name");
let event_type = if is_force_undelegated {
quote! { ::leptos::ev::undelegated(::leptos::ev::#event_type) }
} else {
quote! { ::leptos::ev::#event_type }
};
exprs_for_compiler.push(quote! {
leptos::ssr_event_listener(#event_type, #handler);
})
@@ -421,10 +427,10 @@ fn attribute_to_tokens_ssr(
if name != "class" {
template.push(' ');
template.push_str(&name);
if let Some(value) = node.value.as_ref() {
if let Some(value) = value_to_string(value) {
template.push_str(&name);
template.push_str("=\"");
template.push_str(&value);
template.push('"');
@@ -620,7 +626,7 @@ fn node_to_tokens(
cx,
Span::call_site(),
&fragment.children,
true,
false,
parent_type,
global_class,
),
@@ -702,7 +708,7 @@ fn element_to_tokens(
cx,
Span::call_site(),
&fragment.children,
true,
false,
parent_type,
global_class,
),
@@ -925,9 +931,7 @@ fn component_to_tokens(
let props = attrs
.clone()
.filter(|attr| {
!attr.key.to_string().starts_with("clone:") && !attr.key.to_string().starts_with("on:")
})
.filter(|attr| !attr.key.to_string().starts_with("clone:"))
.map(|attr| {
let name = &attr.key;
@@ -946,7 +950,6 @@ fn component_to_tokens(
});
let items_to_clone = attrs
.clone()
.filter(|attr| attr.key.to_string().starts_with("clone:"))
.map(|attr| {
let ident = attr
@@ -960,17 +963,6 @@ fn component_to_tokens(
})
.collect::<Vec<_>>();
let events = attrs
.filter(|attr| attr.key.to_string().starts_with("on:"))
.map(|attr| {
let (event_type, handler) = event_from_attribute_node(attr);
quote! {
.on(#event_type, #handler)
}
})
.collect::<Vec<_>>();
let children = if node.children.is_empty() {
quote! {}
} else {
@@ -996,55 +988,17 @@ fn component_to_tokens(
}
};
let component = quote! {
quote! {
#name(
#cx,
#component_props_name::builder()
#(#props)*
#children
.build()
.build(),
)
};
if events.is_empty() {
component
} else {
quote! {
#component.into_view(#cx)
#(#events)*
}
}
}
fn event_from_attribute_node(attr: &NodeAttribute) -> (TokenStream, &Expr) {
let event_name = attr.key.to_string().strip_prefix("on:").unwrap().to_owned();
let handler = attr
.value
.as_ref()
.expect("event listener attributes need a value")
.as_ref();
#[allow(unused_variables)]
let (name, is_force_undelegated) = parse_event(&event_name);
let event_type = TYPED_EVENTS
.iter()
.find(|e| **e == name)
.copied()
.unwrap_or("Custom");
let event_type = event_type
.parse::<TokenStream>()
.expect("couldn't parse event name");
let event_type = if is_force_undelegated {
quote! { ::leptos::ev::undelegated(::leptos::ev::#event_type) }
} else {
quote! { ::leptos::ev::#event_type }
};
(event_type, handler)
}
fn ident_from_tag_name(tag_name: &NodeName) -> Ident {
match tag_name {
NodeName::Path(path) => path

View File

@@ -200,7 +200,7 @@ where
}
impl EffectId {
pub(crate) fn run(&self, runtime_id: RuntimeId) {
pub(crate) fn run<T>(&self, runtime_id: RuntimeId) {
_ = with_runtime(runtime_id, |runtime| {
let effect = {
let effects = runtime.effects.borrow();

View File

@@ -130,8 +130,7 @@ where
});
let id = with_runtime(cx.runtime, |runtime| {
let r = Rc::clone(&r) as Rc<dyn SerializableResource>;
runtime.create_serializable_resource(r)
runtime.create_serializable_resource(Rc::clone(&r))
})
.expect("tried to create a Resource in a Runtime that has been disposed.");
@@ -251,8 +250,7 @@ where
});
let id = with_runtime(cx.runtime, |runtime| {
let r = Rc::clone(&r) as Rc<dyn UnserializableResource>;
runtime.create_unserializable_resource(r)
runtime.create_unserializable_resource(Rc::clone(&r))
})
.expect("tried to create a Resource in a runtime that has been disposed.");

View File

@@ -1,8 +1,8 @@
#![forbid(unsafe_code)]
use crate::{
hydration::SharedContext, AnyEffect, AnyResource, Effect, EffectId, Memo, ReadSignal,
ResourceId, ResourceState, RwSignal, Scope, ScopeDisposer, ScopeId, ScopeProperty,
SerializableResource, SignalId, UnserializableResource, WriteSignal,
hydration::SharedContext, serialization::Serializable, AnyEffect, AnyResource, Effect,
EffectId, Memo, ReadSignal, ResourceId, ResourceState, RwSignal, Scope, ScopeDisposer, ScopeId,
ScopeProperty, SignalId, WriteSignal,
};
use cfg_if::cfg_if;
use futures::stream::FuturesUnordered;
@@ -115,19 +115,18 @@ impl RuntimeId {
ret
}
#[track_caller]
pub(crate) fn create_concrete_signal(self, value: Rc<RefCell<dyn Any>>) -> SignalId {
with_runtime(self, |runtime| runtime.signals.borrow_mut().insert(value))
.expect("tried to create a signal in a runtime that has been disposed")
}
#[track_caller]
pub(crate) fn create_signal<T>(self, value: T) -> (ReadSignal<T>, WriteSignal<T>)
where
T: Any + 'static,
{
let id = self.create_concrete_signal(Rc::new(RefCell::new(value)) as Rc<RefCell<dyn Any>>);
let id = with_runtime(self, |runtime| {
runtime
.signals
.borrow_mut()
.insert(Rc::new(RefCell::new(value)))
})
.expect("tried to create a signal in a runtime that has been disposed");
(
ReadSignal {
runtime: self,
@@ -150,7 +149,13 @@ impl RuntimeId {
where
T: Any + 'static,
{
let id = self.create_concrete_signal(Rc::new(RefCell::new(value)) as Rc<RefCell<dyn Any>>);
let id = with_runtime(self, |runtime| {
runtime
.signals
.borrow_mut()
.insert(Rc::new(RefCell::new(value)))
})
.expect("tried to create a signal in a runtime that has been disposed");
RwSignal {
runtime: self,
id,
@@ -160,12 +165,6 @@ impl RuntimeId {
}
}
#[track_caller]
pub(crate) fn create_concrete_effect(self, effect: Rc<dyn AnyEffect>) -> EffectId {
with_runtime(self, |runtime| runtime.effects.borrow_mut().insert(effect))
.expect("tried to create an effect in a runtime that has been disposed")
}
#[track_caller]
pub(crate) fn create_effect<T>(self, f: impl Fn(Option<T>) -> T + 'static) -> EffectId
where
@@ -174,16 +173,18 @@ impl RuntimeId {
#[cfg(debug_assertions)]
let defined_at = std::panic::Location::caller();
let effect = Effect {
f,
value: RefCell::new(None),
#[cfg(debug_assertions)]
defined_at,
};
let id = self.create_concrete_effect(Rc::new(effect));
id.run(self);
id
with_runtime(self, |runtime| {
let effect = Effect {
f,
value: RefCell::new(None),
#[cfg(debug_assertions)]
defined_at,
};
let id = { runtime.effects.borrow_mut().insert(Rc::new(effect)) };
id.run::<T>(self);
id
})
.expect("tried to create an effect in a runtime that has been disposed")
}
#[track_caller]
@@ -255,19 +256,27 @@ impl Runtime {
Self::default()
}
pub(crate) fn create_unserializable_resource(
pub(crate) fn create_unserializable_resource<S, T>(
&self,
state: Rc<dyn UnserializableResource>,
) -> ResourceId {
state: Rc<ResourceState<S, T>>,
) -> ResourceId
where
S: Clone + 'static,
T: 'static,
{
self.resources
.borrow_mut()
.insert(AnyResource::Unserializable(state))
}
pub(crate) fn create_serializable_resource(
pub(crate) fn create_serializable_resource<S, T>(
&self,
state: Rc<dyn SerializableResource>,
) -> ResourceId {
state: Rc<ResourceState<S, T>>,
) -> ResourceId
where
S: Clone + 'static,
T: Serializable + 'static,
{
self.resources
.borrow_mut()
.insert(AnyResource::Serializable(state))

View File

@@ -83,17 +83,6 @@ impl Scope {
self.id
}
/// Returns the chain of scope IDs beginning with this one, going to its parent, grandparents, etc.
pub fn ancestry(&self) -> Vec<ScopeId> {
let mut ids = vec![self.id];
let mut cx = *self;
while let Some(parent) = cx.parent() {
ids.push(parent.id());
cx = parent;
}
ids
}
/// Creates a child scope and runs the given function within it, returning a handle to dispose of it.
///
/// The child scope has its own lifetime and disposer, but will be disposed when the parent is

View File

@@ -399,12 +399,6 @@ where
Dynamic(Signal<T>),
}
impl<T: Default> Default for MaybeSignal<T> {
fn default() -> Self {
Self::Static(Default::default())
}
}
impl<T> UntrackedGettableSignal<T> for MaybeSignal<T>
where
T: 'static,

View File

@@ -89,30 +89,6 @@ where
self.0.update_untracked(f);
}
/// Applies a function to the current value to mutate it in place.
/// Forwards the return value of the closure if the closure was called.
/// ```
/// use leptos_reactive::*;
/// # create_scope(create_runtime(), |cx| {
///
/// pub struct MyUncloneableData {
/// pub value: String
/// }
///
/// let data = store_value(cx, MyUncloneableData { value: "a".into() });
/// let updated = data.update_returning(|data| {
/// data.value = "b".into();
/// data.value.clone()
/// });
///
/// assert_eq!(data.with(|data| data.value.clone()), "b");
/// assert_eq!(updated, Some(String::from("b")));
/// });
/// ```
pub fn update_returning<U>(&self, f: impl FnOnce(&mut T) -> U) -> Option<U> {
self.0.update_returning_untracked(f)
}
/// Sets the stored value.
/// ```
/// # use leptos_reactive::*;

View File

@@ -14,9 +14,12 @@ leptos_reactive = { workspace = true }
form_urlencoded = "1"
gloo-net = "0.2"
lazy_static = "1"
linear-map = "1"
log = "0.4"
serde = { version = "1", features = ["derive"] }
serde_urlencoded = "0.7"
thiserror = "1"
rmp-serde = "1.1.1"
serde_json = "1.0.89"
quote = "1"
syn = { version = "1", features = ["full", "parsing", "extra-traits"] }
@@ -28,23 +31,23 @@ leptos = { path = "../leptos" }
[features]
csr = [
#"leptos/csr",
"leptos_dom/web",
"leptos_reactive/csr",
#"leptos/csr",
"leptos_dom/web",
"leptos_reactive/csr",
]
hydrate = [
#"leptos/hydrate",
"leptos_dom/web",
"leptos_reactive/hydrate",
#"leptos/hydrate",
"leptos_dom/web",
"leptos_reactive/hydrate",
]
ssr = [
#"leptos/ssr",
"leptos_reactive/ssr",
#"leptos/ssr",
"leptos_reactive/ssr",
]
stable = [
#"leptos/stable",
"leptos_dom/stable",
"leptos_reactive/stable",
#"leptos/stable",
"leptos_dom/stable",
"leptos_reactive/stable",
]
[package.metadata.cargo-all-features]

View File

@@ -1,14 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
viewBox="0 0 24 24" style="enable-background:new 0 0 24 24;" xml:space="preserve">
<g>
<path d="M10.1,17.8C7.6,17,5.9,14.6,5.9,12c0-3.4,2.7-6.1,6.1-6.1c0.3,0,0.5,0,0.8,0
c0.4-0.9,0.9-1.7,1.5-2.5c-0.5-0.6-0.8-1.4-0.8-2.3c0-0.3,0-0.7,0.1-1c-0.5-0.1-1-0.1-1.5-0.1C5.4,0.1,0.1,5.4,0.1,12
c0,4.3,2.3,8.1,5.8,10.2L6,22.1C7.9,21.2,9.3,19.7,10.1,17.8z"/>
<path d="M16.9,3c0.7,0,1.3-0.4,1.6-0.9l0,0c-1-0.6-2.1-1.1-3.2-1.5l0,0c-0.1,0.2-0.1,0.4-0.1,0.6
C15.1,2.2,15.9,3,16.9,3z"/>
<path d="M19.9,3.1c-0.7,1-1.8,1.6-2.9,1.6c-0.3,0-0.5,0-0.8-0.1c-0.2,0-0.3-0.1-0.5-0.1
c-0.5,0.6-0.9,1.2-1.2,1.9c2.2,1,3.7,3.1,3.7,5.6c0,3.4-2.7,6.1-6.1,6.1c0,0-0.1,0-0.1,0c-0.8,2.1-2.2,3.8-4.1,5
c1.3,0.5,2.7,0.8,4.2,0.8c6.6,0,11.9-5.3,11.9-11.9C23.9,8.4,22.3,5.3,19.9,3.1z"/>
<circle cx="12" cy="12" r="4.4"/>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 907 B

View File

@@ -11,7 +11,7 @@ description = "Tools to set HTML metadata in the Leptos web framework."
cfg-if = "1"
leptos = { workspace = true }
tracing = "0.1"
typed-builder = "0.12"
typed-builder = "0.11"
[dependencies.web-sys]
version = "0.3"

View File

@@ -10,7 +10,7 @@ pub struct BodyContext {
}
impl BodyContext {
/// Converts the `<body>` metadata into an HTML string.
/// Converts the <body> metadata into an HTML string.
pub fn as_string(&self) -> Option<String> {
self.class
.borrow()

View File

@@ -11,7 +11,7 @@ pub struct HtmlContext {
}
impl HtmlContext {
/// Converts the `<html>` metadata into an HTML string.
/// Converts the <html> metadata into an HTML string.
pub fn as_string(&self) -> Option<String> {
match (self.lang.borrow().as_ref(), self.dir.borrow().as_ref()) {
(None, None) => None,

View File

@@ -13,16 +13,17 @@ leptos = { workspace = true }
cfg-if = "1"
common_macros = "0.1"
gloo-net = "0.2"
itertools = "0.10"
lazy_static = "1"
linear-map = "1"
log = "0.4"
regex = { version = "1", optional = true }
bincode = "1"
url = { version = "2", optional = true }
percent-encoding = "2"
thiserror = "1"
serde_urlencoded = "0.7"
serde = "1"
tracing = "0.1"
js-sys = { version = "0.3" }
wasm-bindgen = { version = "0.2" }
wasm-bindgen-futures = { version = "0.4" }
@@ -30,26 +31,26 @@ wasm-bindgen-futures = { version = "0.4" }
[dependencies.web-sys]
version = "0.3"
features = [
# History/Routing
"History",
"HtmlAnchorElement",
"MouseEvent",
"Url",
# Form
"FormData",
"HtmlButtonElement",
"HtmlFormElement",
"HtmlInputElement",
"SubmitEvent",
"Url",
"UrlSearchParams",
# Fetching in Hydrate Mode
"Headers",
"Request",
"RequestInit",
"RequestMode",
"Response",
"Window",
# History/Routing
"History",
"HtmlAnchorElement",
"MouseEvent",
"Url",
# Form
"FormData",
"HtmlButtonElement",
"HtmlFormElement",
"HtmlInputElement",
"SubmitEvent",
"Url",
"UrlSearchParams",
# Fetching in Hydrate Mode
"Headers",
"Request",
"RequestInit",
"RequestMode",
"Response",
"Window",
]
[features]

View File

@@ -43,109 +43,86 @@ pub fn Form<A>(
where
A: ToHref + 'static,
{
fn inner(
cx: Scope,
method: Option<&'static str>,
action: Memo<Option<String>>,
enctype: Option<String>,
version: Option<RwSignal<usize>>,
error: Option<RwSignal<Option<Box<dyn Error>>>>,
#[allow(clippy::type_complexity)] on_form_data: Option<Rc<dyn Fn(&web_sys::FormData)>>,
#[allow(clippy::type_complexity)] on_response: Option<Rc<dyn Fn(&web_sys::Response)>>,
children: Children,
) -> HtmlElement<Form> {
let action_version = version;
let on_submit = move |ev: web_sys::SubmitEvent| {
if ev.default_prevented() {
return;
}
let navigate = use_navigate(cx);
let action_version = version;
let action = use_resolved_path(cx, move || action.to_href()());
let (form, method, action, enctype) = extract_form_attributes(&ev);
let on_submit = move |ev: web_sys::SubmitEvent| {
if ev.default_prevented() {
return;
}
let navigate = use_navigate(cx);
let form_data = web_sys::FormData::new_with_form(&form).unwrap_throw();
if let Some(on_form_data) = on_form_data.clone() {
on_form_data(&form_data);
}
let params =
web_sys::UrlSearchParams::new_with_str_sequence_sequence(&form_data).unwrap_throw();
let action = use_resolved_path(cx, move || action.clone())
.get()
.unwrap_or_default();
// POST
if method == "post" {
ev.prevent_default();
let (form, method, action, enctype) = extract_form_attributes(&ev);
let on_response = on_response.clone();
spawn_local(async move {
let res = gloo_net::http::Request::post(&action)
.header("Accept", "application/json")
.header("Content-Type", &enctype)
.body(params)
.send()
.await;
match res {
Err(e) => {
log::error!("<Form/> error while POSTing: {e:#?}");
if let Some(error) = error {
error.set(Some(Box::new(e)));
}
let form_data = web_sys::FormData::new_with_form(&form).unwrap_throw();
if let Some(on_form_data) = on_form_data.clone() {
on_form_data(&form_data);
}
let params =
web_sys::UrlSearchParams::new_with_str_sequence_sequence(&form_data).unwrap_throw();
let action = use_resolved_path(cx, move || action.clone())
.get()
.unwrap_or_default();
// POST
if method == "post" {
ev.prevent_default();
let on_response = on_response.clone();
spawn_local(async move {
let res = gloo_net::http::Request::post(&action)
.header("Accept", "application/json")
.header("Content-Type", &enctype)
.body(params)
.send()
.await;
match res {
Err(e) => {
log::error!("<Form/> error while POSTing: {e:#?}");
if let Some(error) = error {
error.set(Some(Box::new(e)));
}
}
Ok(resp) => {
if let Some(version) = action_version {
version.update(|n| *n += 1);
}
if let Some(error) = error {
error.set(None);
}
if let Some(on_response) = on_response.clone() {
on_response(resp.as_raw());
}
Ok(resp) => {
if let Some(version) = action_version {
version.update(|n| *n += 1);
}
if let Some(error) = error {
error.set(None);
}
if let Some(on_response) = on_response.clone() {
on_response(resp.as_raw());
}
if resp.status() == 303 {
if let Some(redirect_url) = resp.headers().get("Location") {
_ = navigate(&redirect_url, Default::default());
}
if resp.status() == 303 {
if let Some(redirect_url) = resp.headers().get("Location") {
_ = navigate(&redirect_url, Default::default());
}
}
}
});
}
// otherwise, GET
else {
let params = params.to_string().as_string().unwrap_or_default();
if navigate(&format!("{action}?{params}"), Default::default()).is_ok() {
ev.prevent_default();
}
}
};
let method = method.unwrap_or("get");
view! { cx,
<form
method=method
action=move || action.get()
enctype=enctype
on:submit=on_submit
>
{children(cx)}
</form>
});
}
}
// otherwise, GET
else {
let params = params.to_string().as_string().unwrap_or_default();
if navigate(&format!("{action}?{params}"), Default::default()).is_ok() {
ev.prevent_default();
}
}
};
let action = use_resolved_path(cx, move || action.to_href()());
inner(
cx,
method,
action,
enctype,
version,
error,
on_form_data,
on_response,
children,
)
let method = method.unwrap_or("get");
view! { cx,
<form
method=method
action=move || action.get()
enctype=enctype
on:submit=on_submit
>
{children(cx)}
</form>
}
}
/// Automatically turns a server [Action](leptos_server::Action) into an HTML

View File

@@ -70,47 +70,35 @@ pub fn A<H>(
where
H: ToHref + 'static,
{
fn inner(
cx: Scope,
href: Memo<Option<String>>,
exact: bool,
state: Option<State>,
replace: bool,
class: Option<MaybeSignal<String>>,
children: Children,
) -> HtmlElement<A> {
let location = use_location(cx);
let is_active = create_memo(cx, move |_| match href.get() {
None => false,
Some(to) => {
let path = to
.split(['?', '#'])
.next()
.unwrap_or_default()
.to_lowercase();
let loc = location.pathname.get().to_lowercase();
if exact {
loc == path
} else {
loc.starts_with(&path)
}
}
});
view! { cx,
<a
href=move || href.get().unwrap_or_default()
prop:state={state.map(|s| s.to_js_value())}
prop:replace={replace}
aria-current=move || if is_active.get() { Some("page") } else { None }
class=move || class.as_ref().map(|class| class.get())
>
{children(cx)}
</a>
}
}
let location = use_location(cx);
let href = use_resolved_path(cx, move || href.to_href()());
inner(cx, href, exact, state, replace, class, children)
let is_active = create_memo(cx, move |_| match href.get() {
None => false,
Some(to) => {
let path = to
.split(['?', '#'])
.next()
.unwrap_or_default()
.to_lowercase();
let loc = location.pathname.get().to_lowercase();
if exact {
loc == path
} else {
loc.starts_with(&path)
}
}
});
view! { cx,
<a
href=move || href.get().unwrap_or_default()
prop:state={state.map(|s| s.to_js_value())}
prop:replace={replace}
aria-current=move || if is_active.get() { Some("page") } else { None }
class=move || class.as_ref().map(|class| class.get())
>
{children(cx)}
</a>
}
}

View File

@@ -1,7 +1,6 @@
mod form;
mod link;
mod outlet;
mod redirect;
mod route;
mod router;
mod routes;
@@ -9,7 +8,6 @@ mod routes;
pub use form::*;
pub use link::*;
pub use outlet::*;
pub use redirect::*;
pub use route::*;
pub use router::*;
pub use routes::*;

View File

@@ -7,7 +7,6 @@ use leptos::*;
/// that child route is displayed. Renders nothing if there is no nested child.
#[component]
pub fn Outlet(cx: Scope) -> impl IntoView {
let id = HydrationCtx::id();
let route = use_route(cx);
let is_showing = Rc::new(Cell::new(None::<(usize, Scope)>));
let (outlet, set_outlet) = create_signal(cx, None::<View>);
@@ -27,11 +26,11 @@ pub fn Outlet(cx: Scope) -> impl IntoView {
prev_scope.dispose();
}
is_showing.set(Some((child.id(), child.cx())));
provide_context(cx, child.clone());
set_outlet.set(Some(child.outlet(cx).into_view(cx)))
provide_context(child.cx(), child.clone());
set_outlet.set(Some(child.outlet().into_view(cx)))
}
}
});
leptos::DynChild::new_with_id(id, move || outlet.get())
move || outlet.get()
}

View File

@@ -1,65 +0,0 @@
use crate::{use_navigate, use_resolved_path, NavigateOptions};
use leptos::{component, provide_context, use_context, IntoView, Scope};
use std::rc::Rc;
/// Redirects the user to a new URL, whether on the client side or on the server
/// side. If rendered on the server, this sets a `302` status code and sets a `Location`
/// header. If rendered in the browser, it uses client-side navigation to redirect.
/// In either case, it resolves the route relative to the current route. (To use
/// an absolute path, prefix it with `/`).
///
/// **Note**: Support for server-side redirects is provided by the server framework
/// integrations (`leptos_actix` and `leptos_axum`). If youre not using one of those
/// integrations, you should manually provide a way of redirecting on the server
/// using [provide_server_redirect].
#[component]
pub fn Redirect<P>(
cx: Scope,
/// The relative path to which the user should be redirected.
path: P,
/// Navigation options to be used on the client side.
#[prop(optional)]
options: Option<NavigateOptions>,
) -> impl IntoView
where
P: std::fmt::Display + 'static,
{
// resolve relative path
let path = use_resolved_path(cx, move || path.to_string());
let path = path.get().unwrap_or_else(|| "/".to_string());
// redirect on the server
if let Some(redirect_fn) = use_context::<ServerRedirectFunction>(cx) {
(redirect_fn.f)(&path);
}
// redirect on the client
let navigate = use_navigate(cx);
navigate(&path, options.unwrap_or_default())
}
/// Wrapping type for a function provided as context to allow for
/// server-side redirects. See [provide_server_redirect]
/// and [Redirect].
#[derive(Clone)]
pub struct ServerRedirectFunction {
f: Rc<dyn Fn(&str)>,
}
impl std::fmt::Debug for ServerRedirectFunction {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ServerRedirectFunction").finish()
}
}
/// Provides a function that can be used to redirect the user to another
/// absolute path, on the server. This should set a `302` status code and an
/// appropriate `Location` header.
pub fn provide_server_redirect(cx: Scope, handler: impl Fn(&str) + 'static) {
provide_context(
cx,
ServerRedirectFunction {
f: Rc::new(handler),
},
)
}

View File

@@ -36,47 +36,31 @@ where
F: Fn(Scope) -> E + 'static,
P: std::fmt::Display,
{
fn inner(
cx: Scope,
children: Option<Children>,
path: String,
view: Rc<dyn Fn(Scope) -> View>,
) -> RouteDefinition {
let children = children
.map(|children| {
children(cx)
.as_children()
.iter()
.filter_map(|child| {
child
.as_transparent()
.and_then(|t| t.downcast_ref::<RouteDefinition>())
})
.cloned()
.collect::<Vec<_>>()
})
.unwrap_or_default();
let id = ROUTE_ID.with(|id| {
let next = id.get() + 1;
id.set(next);
next
});
RouteDefinition {
id,
path,
children,
view,
}
}
inner(
cx,
let children = children
.map(|children| {
children(cx)
.as_children()
.iter()
.filter_map(|child| {
child
.as_transparent()
.and_then(|t| t.downcast_ref::<RouteDefinition>())
})
.cloned()
.collect::<Vec<_>>()
})
.unwrap_or_default();
let id = ROUTE_ID.with(|id| {
let next = id.get() + 1;
id.set(next);
next
});
RouteDefinition {
id,
path: path.to_string(),
children,
path.to_string(),
Rc::new(move |cx| view(cx).into_view(cx)),
)
view: Rc::new(move |cx| view(cx).into_view(cx)),
}
}
impl IntoView for RouteDefinition {
@@ -120,7 +104,7 @@ impl RouteContext {
path: RefCell::new(path),
original_path: route.original_path.to_string(),
params,
outlet: Box::new(move |cx| Some(element(cx))),
outlet: Box::new(move || Some(element(cx))),
}),
})
}
@@ -171,7 +155,7 @@ impl RouteContext {
path: RefCell::new(path.to_string()),
original_path: path.to_string(),
params: create_memo(cx, |_| ParamsMap::new()),
outlet: Box::new(move |cx| fallback.as_ref().map(move |f| f(cx))),
outlet: Box::new(move || fallback.as_ref().map(move |f| f(cx))),
}),
}
}
@@ -187,8 +171,8 @@ impl RouteContext {
}
/// The view associated with the current route.
pub fn outlet(&self, cx: Scope) -> impl IntoView {
(self.inner.outlet)(cx)
pub fn outlet(&self) -> impl IntoView {
(self.inner.outlet)()
}
}
@@ -200,7 +184,7 @@ pub(crate) struct RouteContextInner {
pub(crate) path: RefCell<String>,
pub(crate) original_path: String,
pub(crate) params: Memo<ParamsMap>,
pub(crate) outlet: Box<dyn Fn(Scope) -> Option<View>>,
pub(crate) outlet: Box<dyn Fn() -> Option<View>>,
}
impl PartialEq for RouteContextInner {

View File

@@ -29,6 +29,7 @@ pub fn Routes(
let base_route = router.base();
let mut branches = Vec::new();
let id_before = HydrationCtx::peek();
let frag = children(cx);
let children = frag
.as_children()
@@ -194,12 +195,11 @@ pub fn Routes(
});
// show the root route
let id = HydrationCtx::id();
let root = create_memo(cx, move |prev| {
provide_context(cx, route_states);
route_states.with(|state| {
if state.routes.borrow().is_empty() {
Some(base_route.outlet(cx).into_view(cx))
Some(base_route.outlet().into_view(cx))
} else {
let root = state.routes.borrow();
let root = root.get(0);
@@ -208,7 +208,7 @@ pub fn Routes(
}
if prev.is_none() || !root_equal.get() {
root.as_ref().map(|route| route.outlet(cx).into_view(cx))
root.as_ref().map(|route| route.outlet().into_view(cx))
} else {
prev.cloned().unwrap()
}
@@ -216,8 +216,8 @@ pub fn Routes(
})
});
//HydrationCtx::continue_from(id_before);
leptos::DynChild::new_with_id(id, move || root.get())
HydrationCtx::continue_from(id_before);
(move || root.get()).into_view(cx)
}
#[derive(Clone, Debug, PartialEq)]

View File

@@ -8,6 +8,10 @@
//! apps (SPAs), server-side rendering/multi-page apps (MPAs), or to synchronize
//! state between the two.
//!
//! **Note:** This is a work in progress. The feature to pass client-side route [State] in
//! [History.state](https://developer.mozilla.org/en-US/docs/Web/API/History/state), in particular,
//! is incomplete.
//!
//! ## Philosophy
//!
//! Leptos Router is built on a few simple principles:
@@ -19,7 +23,12 @@
//! and are rendered by different components. This means you can navigate between siblings
//! in this tree without re-rendering or triggering any change in the parent routes.
//!
//! 3. **Progressive enhancement.** The [A] and [Form] components resolve any relative
//! 3. **Route-based data loading.** Each route should know exactly which data it needs
//! to render itself when the route is defined. This allows each routes data to be
//! reloaded independently, and allows data from nested routes to be loaded in parallel,
//! avoiding waterfalls.
//!
//! 4. **Progressive enhancement.** The [A] and [Form] components resolve any relative
//! nested routes, render actual `<a>` and `<form>` elements, and (when possible)
//! upgrading them to handle those navigations with client-side routing. If youre using
//! them with server-side rendering (with or without hydration), they just work,
@@ -193,7 +202,6 @@ mod history;
mod hooks;
#[doc(hidden)]
pub mod matching;
pub use matching::RouteDefinition;
pub use components::*;
#[cfg(any(feature = "ssr", doc))]

View File

@@ -3,18 +3,11 @@ use std::rc::Rc;
use leptos::leptos_dom::View;
use leptos::*;
/// Defines a single route in a nested route tree. This is the return
/// type of the [`<Route/>`](crate::Route) component, but can also be
/// used to build your own configuration-based or filesystem-based routing.
#[derive(Clone)]
pub struct RouteDefinition {
/// A unique ID for each route.
pub id: usize,
/// The path. This can include params like `:id` or wildcards like `*all`.
pub path: String,
/// Other route definitions nested within this one.
pub children: Vec<RouteDefinition>,
/// The view that should be displayed when this route is matched.
pub view: Rc<dyn Fn(Scope) -> View>,
}