Merge pull request #269 from benwis/generated_routes

Generate Routes and pass them to Actix/Axum
This commit is contained in:
Greg Johnston 2023-01-09 07:02:11 -05:00 committed by GitHub
commit 8b92a561a3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
24 changed files with 439 additions and 167 deletions

View File

@ -9,6 +9,7 @@ cfg_if! {
use actix_files::{Files};
use actix_web::*;
use crate::counters::*;
use leptos_actix::{generate_route_list, LeptosRoutes};
#[get("/api/events")]
async fn counter_events() -> impl Responder {
@ -29,23 +30,23 @@ cfg_if! {
#[actix_web::main]
async fn main() -> std::io::Result<()> {
crate::counters::register_server_functions();
let conf = get_configuration(Some("Cargo.toml")).await.unwrap();
let leptos_options = &conf.leptos_options;
let site_root = &leptos_options.site_root;
let pkg_dir = &leptos_options.site_pkg_dir;
let bundle_path = format!("/{site_root}/{pkg_dir}");
let addr = conf.leptos_options.site_address.clone();
let routes = generate_route_list(|cx| view! { cx, <Counters/> });
HttpServer::new(move || {
let leptos_options = &conf.leptos_options;
let site_root = &leptos_options.site_root;
App::new()
.service(Files::new("/pkg", "./pkg")) // used by wasm-pack and cargo run. Can be removed if using cargo-leptos
.service(Files::new(&bundle_path, format!("./{bundle_path}"))) // used by cargo-leptos. Can be removed if using wasm-pack and cargo run.
.service(counter_events)
.route("/api/{tail:.*}", leptos_actix::handle_server_fns())
.route("/{tail:.*}", leptos_actix::render_app_to_stream(leptos_options.to_owned(), |cx| view! { cx, <Counters/> }))
//.wrap(middleware::Compress::default())
.leptos_routes(leptos_options.to_owned(), routes.to_owned(), |cx| view! { cx, <Counters/> })
.service(Files::new("/", &site_root))
//.wrap(middleware::Compress::default())
})
.bind(&addr)?
.run()

View File

@ -15,7 +15,7 @@ pub fn App(cx: Scope) -> impl IntoView {
view! {
cx,
<>
<Stylesheet id="leptos" href="/target/site/pkg/hackernews.css"/>
<Stylesheet id="leptos" href="/pkg/hackernews.css"/>
<Meta name="description" content="Leptos implementation of a HackerNews demo."/>
<Router>
<Nav />
@ -23,7 +23,7 @@ pub fn App(cx: Scope) -> impl IntoView {
<Routes>
<Route path="users/:id" view=|cx| view! { cx, <User/> }/>
<Route path="stories/:id" view=|cx| view! { cx, <Story/> }/>
<Route path="*stories" view=|cx| view! { cx, <Stories/> }/>
<Route path=":stories?" view=|cx| view! { cx, <Stories/> }/>
</Routes>
</main>
</Router>

View File

@ -8,6 +8,7 @@ cfg_if! {
use actix_files::{Files};
use actix_web::*;
use hackernews::{App,AppProps};
use leptos_actix::{LeptosRoutes, generate_route_list};
#[get("/style.css")]
async fn css() -> impl Responder {
@ -18,18 +19,18 @@ cfg_if! {
async fn main() -> std::io::Result<()> {
let conf = get_configuration(Some("Cargo.toml")).await.unwrap();
let addr = conf.leptos_options.site_address.clone();
// Generate the list of routes in your Leptos App
let routes = generate_route_list(|cx| view! { cx, <App/> });
HttpServer::new(move || {
let leptos_options = &conf.leptos_options;
let site_root = &leptos_options.site_root;
let pkg_dir = &leptos_options.site_pkg_dir;
let bundle_path = format!("/{site_root}/{pkg_dir}");
App::new()
.service(Files::new("/pkg", "./pkg")) // used by wasm-pack and cargo run. Can be removed if using cargo-leptos
.service(Files::new(&bundle_path, format!("./{bundle_path}"))) // used by cargo-leptos. Can be removed if using wasm-pack and cargo run.
.service(css)
.route("/api/{tail:.*}", leptos_actix::handle_server_fns())
.route("/{tail:.*}", leptos_actix::render_app_to_stream(leptos_options.to_owned(), |cx| view! { cx, <App/> }))
.leptos_routes(leptos_options.to_owned(), routes.to_owned(), |cx| view! { cx, <App/> })
.service(Files::new("/", &site_root))
//.wrap(middleware::Compress::default())
})
.bind(&addr)?

View File

@ -0,0 +1,41 @@
use cfg_if::cfg_if;
cfg_if! {
if #[cfg(feature = "ssr")] {
use axum::{
body::{boxed, Body, BoxBody},
extract::Extension,
http::{Request, Response, StatusCode, Uri},
};
use tower::ServiceExt;
use tower_http::services::ServeDir;
use std::sync::Arc;
use leptos::LeptosOptions;
pub async fn file_handler(uri: Uri, Extension(options): Extension<Arc<LeptosOptions>>) -> Result<Response<BoxBody>, (StatusCode, String)> {
let options = &*options;
let root = options.site_root.clone();
let res = get_static_file(uri.clone(), &root).await?;
match res.status() {
StatusCode::OK => Ok(res),
_ => Err((res.status(), "File Not Found".to_string()))
}
}
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_path).oneshot(req).await {
Ok(res) => Ok(res.map(boxed)),
Err(err) => Err((
StatusCode::INTERNAL_SERVER_ERROR,
format!("Something went wrong: {}", err),
)),
}
}
}
}

View File

@ -3,6 +3,7 @@ use leptos::{component, view, IntoView, Scope};
use leptos_meta::*;
use leptos_router::*;
mod api;
pub mod file;
pub mod handlers;
mod routes;
use routes::nav::*;
@ -16,7 +17,7 @@ pub fn App(cx: Scope) -> impl IntoView {
view! {
cx,
<>
<Stylesheet id="leptos" href="./target/site/pkg/hackernews_axum.css"/>
<Stylesheet id="leptos" href="/pkg/hackernews_axum.css"/>
<Meta name="description" content="Leptos implementation of a HackerNews demo."/>
<Router>
<Nav />
@ -24,7 +25,7 @@ pub fn App(cx: Scope) -> impl IntoView {
<Routes>
<Route path="users/:id" view=|cx| view! { cx, <User/> }/>
<Route path="stories/:id" view=|cx| view! { cx, <Story/> }/>
<Route path="*stories" view=|cx| view! { cx, <Stories/> }/>
<Route path=":stories?" view=|cx| view! { cx, <Stories/> }/>
</Routes>
</main>
</Router>

View File

@ -6,10 +6,11 @@ cfg_if! {
if #[cfg(feature = "ssr")] {
use axum::{
Router,
error_handling::HandleError,
extract::Extension,
};
use http::StatusCode;
use tower_http::services::ServeDir;
use leptos_axum::{generate_route_list, LeptosRoutes};
use std::sync::Arc;
use hackernews_axum::file::file_handler;
#[tokio::main]
async fn main() {
@ -17,40 +18,16 @@ if #[cfg(feature = "ssr")] {
let conf = get_configuration(Some("Cargo.toml")).await.unwrap();
let leptos_options = conf.leptos_options;
let site_root = &leptos_options.site_root;
let pkg_dir = &leptos_options.site_pkg_dir;
// The URL path of the generated JS/WASM bundle from cargo-leptos
let bundle_path = format!("/{site_root}/{pkg_dir}");
// The filesystem path of the generated JS/WASM bundle from cargo-leptos
let bundle_filepath = format!("./{site_root}/{pkg_dir}");
let addr = leptos_options.site_address.clone();
log::debug!("serving at {addr}");
let routes = generate_route_list(|cx| view! { cx, <App/> }).await;
simple_logger::init_with_level(log::Level::Debug).expect("couldn't initialize logging");
// These are Tower Services that will serve files from the static and pkg repos.
// HandleError is needed as Axum requires services to implement Infallible Errors
// because all Errors are converted into Responses
let static_service = HandleError::new( ServeDir::new("./static"), handle_file_error);
let pkg_service =HandleError::new( ServeDir::new("./pkg"), handle_file_error);
let cargo_leptos_service = HandleError::new( ServeDir::new(&bundle_filepath), handle_file_error);
/// Convert the Errors from ServeDir to a type that implements IntoResponse
async fn handle_file_error(err: std::io::Error) -> (StatusCode, String) {
(
StatusCode::NOT_FOUND,
format!("File Not Found: {}", err),
)
}
// build our application with a route
let app = Router::new()
// `GET /` goes to `root`
.nest_service("/pkg", pkg_service) // Only need if using wasm-pack. Can be deleted if using cargo-leptos
.nest_service(&bundle_path, cargo_leptos_service) // Only needed if using cargo-leptos. Can be deleted if using wasm-pack and cargo-run
.nest_service("/static", static_service)
.fallback(leptos_axum::render_app_to_stream(leptos_options, |cx| view! { cx, <App/> }));
.leptos_routes(leptos_options.clone(), routes, |cx| view! { cx, <App/> } )
.fallback(file_handler)
.layer(Extension(Arc::new(leptos_options)));
// run our app with hyper
// `axum::Server` is a re-export of `hyper::Server`

View File

@ -87,7 +87,7 @@ site-root = "target/site"
# 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 = "src/styles/tailwind.css"
style-file = "style/output.css"
# [Optional] Files in the asset-dir will be copied to the site-root directory
assets-dir = "assets"
# The IP and port (ex: 127.0.0.1:3000) where the server serves the content. Use it in your server setup.

View File

@ -1,28 +1,36 @@
use leptos::*;
use leptos_meta::*;
use leptos_router::*;
#[component]
pub fn App(cx: Scope) -> impl IntoView {
provide_meta_context(cx);
let (count, set_count) = create_signal(cx, 0);
view! {
cx,
<main class="my-0 mx-auto max-w-3xl text-center">
<Stylesheet id="leptos" href="/style.css"/>
<h2 class="p-6 text-4xl">"Welcome to Leptos with Tailwind"</h2>
<p class="px-10 pb-10 text-left">"Tailwind will scan your Rust files for Tailwind class names and compile them into a CSS file."</p>
<button
class="bg-sky-600 hover:bg-sky-700 px-5 py-3 text-white rounded-lg"
on:click=move |_| set_count.update(|count| *count += 1)
>
{move || if count() == 0 {
"Click me!".to_string()
} else {
count().to_string()
}}
</button>
</main>
<Stylesheet id="leptos" href="/pkg/tailwind.css"/>
<Router>
<Routes>
<Route path="" view= move |cx| view! {
cx,
<main class="my-0 mx-auto max-w-3xl text-center">
<h2 class="p-6 text-4xl">"Welcome to Leptos with Tailwind"</h2>
<p class="px-10 pb-10 text-left">"Tailwind will scan your Rust files for Tailwind class names and compile them into a CSS file."</p>
<button
class="bg-sky-600 hover:bg-sky-700 px-5 py-3 text-white rounded-lg"
on:click=move |_| set_count.update(|count| *count += 1)
>
{move || if count() == 0 {
"Click me!".to_string()
} else {
count().to_string()
}}
</button>
</main>
}/>
</Routes>
</Router>
}
}

View File

@ -7,6 +7,7 @@ cfg_if! {
use actix_web::*;
use leptos::*;
use crate::app::*;
use leptos_actix::{generate_route_list, LeptosRoutes};
#[get("/style.css")]
async fn css() -> impl Responder {
@ -15,20 +16,21 @@ cfg_if! {
#[actix_web::main]
async fn main() -> std::io::Result<()> {
let conf = get_configuration(Some("Cargo.toml")).await.unwrap();
let addr = conf.leptos_options.site_address.clone();
let leptos_options = &conf.leptos_options;
let site_root = &leptos_options.site_root;
let pkg_dir = &leptos_options.site_pkg_dir;
let bundle_path = format!("/{site_root}/{pkg_dir}");
// Generate the list of routes in your Leptos App
let routes = generate_route_list(|cx| view! { cx, <App/> });
HttpServer::new(move || {
let leptos_options = &conf.leptos_options;
let site_root = &leptos_options.site_root;
let routes = &routes;
App::new()
.service(css)
.service(Files::new("/pkg", "./pkg")) // used by wasm-pack and cargo run. Can be removed if using cargo-leptos
.service(Files::new(&bundle_path, format!("./{bundle_path}"))) // used by cargo-leptos. Can be removed if using wasm-pack and cargo run.
.route("/{tail:.*}", leptos_actix::render_app_to_stream(leptos_options.to_owned(), |cx| view! { cx, <App/> }))
.leptos_routes(leptos_options.to_owned(), routes.to_owned(), |cx| view! { cx, <App/> })
.service(Files::new("/", &site_root))
.wrap(middleware::Compress::default())
})
.bind(&addr)?

View File

@ -1,5 +1,5 @@
/*
! tailwindcss v3.2.4 | MIT License | https://tailwindcss.com
! tailwindcss v3.1.8 | MIT License | https://tailwindcss.com
*/
/*
@ -30,7 +30,6 @@
2. Prevent adjustments of font size after orientation changes in iOS.
3. Use a more readable tab size.
4. Use the user's configured `sans` font-family by default.
5. Use the user's configured `sans` font-feature-settings by default.
*/
html {
@ -45,8 +44,6 @@ html {
/* 3 */
font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
/* 4 */
font-feature-settings: normal;
/* 5 */
}
/*
@ -413,13 +410,54 @@ video {
height: auto;
}
/* Make elements with the HTML hidden attribute stay hidden by default */
[hidden] {
display: none;
*, ::before, ::after {
--tw-border-spacing-x: 0;
--tw-border-spacing-y: 0;
--tw-translate-x: 0;
--tw-translate-y: 0;
--tw-rotate: 0;
--tw-skew-x: 0;
--tw-skew-y: 0;
--tw-scale-x: 1;
--tw-scale-y: 1;
--tw-pan-x: ;
--tw-pan-y: ;
--tw-pinch-zoom: ;
--tw-scroll-snap-strictness: proximity;
--tw-ordinal: ;
--tw-slashed-zero: ;
--tw-numeric-figure: ;
--tw-numeric-spacing: ;
--tw-numeric-fraction: ;
--tw-ring-inset: ;
--tw-ring-offset-width: 0px;
--tw-ring-offset-color: #fff;
--tw-ring-color: rgb(59 130 246 / 0.5);
--tw-ring-offset-shadow: 0 0 #0000;
--tw-ring-shadow: 0 0 #0000;
--tw-shadow: 0 0 #0000;
--tw-shadow-colored: 0 0 #0000;
--tw-blur: ;
--tw-brightness: ;
--tw-contrast: ;
--tw-grayscale: ;
--tw-hue-rotate: ;
--tw-invert: ;
--tw-saturate: ;
--tw-sepia: ;
--tw-drop-shadow: ;
--tw-backdrop-blur: ;
--tw-backdrop-brightness: ;
--tw-backdrop-contrast: ;
--tw-backdrop-grayscale: ;
--tw-backdrop-hue-rotate: ;
--tw-backdrop-invert: ;
--tw-backdrop-opacity: ;
--tw-backdrop-saturate: ;
--tw-backdrop-sepia: ;
}
*, ::before, ::after {
::-webkit-backdrop {
--tw-border-spacing-x: 0;
--tw-border-spacing-y: 0;
--tw-translate-x: 0;

View File

@ -9,6 +9,7 @@ cfg_if! {
use actix_files::{Files};
use actix_web::*;
use crate::todo::*;
use leptos_actix::{generate_route_list, LeptosRoutes};
#[get("/style.css")]
async fn css() -> impl Responder {
@ -25,23 +26,23 @@ cfg_if! {
crate::todo::register_server_functions();
let conf = get_configuration(Some("Cargo.toml")).await.unwrap();
let addr = conf.leptos_options.site_address.clone();
// Generate the list of routes in your Leptos App
let routes = generate_route_list(|cx| view! { cx, <TodoApp/> });
HttpServer::new(move || {
let leptos_options = &conf.leptos_options;
let site_root = &leptos_options.site_root;
let pkg_dir = &leptos_options.site_pkg_dir;
let bundle_path = format!("/{site_root}/{pkg_dir}");
let routes = &routes;
App::new()
.service(Files::new("/pkg", "./pkg")) // used by wasm-pack and cargo run. Can be removed if using cargo-leptos
.service(Files::new(&bundle_path, format!("./{bundle_path}"))) // used by cargo-leptos. Can be removed if using wasm-pack and cargo run.
.service(css)
.route("/api/{tail:.*}", leptos_actix::handle_server_fns())
.route("/{tail:.*}", leptos_actix::render_app_to_stream(leptos_options.to_owned(), |cx| view! { cx, <TodoApp/> }))
//.wrap(middleware::Compress::default())
.leptos_routes(leptos_options.to_owned(), routes.to_owned(), |cx| view! { cx, <TodoApp/> })
.service(Files::new("/", &site_root))
//.wrap(middleware::Compress::default())
})
.bind(addr)?
.run()

View File

@ -38,9 +38,11 @@ cfg_if! {
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
let req =
use_context::<actix_web::HttpRequest>(cx).expect("couldn't get HttpRequest from context");
println!("req.path = {:?}", req.path());
use_context::<actix_web::HttpRequest>(cx);
if let Some(req) = req{
println!("req.path = {:#?}", req.path());
}
use futures::TryStreamExt;
let mut conn = db().await?;
@ -90,9 +92,10 @@ pub async fn delete_todo(id: u16) -> Result<(), ServerFnError> {
#[component]
pub fn TodoApp(cx: Scope) -> impl IntoView {
provide_meta_context(cx);
view! {
cx,
<Stylesheet id="leptos" href="./target/site/pkg/todo_app_sqlite.css"/>
<Stylesheet id="leptos" href="/pkg/todo_app_sqlite.css"/>
<Router>
<header>
<h1>"My Tasks"</h1>

View File

@ -0,0 +1,41 @@
use cfg_if::cfg_if;
cfg_if! {
if #[cfg(feature = "ssr")] {
use axum::{
body::{boxed, Body, BoxBody},
extract::Extension,
http::{Request, Response, StatusCode, Uri},
};
use tower::ServiceExt;
use tower_http::services::ServeDir;
use std::sync::Arc;
use leptos::LeptosOptions;
pub async fn file_handler(uri: Uri, Extension(options): Extension<Arc<LeptosOptions>>) -> Result<Response<BoxBody>, (StatusCode, String)> {
let options = &*options;
let root = options.site_root.clone();
let res = get_static_file(uri.clone(), &root).await?;
match res.status() {
StatusCode::OK => Ok(res),
_ => Err((res.status(), "File Not Found".to_string()))
}
}
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_path).oneshot(req).await {
Ok(res) => Ok(res.map(boxed)),
Err(err) => Err((
StatusCode::INTERNAL_SERVER_ERROR,
format!("Something went wrong: {}", err),
)),
}
}
}
}

View File

@ -1,5 +1,6 @@
use cfg_if::cfg_if;
use leptos::*;
pub mod file;
pub mod todo;
// Needs to be in lib.rs AFAIK because wasm-bindgen needs us to be compiling a lib. I may be wrong.

View File

@ -1,24 +1,24 @@
use cfg_if::cfg_if;
use leptos::*;
// boilerplate to run in different modes
cfg_if! {
if #[cfg(feature = "ssr")] {
use axum::{
routing::{post},
error_handling::HandleError,
routing::post,
extract::Extension,
Router,
};
use crate::todo::*;
use todo_app_sqlite_axum::*;
use http::StatusCode;
use tower_http::services::ServeDir;
use crate::file::file_handler;
use leptos_axum::{generate_route_list, LeptosRoutes};
use std::sync::Arc;
#[tokio::main]
async fn main() {
simple_logger::init_with_level(log::Level::Debug).expect("couldn't initialize logging");
let mut conn = db().await.expect("couldn't connect to DB");
let conn = db().await.expect("couldn't connect to DB");
/* sqlx::migrate!()
.run(&mut conn)
.await
@ -28,38 +28,15 @@ if #[cfg(feature = "ssr")] {
let conf = get_configuration(Some("Cargo.toml")).await.unwrap();
let leptos_options = conf.leptos_options;
let site_root = &leptos_options.site_root;
let pkg_dir = &leptos_options.site_pkg_dir;
// The URL path of the generated JS/WASM bundle from cargo-leptos
let bundle_path = format!("/{site_root}/{pkg_dir}");
// The filesystem path of the generated JS/WASM bundle from cargo-leptos
let bundle_filepath = format!("./{site_root}/{pkg_dir}");
let addr = leptos_options.site_address.clone();
log::debug!("serving at {addr}");
// These are Tower Services that will serve files from the static and pkg repos.
// HandleError is needed as Axum requires services to implement Infallible Errors
// because all Errors are converted into Responses
let static_service = HandleError::new( ServeDir::new("./static"), handle_file_error);
let pkg_service = HandleError::new( ServeDir::new("./pkg"), handle_file_error);
let cargo_leptos_service = HandleError::new( ServeDir::new(&bundle_filepath), handle_file_error);
/// Convert the Errors from ServeDir to a type that implements IntoResponse
async fn handle_file_error(err: std::io::Error) -> (StatusCode, String) {
(
StatusCode::NOT_FOUND,
format!("File Not Found: {}", err),
)
}
let routes = generate_route_list(|cx| view! { cx, <TodoApp/> }).await;
// build our application with a route
let app = Router::new()
.route("/api/*fn_name", post(leptos_axum::handle_server_fns))
.nest_service("/pkg", pkg_service) // Only need if using wasm-pack. Can be deleted if using cargo-leptos
.nest_service(&bundle_path, cargo_leptos_service) // Only needed if using cargo-leptos. Can be deleted if using wasm-pack and cargo-run
.nest_service("/static", static_service)
.fallback(leptos_axum::render_app_to_stream(leptos_options, |cx| view! { cx, <TodoApp/> }));
.leptos_routes(leptos_options.clone(), routes, |cx| view! { cx, <TodoApp/> } )
.fallback(file_handler)
.layer(Extension(Arc::new(leptos_options)));
// run our app with hyper
// `axum::Server` is a re-export of `hyper::Server`

View File

@ -39,9 +39,11 @@ cfg_if! {
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).unwrap();
println!("\ncalling server fn");
let req_parts = use_context::<leptos_axum::RequestParts>(cx);
if let Some(req_parts) = req_parts{
println!("Uri = {:?}", req_parts.uri);
}
use futures::TryStreamExt;
@ -105,9 +107,10 @@ pub async fn delete_todo(id: u16) -> Result<(), ServerFnError> {
#[component]
pub fn TodoApp(cx: Scope) -> impl IntoView {
provide_meta_context(cx);
view! {
cx,
<Stylesheet id="leptos" href="./target/site/pkg/todo_app_sqlite_axum.css"/>
<Stylesheet id="leptos" href="./pkg/todo_app_sqlite_axum.css"/>
<Router>
<header>
<h1>"My Tasks"</h1>

View File

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

View File

@ -1,12 +1,12 @@
use actix_web::{http::header, web::Bytes, *};
use futures::{StreamExt};
use actix_web::{http::header, web::Bytes, dev::{ServiceFactory, ServiceRequest}, *};
use futures::StreamExt;
use http::StatusCode;
use leptos::*;
use leptos_meta::*;
use leptos_router::*;
use std::sync::Arc;
use tokio::sync::RwLock;
use regex::Regex;
/// 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.
@ -267,8 +267,6 @@ where IV: IntoView
}
};
let site_root = &options.site_root;
// 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 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
@ -279,20 +277,10 @@ where IV: IntoView
wasm_output_name.push_str("_bg");
}
let site_ip = &options.site_address.ip().to_string();
let reload_port = options.reload_port;
let site_root = &options.site_root;
let pkg_path = &options.site_pkg_dir;
// We need to do some logic to check if the site_root is pkg
// if it is, then we need to not add pkg_path. This would mean
// the site was built with cargo run and not cargo-leptos
let bundle_path = match site_root.as_ref() {
"pkg" => "pkg".to_string(),
_ => format!("{site_root}/{pkg_path}"),
};
let leptos_autoreload = match std::env::var("LEPTOS_WATCH").is_ok() {
true => format!(
r#"
@ -326,9 +314,9 @@ where IV: IntoView
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<link rel="modulepreload" href="/{bundle_path}/{output_name}.js">
<link rel="preload" href="/{bundle_path}/{wasm_output_name}.wasm" as="fetch" type="application/wasm" crossorigin="">
<script type="module">import init, {{ hydrate }} from '/{bundle_path}/{output_name}.js'; init('/{bundle_path}/{wasm_output_name}.wasm').then(hydrate);</script>
<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}
"#
);
@ -382,3 +370,70 @@ where IV: IntoView
}
})
}
/// Generates a list of all routes defined in Leptos's Router in your app. We can then use this to automatically
/// create routes in Actix's App 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 generated Actix compatible paths.
pub fn generate_route_list<IV>(app_fn: impl FnOnce(leptos::Scope) -> IV + 'static) -> Vec<String>
where
IV: IntoView + 'static,
{
let mut routes = leptos_router::generate_route_list_inner(app_fn);
// Empty strings screw with Actix pathing, they need to be "/"
routes = routes.iter().map(|s| {
if s.is_empty() {
return "/".to_string()
}
s.to_string()
}).collect();
// Actix's Router doesn't follow Leptos's
// Match `*` or `*someword` to replace with replace it with "/{tail.*}
let wildcard_re = Regex::new(r"\*.*").unwrap();
// Match `:some_word` but only capture `some_word` in the groups to replace with `{some_word}`
let capture_re = Regex::new(r":((?:[^.,/]+)+)[^/]?").unwrap();
routes.iter().map(|s|
wildcard_re.replace_all(s, "{tail:.*}").to_string()
)
.map(|s| {
capture_re.replace_all(&s, "{$1}").to_string()
})
.collect()
}
/// This trait allows one to pass a list of routes and a render function to Axum's router, letting us avoid
/// having to use wildcards or manually define all routes in multiple places.
pub trait LeptosRoutes {
fn leptos_routes<IV>(
self,
options: LeptosOptions,
paths: Vec<String>,
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
/// to those paths to Leptos's renderer.
impl <T>LeptosRoutes for actix_web::App<T> where
T: ServiceFactory<ServiceRequest, Config = (), Error = Error, InitError = ()>{
fn leptos_routes<IV>(
self,
options: LeptosOptions,
paths: Vec<String>,
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(options.clone(), app_fn.clone()),
);
}
router
}
}

View File

@ -3,6 +3,7 @@ use axum::{
extract::Path,
http::{header::HeaderName, header::HeaderValue, HeaderMap, Request, StatusCode},
response::IntoResponse,
routing::get,
};
use futures::{Future, SinkExt, Stream, StreamExt};
use http::{header, method::Method, uri::Uri, version::Version, Response};
@ -11,7 +12,7 @@ use leptos::*;
use leptos_meta::MetaContext;
use leptos_router::*;
use std::{io, pin::Pin, sync::Arc};
use tokio::{sync::RwLock, task::spawn_blocking};
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
@ -328,17 +329,7 @@ where
full_path = "http://leptos".to_string() + &path.to_string()
}
let site_root = &options.site_root;
let pkg_path = &options.site_pkg_dir;
// We need to do some logic to check if the site_root is pkg
// if it is, then we need to not add pkg_path. This would mean
// the site was built with cargo run and not cargo-leptos
let bundle_path = match site_root.as_ref() {
"pkg" => "pkg".to_string(),
_ => format!("{site_root}/{pkg_path}"),
};
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
@ -385,9 +376,9 @@ where
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<link rel="modulepreload" href="/{bundle_path}/{output_name}.js">
<link rel="preload" href="/{bundle_path}/{wasm_output_name}.wasm" as="fetch" type="application/wasm" crossorigin="">
<script type="module">import init, {{ hydrate }} from '/{bundle_path}/{output_name}.js'; init('/{bundle_path}/{wasm_output_name}.wasm').then(hydrate);</script>
<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}
"#
);
@ -495,3 +486,79 @@ where
})
}
}
/// 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.
pub async fn generate_route_list<IV>(app_fn: impl FnOnce(Scope) -> IV + 'static) -> Vec<String>
where
IV: IntoView + 'static,
{
#[derive(Default, Clone, Debug)]
pub struct Routes(pub Arc<RwLock<Vec<String>>>);
let routes = Routes::default();
let routes_inner = routes.clone();
let local = LocalSet::new();
// Run the local task set.
local
.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;
*writable = routes;
})
.await
.unwrap();
})
.await;
let routes = routes.0.read().await.to_owned();
// Axum's Router defines Root routes as "/" not ""
routes
.iter()
.map(|s| {
if s.is_empty() {
return "/".to_string();
}
s.to_string()
})
.collect()
}
/// This trait allows one to pass a list of routes and a render function to Axum's router, letting us avoid
/// having to use wildcards or manually define all routes in multiple places.
pub trait LeptosRoutes {
fn leptos_routes<IV>(
self,
options: LeptosOptions,
paths: Vec<String>,
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
/// to those paths to Leptos's renderer.
impl LeptosRoutes for axum::Router {
fn leptos_routes<IV>(
self,
options: LeptosOptions,
paths: Vec<String>,
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(options.clone(), app_fn.clone())),
);
}
router
}
}

View File

@ -10,7 +10,7 @@ use typed_builder::TypedBuilder;
/// A Struct to allow us to parse LeptosOptions from the file. Not really needed, most interactions should
/// occur with LeptosOptions
#[derive(Clone, serde::Deserialize)]
#[derive(Clone, Debug, serde::Deserialize)]
pub struct ConfFile {
pub leptos_options: LeptosOptions,
}
@ -18,13 +18,13 @@ pub struct ConfFile {
/// It's used in our actix and axum integrations to generate the
/// correct path for WASM, JS, and Websockets, as well as other configuration tasks.
/// It shares keys with cargo-leptos, to allow for easy interoperability
#[derive(TypedBuilder, Clone, serde::Deserialize)]
#[derive(TypedBuilder, Debug, Clone, serde::Deserialize)]
pub struct LeptosOptions {
/// The name of the WASM and JS files generated by wasm-bindgen. Defaults to the crate name with underscores instead of dashes
#[builder(setter(into))]
pub output_name: String,
/// The path of the all the files generated by cargo-leptos
#[builder(setter(into), default="pkg".to_string())]
#[builder(setter(into), default="target/site".to_string())]
pub site_root: String,
/// The path of the WASM and JS files generated by wasm-bindgen from the root of your app
/// By default, wasm-bindgen puts them in `pkg`.

View File

@ -11,8 +11,8 @@ use wasm_bindgen::JsCast;
use leptos_reactive::use_transition;
use crate::{
create_location, matching::resolve_path, History, Location, LocationChange, RouteContext,
RouterIntegrationContext, State,
create_location, matching::resolve_path, Branch, History, Location, LocationChange,
RouteContext, RouterIntegrationContext, State,
};
#[cfg(not(feature = "ssr"))]
@ -49,6 +49,7 @@ pub struct RouterContext {
pub(crate) struct RouterContextInner {
pub location: Location,
pub base: RouteContext,
pub possible_routes: RefCell<Option<Vec<Branch>>>,
base_path: String,
history: Box<dyn History>,
cx: Scope,
@ -153,6 +154,7 @@ impl RouterContext {
referrers,
state,
set_state,
possible_routes: Default::default(),
});
// handle all click events on anchor tags
@ -175,6 +177,15 @@ impl RouterContext {
pub fn base(&self) -> RouteContext {
self.inner.base.clone()
}
/// A list of all possible routes this router can match.
pub fn possible_branches(&self) -> Vec<Branch> {
self.inner
.possible_routes
.borrow()
.clone()
.unwrap_or_default()
}
}
impl RouterContextInner {

View File

@ -12,7 +12,7 @@ use crate::{
expand_optionals, get_route_matches, join_paths, Branch, Matcher, RouteDefinition,
RouteMatch,
},
RouteContext, RouterContext,
PossibleBranchContext, RouteContext, RouterContext,
};
/// Contains route definitions and manages the actual routing process.
@ -42,6 +42,7 @@ pub fn Routes(
})
.cloned()
.collect::<Vec<_>>();
create_branches(
&children,
&base.unwrap_or_default(),
@ -49,6 +50,10 @@ pub fn Routes(
&mut branches,
);
if let Some(context) = use_context::<PossibleBranchContext>(cx) {
*context.0.borrow_mut() = branches.clone();
}
// whenever path changes, update matches
let matches = create_memo(cx, {
let router = router.clone();

View File

@ -0,0 +1,36 @@
use leptos::*;
use std::{cell::RefCell, rc::Rc};
use crate::{Branch, RouterIntegrationContext, ServerIntegration};
/// Context to contain all possible routes.
#[derive(Clone, Default, Debug)]
pub struct PossibleBranchContext(pub(crate) Rc<RefCell<Vec<Branch>>>);
/// Generates a list of all routes this application could possibly serve. This returns the raw routes in the leptos_router
/// format. Odds are you want `generate_route_list()` from either the actix or axum integrations if you want
/// to work with their router
#[cfg(feature = "ssr")]
pub fn generate_route_list_inner<IV>(app_fn: impl FnOnce(Scope) -> IV + 'static) -> Vec<String>
where
IV: IntoView + 'static,
{
let runtime = create_runtime();
run_scope(runtime, move |cx| {
let integration = ServerIntegration {
path: "http://leptos.rs/".to_string(),
};
provide_context(cx, RouterIntegrationContext::new(integration));
let branches = PossibleBranchContext::default();
provide_context(cx, branches.clone());
let _ = app_fn(cx).into_view(cx);
let branches = branches.0.borrow();
branches
.iter()
.flat_map(|branch| branch.routes.last().map(|route| route.pattern.clone()))
.collect()
})
}

View File

@ -184,12 +184,14 @@
#![cfg_attr(not(feature = "stable"), feature(type_name_of_val))]
mod components;
mod extract_routes;
mod history;
mod hooks;
#[doc(hidden)]
pub mod matching;
pub use components::*;
pub use extract_routes::*;
pub use history::*;
pub use hooks::*;
pub use matching::*;