Compare commits

..

23 Commits

Author SHA1 Message Date
Greg Johnston
52c5a88e53 Construct all fragments lazily (closes #299 and #421) 2023-01-31 23:34:33 -05:00
Greg Johnston
25dfd88978 Add html-escape dependency 2023-01-31 23:26:31 -05:00
Greg Johnston
066ad56dbd Fix HTML entities 2023-01-31 22:31:15 -05:00
Greg Johnston
decd5fbfdb clippy 2023-01-31 22:28:01 -05:00
Greg Johnston
fdb6425504 Correctly escape special HTML characters in static strings in view macro 2023-01-31 22:07:17 -05:00
Ben Wishovich
160f336303 Update ErrorBoundary to use miette::Diagnostic instead of Error, and various other tweaks (#401)
* Switch RwLock to parking_lot so they are no longer async
* cleanup todo_app_sqlite_axum
* add errors_axum example

---------

Co-authored-by: Indrazar <110272232+Indrazar@users.noreply.github.com>
2023-01-31 21:56:42 -05:00
starmaker
e2b1365e46 Implemented update_returning for StoredValue (#419) 2023-01-31 17:40:39 -05:00
Greg Johnston
45eee12b18 Fix issues with attribute names in SSR (#418) 2023-01-31 11:57:05 -05:00
Bruno De Simone
e2cdbc746f Add leptos_routes functions for integrations (#415)
* added leptos_routes_with_context

* added leptos_routes_with_handler for axum integration
2023-01-31 09:09:58 -05:00
Ben Wishovich
48cf8d9382 Switch RwLock to parking_lot so they are no longer async (#414) 2023-01-30 20:11:56 -05:00
Greg Johnston
42e50327a6 Fix <option> and <use> top-level types in SSR (#416) 2023-01-30 20:10:07 -05:00
martin frances
ea0e2ce363 Escape <HTML> and <BODY> tokens in documentation markup. (#410) 2023-01-30 19:17:41 -05:00
martin frances
465cbc36be Minor: Bump typed-builder from 0.11 to 0.12. (#409) 2023-01-30 19:17:09 -05:00
Greg Johnston
62061f90ea Add <Html/> and <Body/> components in leptos_meta (#407)
Closes #376.
2023-01-29 19:07:48 -05:00
Greg Johnston
9a231ddef0 Merge pull request #408 from leptos-rs/fix-boolean-attributes-ssr
Fix boolean attributes in `view` macro fast-path SSR
2023-01-29 18:43:21 -05:00
Greg Johnston
ce6a093f9f oops 2023-01-29 17:11:02 -05:00
Greg Johnston
f07fa0e0be escape attributes 2023-01-29 16:55:28 -05:00
Greg Johnston
43ad91512a Fixes boolean attributes in SSR (closes #405) 2023-01-29 16:29:06 -05:00
Greg Johnston
116d23f2c3 Revert "fix: Fixes boolean attributes in HTML fast-path (closes issue #405)"
This reverts commit 2ecb345a79.
2023-01-29 16:27:28 -05:00
Greg Johnston
2ecb345a79 fix: Fixes boolean attributes in HTML fast-path (closes issue #405) 2023-01-29 16:02:47 -05:00
Greg Johnston
f55f833426 Merge pull request #403 from leptos-rs/children-type-alias
Add `Children` type alias
2023-01-29 07:07:09 -05:00
Greg Johnston
7101a2f55e Add Children type alias 2023-01-28 22:32:00 -05:00
Greg Johnston
f8b76387ec Fix labels in parent_child README 2023-01-28 21:52:16 -05:00
46 changed files with 1098 additions and 192 deletions

View File

@@ -0,0 +1,94 @@
[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

@@ -0,0 +1,21 @@
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

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

View File

@@ -0,0 +1,42 @@
# Leptos Todo App Sqlite with Axum
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 as it requires the server to send HTTP 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.

After

Width:  |  Height:  |  Size: 15 KiB

View File

@@ -0,0 +1,66 @@
use crate::errors::AppError;
use cfg_if::cfg_if;
use leptos::Errors;
use leptos::{
component, create_rw_signal, use_context, view, For, ForProps, IntoView, RwSignal, Scope,
};
#[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

@@ -0,0 +1,19 @@
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

@@ -0,0 +1,49 @@
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

@@ -0,0 +1,80 @@
use crate::{
error_template::{ErrorTemplate, ErrorTemplateProps},
errors::AppError,
};
use cfg_if::cfg_if;
use leptos::*;
use leptos_meta::*;
use leptos_router::*;
cfg_if! { if #[cfg(feature = "ssr")] {
pub fn register_server_functions() {
_ = CauseInternalServerError::register();
_ = CauseNotFoundError::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(),
))
}
#[server(CauseNotFoundError, "/api")]
pub async fn cause_not_found_error() -> Result<(), ServerFnError> {
Err(ServerFnError::ServerError("Not Found".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,
<ErrorBoundary fallback=|cx, errors| view!{cx, <ErrorTemplate errors=errors/>}>
<ExampleErrors/>
</ErrorBoundary>
}/>
</Routes>
</main>
</Router>
}
}
#[component]
pub fn ExampleErrors(cx: Scope) -> impl IntoView {
view! {
cx,
<p>
"This link will load a 404 page since it does not exist. Verify with browser development tools:"
<a href="/404">"This Page Does not Exist"</a>
</p>
<p>
"The following <div> will always contain an error and cause the page to produce status 500. Check browser dev tools. "
</p>
<div>
<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

@@ -0,0 +1,25 @@
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

@@ -0,0 +1,74 @@
use cfg_if::cfg_if;
use leptos::*;
// boilerplate to run in different modes
cfg_if! {
if #[cfg(feature = "ssr")] {
use axum::{
routing::{post, get},
extract::{Extension, Path},
http::Request,
response::{IntoResponse, Response},
Router,
};
use axum::body::Body as AxumBody;
use crate::landing::*;
use errors_axum::*;
use crate::fallback::file_and_error_handler;
use leptos_axum::{generate_route_list, LeptosRoutes};
use std::sync::Arc;
//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{
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()
}
#[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();
}
}
// client-only stuff for Trunk
else {
use todo_app_sqlite_axum::landing::*;
pub fn main() {
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, <App/> }
});
}
}
}

View File

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

View File

@@ -2,12 +2,12 @@
This example highlights four different ways that child components can communicate with their parent:
1. <ButtonA/>: passing a WriteSignal as one of the child component props,
1. `<ButtonA/>`: passing a WriteSignal as one of the child component props,
for the child component to write into and the parent to read
2. <ButtonB/>: passing a closure as one of the child component props, for
2. `<ButtonB/>`: passing a closure as one of the child component props, for
the child component to call
3. <ButtonC/>: adding a simple event listener on the child component itself
4. <ButtonD/>: providing a context that is used in the component (rather than prop drilling)
3. `<ButtonC/>`: adding a simple event listener on the child component itself
4. `<ButtonD/>`: providing a context that is used in the component (rather than prop drilling)
## Client Side Rendering

View File

@@ -34,12 +34,14 @@ 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", "leptos_axum"]
ssr = ["dep:axum", "dep:tower", "dep:tower-http", "dep:tokio", "dep:sqlx", "leptos/ssr", "leptos_meta/ssr", "leptos_router/ssr", "dep:leptos_axum"]
[package.metadata.cargo-all-features]
denylist = [

View File

@@ -3,8 +3,7 @@
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
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`.
This example cannot be built as a trunk standalone CSR-only app. Only the server may directly connect to the database.
## 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,28 +1,70 @@
use crate::errors::TodoAppError;
use cfg_if::cfg_if;
use leptos::Errors;
use leptos::{view, For, ForProps, IntoView, RwSignal, Scope, View};
use leptos::{
component, create_rw_signal, use_context, view, For, ForProps, IntoView, RwSignal, Scope,
};
#[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
pub fn error_template(cx: Scope, errors: Option<RwSignal<Errors>>) -> View {
let Some(errors) = errors else {
panic!("No Errors found and we expected errors!");
#[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) => {
let errors = create_rw_signal(cx, e);
errors
}
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<TodoAppError> = errors
.into_iter()
.map(|(_k, v)| v.downcast_ref::<TodoAppError>().cloned())
.flatten()
.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.get().0.into_iter()}
each= move || {errors.clone().into_iter().enumerate()}
// a unique key for each item as a reference
key=|error| error.0.clone()
key=|(index, _error)| index.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

@@ -0,0 +1,19 @@
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,8 +12,9 @@ if #[cfg(feature = "ssr")] {
use tower::ServiceExt;
use tower_http::services::ServeDir;
use std::sync::Arc;
use leptos::{LeptosOptions};
use crate::error_template::error_template;
use leptos::{LeptosOptions, Errors, view};
use crate::error_template::{ErrorTemplate, ErrorTemplateProps};
use crate::errors::TodoAppError;
pub async fn file_and_error_handler(uri: Uri, Extension(options): Extension<Arc<LeptosOptions>>, req: Request<Body>) -> AxumResponse {
let options = &*options;
@@ -23,7 +24,9 @@ if #[cfg(feature = "ssr")] {
if res.status() == StatusCode::OK {
res.into_response()
} else{
let handler = leptos_axum::render_app_to_stream(options.to_owned(), |cx| error_template(cx, None));
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()/>});
handler(req).await.into_response()
}
}

View File

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

View File

@@ -7,7 +7,6 @@ if #[cfg(feature = "ssr")] {
routing::{post, get},
extract::{Extension, Path},
http::Request,
body::StreamBody,
response::{IntoResponse, Response},
Router,
};
@@ -17,7 +16,6 @@ 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{

View File

@@ -1,3 +1,4 @@
use crate::error_template::{ErrorTemplate, ErrorTemplateProps};
use cfg_if::cfg_if;
use leptos::*;
use leptos_meta::*;
@@ -40,9 +41,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;
@@ -107,7 +108,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,
@@ -121,8 +122,10 @@ 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

@@ -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 async fn overwrite(&self, parts: ResponseParts) {
let mut writable = self.0.write().await;
pub fn overwrite(&self, parts: ResponseParts) {
let mut writable = self.0.write();
*writable = parts
}
/// Set the status of the returned Response
pub async fn set_status(&self, status: StatusCode) {
let mut writeable = self.0.write().await;
pub fn set_status(&self, status: StatusCode) {
let mut writeable = self.0.write();
let res_parts = &mut *writeable;
res_parts.status = Some(status);
}
/// Insert a header, overwriting any previous value with the same key
pub async fn insert_header(&self, key: header::HeaderName, value: header::HeaderValue) {
let mut writeable = self.0.write().await;
pub fn insert_header(&self, key: header::HeaderName, value: header::HeaderValue) {
let mut writeable = self.0.write();
let res_parts = &mut *writeable;
res_parts.headers.insert(key, value);
}
/// Append a header, leaving any header with the same key intact
pub async fn append_header(&self, key: header::HeaderName, value: header::HeaderValue) {
let mut writeable = self.0.write().await;
pub fn append_header(&self, key: header::HeaderName, value: header::HeaderValue) {
let mut writeable = self.0.write();
let res_parts = &mut *writeable;
res_parts.headers.append(key, value);
}
@@ -76,15 +76,13 @@ 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 async fn redirect(cx: leptos::Scope, path: &str) {
pub fn redirect(cx: leptos::Scope, path: &str) {
let response_options = use_context::<ResponseOptions>(cx).unwrap();
response_options.set_status(StatusCode::FOUND).await;
response_options
.insert_header(
header::LOCATION,
header::HeaderValue::from_str(path).expect("Failed to create HeaderValue"),
)
.await;
response_options.set_status(StatusCode::FOUND);
response_options.insert_header(
header::LOCATION,
header::HeaderValue::from_str(path).expect("Failed to create HeaderValue"),
);
}
/// An Actix [Route](actix_web::Route) that listens for a `POST` request with
@@ -182,7 +180,7 @@ pub fn handle_server_fns_with_context(
runtime.dispose();
let mut res: HttpResponseBuilder;
let mut res_parts = res_options.0.write().await;
let mut res_parts = res_options.0.write();
if accept_header == Some("application/json")
|| accept_header == Some("application/x-www-form-urlencoded")
@@ -339,9 +337,7 @@ where
}
};
let (head, tail) = html_parts(&options);
stream_app(app, head, tail, res_options, additional_context).await
stream_app(&options, app, res_options, additional_context).await
}
})
}
@@ -429,9 +425,7 @@ where
}
};
let (head, tail) = html_parts(&options);
stream_app(app, head, tail, res_options, |_cx| {}).await
stream_app(&options, app, res_options, |_cx| {}).await
}
})
}
@@ -457,23 +451,31 @@ fn leptos_corrected_path(req: &HttpRequest) -> String {
}
async fn stream_app(
options: &LeptosOptions,
app: impl FnOnce(leptos::Scope) -> View + 'static,
head: String,
tail: String,
res_options: ResponseOptions,
additional_context: impl Fn(leptos::Scope) + 'static + Clone + Send,
) -> HttpResponse<BoxBody> {
let (stream, runtime, _) = render_to_stream_with_prefix_undisposed_with_context(
let (stream, runtime, scope) = render_to_stream_with_prefix_undisposed_with_context(
app,
move |cx| {
let head = use_context::<MetaContext>(cx)
let meta = use_context::<MetaContext>(cx);
let head = meta
.as_ref()
.map(|meta| meta.dehydrate())
.unwrap_or_default();
format!("{head}</head><body>").into()
let body_meta = meta
.as_ref()
.and_then(|meta| meta.body.as_string())
.unwrap_or_default();
format!("{head}</head><body{body_meta}>").into()
},
additional_context,
);
let cx = leptos::Scope { runtime, id: scope };
let (head, tail) = html_parts(options, use_context::<MetaContext>(cx).as_ref());
let mut stream = Box::pin(
futures::stream::once(async move { head.clone() })
.chain(stream)
@@ -489,7 +491,7 @@ async fn stream_app(
let second_chunk = stream.next().await;
let third_chunk = stream.next().await;
let res_options = res_options.0.read().await;
let res_options = res_options.0.read();
let (status, mut headers) = (res_options.status, res_options.headers.clone());
let status = status.unwrap_or_default();
@@ -516,7 +518,7 @@ async fn stream_app(
res
}
fn html_parts(options: &LeptosOptions) -> (String, String) {
fn html_parts(options: &LeptosOptions, meta_context: Option<&MetaContext>) -> (String, String) {
// Because wasm-pack adds _bg to the end of the WASM filename, and we want to mantain compatibility with it's default options
// we add _bg to the wasm files if cargo-leptos doesn't set the env var LEPTOS_OUTPUT_NAME
// Otherwise we need to add _bg because wasm_pack always does. This is not the same as options.output_name, which is set regardless
@@ -557,9 +559,12 @@ fn html_parts(options: &LeptosOptions) -> (String, String) {
false => "".to_string(),
};
let html_metadata = meta_context
.and_then(|mc| mc.html.as_string())
.unwrap_or_default();
let head = format!(
r#"<!DOCTYPE html>
<html lang="en">
<html{html_metadata}>
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
@@ -641,6 +646,16 @@ 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
@@ -687,4 +702,28 @@ 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

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

View File

@@ -19,8 +19,9 @@ 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::{sync::RwLock, task::spawn_blocking, task::LocalSet};
use tokio::{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
@@ -59,25 +60,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 async fn overwrite(&self, parts: ResponseParts) {
let mut writable = self.0.write().await;
pub fn overwrite(&self, parts: ResponseParts) {
let mut writable = self.0.write();
*writable = parts
}
/// Set the status of the returned Response
pub async fn set_status(&self, status: StatusCode) {
let mut writeable = self.0.write().await;
pub fn set_status(&self, status: StatusCode) {
let mut writeable = self.0.write();
let res_parts = &mut *writeable;
res_parts.status = Some(status);
}
/// Insert a header, overwriting any previous value with the same key
pub async fn insert_header(&self, key: HeaderName, value: HeaderValue) {
let mut writeable = self.0.write().await;
pub fn insert_header(&self, key: HeaderName, value: HeaderValue) {
let mut writeable = self.0.write();
let res_parts = &mut *writeable;
res_parts.headers.insert(key, value);
}
/// Append a header, leaving any header with the same key intact
pub async fn append_header(&self, key: HeaderName, value: HeaderValue) {
let mut writeable = self.0.write().await;
pub fn append_header(&self, key: HeaderName, value: HeaderValue) {
let mut writeable = self.0.write();
let res_parts = &mut *writeable;
res_parts.headers.append(key, value);
}
@@ -86,15 +87,13 @@ 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 async fn redirect(cx: leptos::Scope, path: &str) {
pub fn redirect(cx: leptos::Scope, path: &str) {
let response_options = use_context::<ResponseOptions>(cx).unwrap();
response_options.set_status(StatusCode::FOUND).await;
response_options
.insert_header(
header::LOCATION,
header::HeaderValue::from_str(path).expect("Failed to create HeaderValue"),
)
.await;
response_options.set_status(StatusCode::FOUND);
response_options.insert_header(
header::LOCATION,
header::HeaderValue::from_str(path).expect("Failed to create HeaderValue"),
);
}
/// Decomposes an HTTP request into its parts, allowing you to read its headers
@@ -226,7 +225,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().await;
let res_options_inner = res_options_outer.read();
let (status, mut res_headers) = (
res_options_inner.status,
res_options_inner.headers.clone(),
@@ -420,61 +419,6 @@ where
let full_path = format!("http://leptos.dev{path}");
let pkg_path = &options.site_pkg_dir;
let output_name = &options.output_name;
// Because wasm-pack adds _bg to the end of the WASM filename, and we want to mantain compatibility with it's default options
// we add _bg to the wasm files if cargo-leptos doesn't set the env var LEPTOS_OUTPUT_NAME
// Otherwise we need to add _bg because wasm_pack always does. This is not the same as options.output_name, which is set regardless
let mut wasm_output_name = output_name.clone();
if std::env::var("LEPTOS_OUTPUT_NAME").is_err() {
wasm_output_name.push_str("_bg");
}
let site_ip = &options.site_address.ip().to_string();
let reload_port = options.reload_port;
let leptos_autoreload = match std::env::var("LEPTOS_WATCH").is_ok() {
true => format!(
r#"
<script crossorigin="">(function () {{
var ws = new WebSocket('ws://{site_ip}:{reload_port}/live_reload');
ws.onmessage = (ev) => {{
let msg = JSON.parse(ev.data);
if (msg.all) window.location.reload();
if (msg.css) {{
const link = document.querySelector("link#leptos");
if (link) {{
let href = link.getAttribute('href').split('?')[0];
let newHref = href + '?version=' + new Date().getMilliseconds();
link.setAttribute('href', newHref);
}} else {{
console.warn("Could not find link#leptos");
}}
}};
}};
ws.onclose = () => console.warn('Live-reload stopped. Manual reload necessary.');
}})()
</script>
"#
),
false => "".to_string(),
};
let head = format!(
r#"<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<link rel="modulepreload" href="/{pkg_path}/{output_name}.js">
<link rel="preload" href="/{pkg_path}/{wasm_output_name}.wasm" as="fetch" type="application/wasm" crossorigin="">
<script type="module">import init, {{ hydrate }} from '/{pkg_path}/{output_name}.js'; init('/{pkg_path}/{wasm_output_name}.wasm').then(hydrate);</script>
{leptos_autoreload}
"#
);
let tail = "</body></html>";
let (mut tx, rx) = futures::channel::mpsc::channel(8);
spawn_blocking({
@@ -518,19 +462,24 @@ where
},
add_context,
);
let cx = Scope { runtime, id: scope };
let (head, tail) = html_parts(&options, use_context::<MetaContext>(cx).as_ref());
_ = tx.send(head).await;
let mut shell = Box::pin(bundle);
while let Some(fragment) = shell.next().await {
_ = tx.send(fragment).await;
}
_ = tx.send(tail.to_string()).await;
// Extract the value of ResponseOptions from here
let cx = Scope { runtime, id: scope };
let res_options =
use_context::<ResponseOptions>(cx).unwrap();
let new_res_parts = res_options.0.read().await.clone();
let new_res_parts = res_options.0.read().clone();
let mut writable = res_options2.0.write().await;
let mut writable = res_options2.0.write();
*writable = new_res_parts;
runtime.dispose();
@@ -543,12 +492,7 @@ where
}
});
let mut stream = Box::pin(
futures::stream::once(async move { head.clone() })
.chain(rx)
.chain(futures::stream::once(async { tail.to_string() }))
.map(|html| Ok(Bytes::from(html))),
);
let mut stream = Box::pin(rx.map(|html| Ok(Bytes::from(html))));
// Get the first, second, and third chunks in the stream, which renders the app shell, and thus allows Resources to run
let first_chunk = stream.next().await;
@@ -556,7 +500,7 @@ where
let third_chunk = stream.next().await;
// Extract the resources now that they've been rendered
let res_options = res_options3.0.read().await;
let res_options = res_options3.0.read();
let complete_stream = futures::stream::iter([
first_chunk.unwrap(),
@@ -581,6 +525,65 @@ where
}
}
fn html_parts(options: &LeptosOptions, meta: Option<&MetaContext>) -> (String, &'static str) {
let pkg_path = &options.site_pkg_dir;
let output_name = &options.output_name;
// Because wasm-pack adds _bg to the end of the WASM filename, and we want to mantain compatibility with it's default options
// we add _bg to the wasm files if cargo-leptos doesn't set the env var LEPTOS_OUTPUT_NAME
// Otherwise we need to add _bg because wasm_pack always does. This is not the same as options.output_name, which is set regardless
let mut wasm_output_name = output_name.clone();
if std::env::var("LEPTOS_OUTPUT_NAME").is_err() {
wasm_output_name.push_str("_bg");
}
let site_ip = &options.site_address.ip().to_string();
let reload_port = options.reload_port;
let leptos_autoreload = match std::env::var("LEPTOS_WATCH").is_ok() {
true => format!(
r#"
<script crossorigin="">(function () {{
var ws = new WebSocket('ws://{site_ip}:{reload_port}/live_reload');
ws.onmessage = (ev) => {{
let msg = JSON.parse(ev.data);
if (msg.all) window.location.reload();
if (msg.css) {{
const link = document.querySelector("link#leptos");
if (link) {{
let href = link.getAttribute('href').split('?')[0];
let newHref = href + '?version=' + new Date().getMilliseconds();
link.setAttribute('href', newHref);
}} else {{
console.warn("Could not find link#leptos");
}}
}};
}};
ws.onclose = () => console.warn('Live-reload stopped. Manual reload necessary.');
}})()
</script>
"#
),
false => "".to_string(),
};
let html_metadata = meta.and_then(|mc| mc.html.as_string()).unwrap_or_default();
let head = format!(
r#"<!DOCTYPE html>
<html{html_metadata}>
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<link rel="modulepreload" href="/{pkg_path}/{output_name}.js">
<link rel="preload" href="/{pkg_path}/{wasm_output_name}.wasm" as="fetch" type="application/wasm" crossorigin="">
<script type="module">import init, {{ hydrate }} from '/{pkg_path}/{output_name}.js'; init('/{pkg_path}/{wasm_output_name}.wasm').then(hydrate);</script>
{leptos_autoreload}
"#
);
let tail = "</body></html>";
(head, tail)
}
/// Generates a list of all routes defined in Leptos's Router in your app. We can then use this to automatically
/// create routes in Axum's Router without having to use wildcard matching or fallbacks. Takes in your root app Element
/// as an argument so it can walk you app tree. This version is tailored to generate Axum compatible paths.
@@ -601,7 +604,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().await;
let mut writable = routes_inner.0.write();
*writable = routes;
})
.await
@@ -609,7 +612,7 @@ where
})
.await;
let routes = routes.0.read().await.to_owned();
let routes = routes.0.read().to_owned();
// Axum's Router defines Root routes as "/" not ""
let routes: Vec<String> = routes
.into_iter()
@@ -634,6 +637,21 @@ 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.
@@ -656,4 +674,40 @@ 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,7 +16,7 @@ leptos_reactive = { workspace = true }
leptos_server = { workspace = true }
leptos_config = { workspace = true }
tracing = "0.1"
typed-builder = "0.11"
typed-builder = "0.12"
once_cell = "1.17.0"
[dev-dependencies]
@@ -24,10 +24,30 @@ 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

@@ -1,4 +1,5 @@
use leptos_dom::{Errors, Fragment, IntoView};
use crate::Children;
use leptos_dom::{Errors, IntoView};
use leptos_macro::component;
use leptos_reactive::{create_rw_signal, provide_context, RwSignal, Scope};
@@ -29,12 +30,12 @@ use leptos_reactive::{create_rw_signal, provide_context, RwSignal, Scope};
pub fn ErrorBoundary<F, IV>(
cx: Scope,
/// The components inside the tag which will get rendered
children: Box<dyn FnOnce(Scope) -> Fragment>,
children: Children,
/// A fallback that will be shown if an error occurs.
fallback: F,
) -> impl IntoView
where
F: Fn(Scope, Option<RwSignal<Errors>>) -> IV + 'static,
F: Fn(Scope, RwSignal<Errors>) -> IV + 'static,
IV: IntoView,
{
let errors: RwSignal<Errors> = create_rw_signal(cx, Errors::default());
@@ -46,6 +47,6 @@ where
move || match errors.get().0.is_empty() {
true => children.clone().into_view(cx),
false => fallback(cx, Some(errors)).into_view(cx),
false => fallback(cx, errors).into_view(cx),
}
}

View File

@@ -164,3 +164,11 @@ pub use transition::*;
pub use leptos_reactive::debug_warn;
extern crate self as leptos;
/// The most common type for the `children` property on components,
/// which can only be called once.
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>;

View File

@@ -1,5 +1,6 @@
use crate::Children;
use leptos::component;
use leptos_dom::{Fragment, IntoView};
use leptos_dom::IntoView;
use leptos_reactive::Scope;
use once_cell::sync::Lazy;
@@ -29,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 FnOnce(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

View File

@@ -129,3 +129,22 @@ fn ssr_with_styles() {
);
});
}
#[cfg(not(any(feature = "csr", feature = "hydrate")))]
#[test]
fn ssr_option() {
use leptos::*;
_ = create_scope(create_runtime(), |cx| {
let (value, set_value) = create_signal(cx, 0);
let rendered = view! {
cx,
<option/>
};
assert_eq!(
rendered.into_view(cx).render_to_string(cx),
"<option id=\"_0-1\"></option>"
);
});
}

View File

@@ -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.11"
typed-builder = "0.12"

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>>);
pub struct Errors(pub HashMap<HydrationKey, Arc<dyn Error + Send + Sync>>);
impl<T, E> IntoView for Result<T, E>
where
T: IntoView + 'static,
E: std::error::Error + Send + Sync + 'static,
E: Error + Send + Sync + 'static,
{
fn into_view(self, cx: leptos_reactive::Scope) -> crate::View {
match self {
@@ -59,14 +59,21 @@ 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 + 'static,
E: Error + Send + Sync + '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 + 'static,
E: Error + Send + Sync + 'static,
{
self.0.remove(key);
}

View File

@@ -49,9 +49,9 @@ impl Attribute {
/// Converts the attribute to its HTML value at that moment, not including
/// the attribute name, so it can be rendered on the server.
pub fn as_nameless_value_string(&self) -> String {
pub fn as_nameless_value_string(&self) -> Option<String> {
match self {
Attribute::String(value) => value.to_string(),
Attribute::String(value) => Some(value.to_string()),
Attribute::Fn(_, f) => {
let mut value = f();
while let Attribute::Fn(_, f) = value {
@@ -59,11 +59,16 @@ impl Attribute {
}
value.as_nameless_value_string()
}
Attribute::Option(_, value) => value
.as_ref()
.map(|value| value.to_string())
.unwrap_or_default(),
Attribute::Bool(_) => String::new(),
Attribute::Option(_, value) => {
value.as_ref().map(|value| value.to_string())
}
Attribute::Bool(include) => {
if *include {
Some("".to_string())
} else {
None
}
}
}
}
}

View File

@@ -14,6 +14,7 @@ proc-macro = true
[dependencies]
cfg-if = "1"
doc-comment = "0.3"
html-escape = "0.2"
itertools = "0.10"
pad-adapter = "0.1"
prettyplease = "0.1"
@@ -31,7 +32,7 @@ convert_case = "0.6.0"
[dev-dependencies]
log = "0.4"
typed-builder = "0.11"
typed-builder = "0.12"
leptos = { path = "../leptos" }
[features]

View File

@@ -171,7 +171,7 @@ pub(crate) fn render_view(
cx,
Span::call_site(),
nodes,
false,
true,
TagType::Unknown,
global_class,
)
@@ -219,7 +219,7 @@ fn fragment_to_tokens_ssr(
});
quote! {
{
leptos::Fragment::new(vec![
leptos::Fragment::lazy(|| vec![
#(#nodes),*
])
}
@@ -336,7 +336,7 @@ fn element_to_tokens_ssr(
),
Node::Text(text) => {
if let Some(value) = value_to_string(&text.value) {
template.push_str(&value);
template.push_str(&html_escape::encode_safe(&value));
} else {
template.push_str("{}");
let value = text.value.as_ref();
@@ -427,18 +427,21 @@ 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('"');
} else {
template.push_str("=\"{}\"");
template.push_str("{}");
let value = value.as_ref();
holes.push(quote! {
leptos::escape_attr(&{#value}.into_attribute(#cx).as_nameless_value_string()),
&{#value}.into_attribute(#cx)
.as_nameless_value_string()
.map(|a| format!("{}=\"{}\"", #name, leptos::escape_attr(&a)))
.unwrap_or_default(),
})
}
}
@@ -555,7 +558,9 @@ fn set_class_attribute_ssr(
template.push_str(" {}");
let value = value.as_ref();
holes.push(quote! {
leptos::escape_attr(&(cx, #value).into_attribute(#cx).as_nameless_value_string()),
&(cx, #value).into_attribute(#cx).as_nameless_value_string()
.map(|a| leptos::escape_attr(&a).to_string())
.unwrap_or_default(),
});
}
}
@@ -621,7 +626,7 @@ fn node_to_tokens(
cx,
Span::call_site(),
&fragment.children,
false,
true,
parent_type,
global_class,
),
@@ -703,7 +708,7 @@ fn element_to_tokens(
cx,
Span::call_site(),
&fragment.children,
false,
true,
parent_type,
global_class,
),
@@ -1058,11 +1063,17 @@ fn is_self_closing(node: &NodeElement) -> bool {
fn camel_case_tag_name(tag_name: &str) -> String {
let mut chars = tag_name.chars();
let first = chars.next();
let underscore = if tag_name == "option" || tag_name == "use" {
"_"
} else {
""
};
first
.map(|f| f.to_ascii_uppercase())
.into_iter()
.chain(chars)
.collect()
.collect::<String>()
+ underscore
}
fn is_svg_element(tag: &str) -> bool {

View File

@@ -89,6 +89,30 @@ 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

@@ -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.11"
typed-builder = "0.12"
[dependencies.web-sys]
version = "0.3"

74
meta/src/body.rs Normal file
View File

@@ -0,0 +1,74 @@
use crate::TextProp;
use cfg_if::cfg_if;
use leptos::*;
use std::{cell::RefCell, rc::Rc};
/// Contains the current metadata for the document's `<body>`.
#[derive(Clone, Default)]
pub struct BodyContext {
class: Rc<RefCell<Option<TextProp>>>,
}
impl BodyContext {
/// Converts the `<body>` metadata into an HTML string.
pub fn as_string(&self) -> Option<String> {
self.class
.borrow()
.as_ref()
.map(|class| format!(" class=\"{}\"", class.get()))
}
}
impl std::fmt::Debug for BodyContext {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("TitleContext").finish()
}
}
/// A component to set metadata on the documents `<body>` element from
/// within the application.
///
/// ```
/// use leptos::*;
/// use leptos_meta::*;
///
/// #[component]
/// fn MyApp(cx: Scope) -> impl IntoView {
/// provide_meta_context(cx);
/// let (prefers_dark, set_prefers_dark) = create_signal(cx, false);
/// let body_class = move || if prefers_dark() {
/// "dark".to_string()
/// } else {
/// "light".to_string()
/// };
///
/// view! { cx,
/// <main>
/// <Body class=body_class/>
/// </main>
/// }
/// }
/// ```
#[component(transparent)]
pub fn Body(
cx: Scope,
/// The `class` attribute on the `<body>`.
#[prop(optional, into)]
class: Option<TextProp>,
) -> impl IntoView {
cfg_if! {
if #[cfg(any(feature = "csr", feature = "hydrate"))] {
let el = document().body().expect("there to be a <body> element");
if let Some(class) = class {
create_render_effect(cx, move |_| {
let value = class.get();
_ = el.set_attribute("class", &value);
});
}
} else {
let meta = crate::use_head(cx);
*meta.body.class.borrow_mut() = class;
}
}
}

85
meta/src/html.rs Normal file
View File

@@ -0,0 +1,85 @@
use crate::TextProp;
use cfg_if::cfg_if;
use leptos::*;
use std::{cell::RefCell, rc::Rc};
/// Contains the current metadata for the document's `<html>`.
#[derive(Clone, Default)]
pub struct HtmlContext {
lang: Rc<RefCell<Option<TextProp>>>,
dir: Rc<RefCell<Option<TextProp>>>,
}
impl HtmlContext {
/// 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,
(Some(lang), None) => Some(format!(" lang=\"{}\"", lang.get())),
(None, Some(dir)) => Some(format!(" dir=\"{}\"", dir.get())),
(Some(lang), Some(dir)) => {
Some(format!(" lang=\"{}\" dir=\"{}\"", lang.get(), dir.get()))
}
}
}
}
impl std::fmt::Debug for HtmlContext {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("TitleContext").finish()
}
}
/// A component to set metadata on the documents `<html>` element from
/// within the application.
///
/// ```
/// use leptos::*;
/// use leptos_meta::*;
///
/// #[component]
/// fn MyApp(cx: Scope) -> impl IntoView {
/// provide_meta_context(cx);
///
/// view! { cx,
/// <main>
/// <Html lang="he" dir="rtl"/>
/// </main>
/// }
/// }
/// ```
#[component(transparent)]
pub fn Html(
cx: Scope,
/// The `lang` attribute on the `<html>`.
#[prop(optional, into)]
lang: Option<TextProp>,
/// The `dir` attribute on the `<html>`.
#[prop(optional, into)]
dir: Option<TextProp>,
) -> impl IntoView {
cfg_if! {
if #[cfg(any(feature = "csr", feature = "hydrate"))] {
let el = document().document_element().expect("there to be a <html> element");
if let Some(lang) = lang {
let el = el.clone();
create_render_effect(cx, move |_| {
let value = lang.get();
_ = el.set_attribute("lang", &value);
});
}
if let Some(dir) = dir {
create_render_effect(cx, move |_| {
let value = dir.get();
_ = el.set_attribute("dir", &value);
});
}
} else {
let meta = crate::use_head(cx);
*meta.html.lang.borrow_mut() = lang;
*meta.html.dir.borrow_mut() = dir;
}
}
}

View File

@@ -55,12 +55,16 @@ use std::{
use leptos::{leptos_dom::debug_warn, *};
mod body;
mod html;
mod link;
mod meta_tags;
mod script;
mod style;
mod stylesheet;
mod title;
pub use body::*;
pub use html::*;
pub use link::*;
pub use meta_tags::*;
pub use script::*;
@@ -74,13 +78,19 @@ pub use title::*;
/// [provide_meta_context].
#[derive(Clone, Default, Debug)]
pub struct MetaContext {
pub(crate) title: TitleContext,
pub(crate) tags: MetaTagsContext,
/// Metadata associated with the `<html>` element
pub html: HtmlContext,
/// Metadata associated with the `<title>` element.
pub title: TitleContext,
/// Metadata associated with the `<body>` element
pub body: BodyContext,
/// Other metadata tags.
pub tags: MetaTagsContext,
}
/// Manages all of the element created by components.
#[derive(Clone, Default)]
pub(crate) struct MetaTagsContext {
pub struct MetaTagsContext {
next_id: Rc<Cell<MetaTagId>>,
#[allow(clippy::type_complexity)]
els: Rc<RefCell<HashMap<String, (HtmlElement<AnyElement>, Scope, Option<web_sys::Element>)>>>,
@@ -93,7 +103,8 @@ impl std::fmt::Debug for MetaTagsContext {
}
impl MetaTagsContext {
#[cfg(feature = "ssr")]
/// Converts metadata tags into an HTML string.
#[cfg(any(feature = "ssr", docs))]
pub fn as_string(&self) -> String {
self.els
.borrow()
@@ -102,6 +113,7 @@ impl MetaTagsContext {
.collect()
}
#[doc(hidden)]
pub fn register(&self, cx: Scope, id: String, builder_el: HtmlElement<AnyElement>) {
cfg_if! {
if #[cfg(any(feature = "csr", feature = "hydrate"))] {
@@ -209,7 +221,7 @@ impl MetaContext {
///
/// # #[cfg(not(any(feature = "csr", feature = "hydrate")))] {
/// run_scope(create_runtime(), |cx| {
/// provide_context(cx, MetaContext::new());
/// provide_meta_context(cx);
///
/// let app = view! { cx,
/// <main>

View File

@@ -55,7 +55,7 @@ where
///
/// #[component]
/// fn MyApp(cx: Scope) -> impl IntoView {
/// provide_context(cx, MetaContext::new());
/// provide_meta_context(cx);
/// let formatter = |text| format!("{text} — Leptos Online");
///
/// view! { cx,

View File

@@ -38,7 +38,7 @@ pub fn Form<A>(
#[allow(clippy::type_complexity)]
on_response: Option<Rc<dyn Fn(&web_sys::Response)>>,
/// Component children; should include the HTML of the form elements.
children: Box<dyn FnOnce(Scope) -> Fragment>,
children: Children,
) -> impl IntoView
where
A: ToHref + 'static,
@@ -136,7 +136,7 @@ pub fn ActionForm<I, O>(
/// manually using [leptos_server::Action::using_server_fn].
action: Action<I, Result<O, ServerFnError>>,
/// Component children; should include the HTML of the form elements.
children: Box<dyn FnOnce(Scope) -> Fragment>,
children: Children,
) -> impl IntoView
where
I: Clone + ServerFn + 'static,
@@ -210,7 +210,7 @@ pub fn MultiActionForm<I, O>(
/// manually using [leptos_server::Action::using_server_fn].
action: MultiAction<I, Result<O, ServerFnError>>,
/// Component children; should include the HTML of the form elements.
children: Box<dyn FnOnce(Scope) -> Fragment>,
children: Children,
) -> impl IntoView
where
I: Clone + ServerFn + 'static,

View File

@@ -65,7 +65,7 @@ pub fn A<H>(
#[prop(optional, into)]
class: Option<MaybeSignal<String>>,
/// The nodes or elements to be shown inside the link.
children: Box<dyn FnOnce(Scope) -> Fragment>,
children: Children,
) -> impl IntoView
where
H: ToHref + 'static,

View File

@@ -29,7 +29,7 @@ pub fn Route<E, F, P>(
view: F,
/// `children` may be empty or include nested routes.
#[prop(optional)]
children: Option<Box<dyn FnOnce(Scope) -> Fragment>>,
children: Option<Children>,
) -> impl IntoView
where
E: IntoView,

View File

@@ -32,7 +32,7 @@ pub fn Router(
/// The `<Router/>` should usually wrap your whole page. It can contain
/// any elements, and should include a [Routes](crate::Routes) component somewhere
/// to define and display [Route](crate::Route)s.
children: Box<dyn FnOnce(Scope) -> Fragment>,
children: Children,
) -> impl IntoView {
// create a new RouterContext and provide it to every component beneath the router
let router = RouterContext::new(cx, base, fallback);

View File

@@ -22,7 +22,7 @@ use crate::{
pub fn Routes(
cx: Scope,
#[prop(optional)] base: Option<String>,
children: Box<dyn FnOnce(Scope) -> Fragment>,
children: Children,
) -> impl IntoView {
let router = use_context::<RouterContext>(cx)
.expect("<Routes/> component should be nested within a <Router/>.");