Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Action form error handling when no JS/WASM #2110

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
afdc02f
Make ActionForm example to test with
SleeplessOne1917 Oct 28, 2023
e327879
Setup example
SleeplessOne1917 Oct 29, 2023
a209b0e
Tweak error in example
SleeplessOne1917 Oct 29, 2023
3f28223
Use local leptos as action form example dependency
SleeplessOne1917 Oct 31, 2023
708781f
Make actix redirect with error in url
SleeplessOne1917 Nov 2, 2023
bda91d9
Merge branch 'main' into action-form-error
SleeplessOne1917 Nov 19, 2023
3642184
Merge branch 'main' into action-form-error
Dec 4, 2023
12db042
Merge branch 'leptos-rs:main' into action-form-error
SleeplessOne1917 Dec 14, 2023
3fe47ce
Make ServerFn Serialization easier
Dec 14, 2023
ccd43ce
Formatting
Dec 15, 2023
562edb4
Merge branch 'main' into action-form-error
Dec 15, 2023
74cd77f
Merge branch 'main' into action-form-error
Dec 21, 2023
2cb5877
Implement serverfnerr encoding for axum integration and refactor
Dec 22, 2023
be3504e
Implement serverfn encoding for viz
Dec 23, 2023
109d13d
Merge branch 'main' into action-form-error
Dec 24, 2023
3b2e898
Merge branch 'main' into action-form-error
Jan 2, 2024
554a593
Uniquely identify serverfn errors in URL
Jan 6, 2024
3794207
Uniquely identify serverfn errors in URL
Jan 6, 2024
ed389bf
Merge branch 'action-form-error' of https://github.com/SleeplessOne19…
Jan 6, 2024
a3c8fe8
Make error gettable by server rendered action form
Jan 9, 2024
15cb078
Make error gettable by server rendered action form
Jan 9, 2024
2dbff24
Merge branch 'action-form-error' of https://github.com/SleeplessOne19…
Jan 9, 2024
463f778
Rearrange query string errors logic
Jan 11, 2024
a4f2ac5
Merge branch 'main' into action-form-error
Jan 12, 2024
5b056a7
Add a way to detect if server fn is coming from a client with wasm di…
Jan 12, 2024
1472aaa
Work on handling server fns
Jan 13, 2024
7d1583a
Make server fn responses work on both success and failure
Jan 13, 2024
487b356
Uncomment iso effect
Jan 13, 2024
90f5dac
Revert "Uncomment iso effect"
Jan 13, 2024
d4f7fd8
Revert "Make server fn responses work on both success and failure"
Jan 13, 2024
c00a696
Revert "Work on handling server fns"
Jan 13, 2024
29df4a5
Go further
Jan 14, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions examples/Makefile.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ CARGO_MAKE_EXTEND_WORKSPACE_MAKEFILE = true
CARGO_MAKE_CARGO_BUILD_TEST_FLAGS = ""
CARGO_MAKE_WORKSPACE_EMULATION = true
CARGO_MAKE_CRATE_WORKSPACE_MEMBERS = [
"action_form_error_handling",
"animated_show",
"counter",
"counter_isomorphic",
Expand Down
90 changes: 90 additions & 0 deletions examples/action-form-error-handling/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
[package]
name = "action-form-error-handling"
version = "0.1.0"
edition = "2021"

[lib]
crate-type = ["cdylib", "rlib"]

[dependencies]
actix-files = { version = "0.6", optional = true }
actix-web = { version = "4", optional = true, features = ["macros"] }
console_error_panic_hook = "0.1"
cfg-if = "1"
http = { version = "0.2", optional = true }
leptos = { path = "../../leptos" }
leptos_meta = { path = "../../meta" }
leptos_actix = { path = "../../integrations/actix", optional = true }
leptos_router = { path = "../../router" }
wasm-bindgen = "0.2"
serde = { version = "1", features = ["derive"] }

[features]
csr = ["leptos/csr", "leptos_meta/csr", "leptos_router/csr"]
hydrate = ["leptos/hydrate", "leptos_meta/hydrate", "leptos_router/hydrate"]
ssr = [
"dep:actix-files",
"dep:actix-web",
"dep:leptos_actix",
"leptos/ssr",
"leptos_meta/ssr",
"leptos_router/ssr",
]

# Defines a size-optimized profile for the WASM bundle in release mode
[profile.wasm-release]
inherits = "release"
opt-level = 'z'
lto = true
codegen-units = 1
panic = "abort"

[package.metadata.leptos]
# The name used by wasm-bindgen/cargo-leptos for the JS/WASM bundle. Defaults to the crate name
output-name = "leptos_start"
# The site root folder is where cargo-leptos generate all output. WARNING: all content of this folder will be erased on a rebuild. Use it in your server setup.
site-root = "target/site"
# The site-root relative folder where all compiled output (JS, WASM and CSS) is written
# Defaults to pkg
site-pkg-dir = "pkg"
# [Optional] The source CSS file. If it ends with .sass or .scss then it will be compiled by dart-sass into CSS. The CSS is optimized by Lightning CSS before being written to <site-root>/<site-pkg>/app.css
style-file = "style/main.scss"
# The IP and port (ex: 127.0.0.1:3000) where the server serves the content. Use it in your server setup.
site-addr = "127.0.0.1:3000"
# The port to use for automatic reload monitoring
reload-port = 3001
# [Optional] Command to use when running end2end tests. It will run in the end2end dir.
# [Windows] for non-WSL use "npx.cmd playwright test"
# This binary name can be checked in Powershell with Get-Command npx
end2end-cmd = "npx playwright test"
end2end-dir = "end2end"
# The browserlist query used for optimizing the CSS.
browserquery = "defaults"
# Set by cargo-leptos watch when building with that 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

# The profile to use for the lib target when compiling for release
#
# Optional. Defaults to "release".
lib-profile-release = "wasm-release"
8 changes: 8 additions & 0 deletions examples/action-form-error-handling/Makefile.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
extend = [
{ path = "../cargo-make/main.toml" },
{ path = "../cargo-make/cargo-leptos.toml" },
]

[env]

CLIENT_PROCESS_NAME = "action_form_error_handling"
68 changes: 68 additions & 0 deletions examples/action-form-error-handling/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
<picture>
<source srcset="https://raw.githubusercontent.com/leptos-rs/leptos/main/docs/logos/Leptos_logo_Solid_White.svg" media="(prefers-color-scheme: dark)">
<img src="https://raw.githubusercontent.com/leptos-rs/leptos/main/docs/logos/Leptos_logo_RGB.svg" alt="Leptos Logo">
</picture>

# Leptos Starter Template

This is a template for use with the [Leptos](https://github.com/leptos-rs/leptos) web framework and the [cargo-leptos](https://github.com/akesson/cargo-leptos) tool.

## Creating your template repo

If you don't have `cargo-leptos` installed you can install it with

`cargo install cargo-leptos`

Then run

`cargo leptos new --git leptos-rs/start`

to generate a new project template (you will be prompted to enter a project name).

`cd {projectname}`

to go to your newly created project.

Of course, you should explore around the project structure, but the best place to start with your application code is in `src/app.rs`.

## Running your project

`cargo leptos watch`
By default, you can access your local project at `http://localhost:3000`

## Installing Additional Tools

By default, `cargo-leptos` uses `nightly` Rust, `cargo-generate`, and `sass`. If you run into any trouble, you may need to install one or more of these tools.

1. `rustup toolchain install nightly --allow-downgrade` - make sure you have Rust nightly
2. `rustup target add wasm32-unknown-unknown` - add the ability to compile Rust to WebAssembly
3. `cargo install cargo-generate` - install `cargo-generate` binary (should be installed automatically in future)
4. `npm install -g sass` - install `dart-sass` (should be optional in future)

## Executing a Server on a Remote Machine Without the Toolchain
After running a `cargo leptos build --release` the minimum files needed are:

1. The server binary located in `target/server/release`
2. The `site` directory and all files within located in `target/site`

Copy these files to your remote server. The directory structure should be:
```text
leptos_start
site/
```
Set the following environment variables (updating for your project as needed):
```sh
export LEPTOS_OUTPUT_NAME="leptos_start"
export LEPTOS_SITE_ROOT="site"
export LEPTOS_SITE_PKG_DIR="pkg"
export LEPTOS_SITE_ADDR="127.0.0.1:3000"
export LEPTOS_RELOAD_PORT="3001"
```
Finally, run the server binary.

## Notes about CSR and Trunk:
Although it is not recommended, you can also run your project without server integration using the feature `csr` and `trunk serve`:

`trunk serve --open --features csr`

This may be useful for integrating external tools which require a static site, e.g. `tauri`.
90 changes: 90 additions & 0 deletions examples/action-form-error-handling/src/app.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
use leptos::*;
use leptos_meta::*;
use leptos_router::*;

#[component]
pub fn App() -> impl IntoView {
// Provides context that manages stylesheets, titles, meta tags, etc.
provide_meta_context();

view! {
// injects a stylesheet into the document <head>
// id=leptos means cargo-leptos will hot-reload this stylesheet
<Stylesheet id="leptos" href="/pkg/leptos_start.css"/>

// sets the document title
<Title text="Welcome to Leptos"/>

// content for this welcome page
<Router>
<main id="app">
<Routes>
<Route path="" view=HomePage/>
<Route path="/*any" view=NotFound/>
</Routes>
</main>
</Router>
}
}

#[server]
async fn do_something(should_error: Option<String>) -> Result<String, ServerFnError> {
if should_error.is_none() {
Ok(String::from("Successful submit"))
} else {
Err(ServerFnError::ServerError(String::from(
"You got an error!",
)))
}
}

/// Renders the home page of your application.
#[component]
fn HomePage() -> impl IntoView {
let do_something_action = Action::<DoSomething, _>::server();
let value = Signal::derive(move || do_something_action.value().get().unwrap_or_else(|| Ok(String::new())));

Effect::new_isomorphic(move |_| {
logging::log!("Got value = {:?}", value.get());
});

view! {
<h1>"Test the action form!"</h1>
<ErrorBoundary fallback=move |error| format!("{:#?}", error
.get()
.into_iter()
.next()
.unwrap()
.1.into_inner()
.to_string())
>
{value}
</ErrorBoundary>
<ActionForm action=do_something_action class="form">
<label>Should error: <input type="checkbox" name="should_error"/></label>
<button type="submit">Submit</button>
</ActionForm>
}
}

/// 404 - Not Found
#[component]
fn NotFound() -> impl IntoView {
// set an HTTP status code 404
// this is feature gated because it can only be done during
// initial server-side rendering
// if you navigate to the 404 page subsequently, the status
// code will not be set because there is not a new HTTP request
// to the server
#[cfg(feature = "ssr")]
{
// this can be done inline because it's synchronous
// if it were async, we'd use a server function
let resp = expect_context::<leptos_actix::ResponseOptions>();
resp.set_status(actix_web::http::StatusCode::NOT_FOUND);
}

view! {
<h1>"Not Found"</h1>
}
}
18 changes: 18 additions & 0 deletions examples/action-form-error-handling/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
pub mod app;
use cfg_if::cfg_if;

cfg_if! {
if #[cfg(feature = "hydrate")] {

use wasm_bindgen::prelude::wasm_bindgen;

#[wasm_bindgen]
pub fn hydrate() {
use app::*;

console_error_panic_hook::set_once();

leptos::mount_to_body(App);
}
}
}
53 changes: 53 additions & 0 deletions examples/action-form-error-handling/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
#[cfg(feature = "ssr")]
#[actix_web::main]
async fn main() -> std::io::Result<()> {
use actix_files::Files;
use actix_web::*;
use leptos::*;
use leptos_actix::{generate_route_list, LeptosRoutes};
use action_form_error_handling::app::*;

let conf = get_configuration(None).await.unwrap();
let addr = conf.leptos_options.site_addr;
// Generate the list of routes in your Leptos App
let routes = generate_route_list(App);
println!("listening on http://{}", &addr);

HttpServer::new(move || {
let leptos_options = &conf.leptos_options;
let site_root = &leptos_options.site_root;

App::new()
.route("/api/{tail:.*}", leptos_actix::handle_server_fns())
// serve JS/WASM/CSS from `pkg`
.service(Files::new("/pkg", format!("{site_root}/pkg")))
.leptos_routes(leptos_options.to_owned(), routes.to_owned(), App)
.app_data(web::Data::new(leptos_options.to_owned()))
//.wrap(middleware::Compress::default())
})
.bind(&addr)?
.run()
.await
}

#[cfg(not(any(feature = "ssr", feature = "csr")))]
pub fn main() {
// no client-side main function
// unless we want this to work with e.g., Trunk for pure client-side testing
// see lib.rs for hydration function instead
// see optional feature `csr` instead
}

#[cfg(all(not(feature = "ssr"), feature = "csr"))]
pub fn main() {
// a client-side main function is required for using `trunk serve`
// prefer using `cargo leptos serve` instead
// to run: `trunk serve --open --features csr`
use leptos::*;
use action_form_error_handling::app::*;
use wasm_bindgen::prelude::wasm_bindgen;

console_error_panic_hook::set_once();

leptos::mount_to_body(App);
}
15 changes: 15 additions & 0 deletions examples/action-form-error-handling/style/main.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
body {
font-family: sans-serif;
text-align: center;
}

#app {
text-align: center;
}

.form {
display: flex;
flex-direction: column;
align-items: center;
gap: 0.5rem;
}
Loading