repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/login_with_token_csr_only/client/src/pages/register.rs | projects/login_with_token_csr_only/client/src/pages/register.rs | use crate::{
api::{self, UnauthorizedApi},
components::credentials::*,
Page,
};
use api_boundary::*;
use leptos::{logging::log, *};
use leptos_router::*;
#[component]
pub fn Register(api: UnauthorizedApi) -> impl IntoView {
let (register_response, set_register_response) = create_signal(None::<()>);
let (register_error, set_register_error) = create_signal(None::<String>);
let (wait_for_response, set_wait_for_response) = create_signal(false);
let register_action =
create_action(move |(email, password): &(String, String)| {
let email = email.to_string();
let password = password.to_string();
let credentials = Credentials { email, password };
log!("Try to register new account for {}", credentials.email);
async move {
set_wait_for_response.update(|w| *w = true);
let result = api.register(&credentials).await;
set_wait_for_response.update(|w| *w = false);
match result {
Ok(res) => {
set_register_response.update(|v| *v = Some(res));
set_register_error.update(|e| *e = None);
}
Err(err) => {
let msg = match err {
api::Error::Fetch(js_err) => {
format!("{js_err:?}")
}
api::Error::Api(err) => err.message,
};
log::warn!(
"Unable to register new account for {}: {msg}",
credentials.email
);
set_register_error.update(|e| *e = Some(msg));
}
}
}
});
let disabled = Signal::derive(move || wait_for_response.get());
view! {
<Show
when=move || register_response.get().is_some()
fallback=move || {
view! {
<CredentialsForm
title="Please enter the desired credentials"
action_label="Register"
action=register_action
error=register_error.into()
disabled
/>
<p>"Your already have an account?"</p>
<A href=Page::Login.path()>"Login"</A>
}
}
>
<p>"You have successfully registered."</p>
<p>"You can now " <A href=Page::Login.path()>"login"</A> " with your new account."</p>
</Show>
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/login_with_token_csr_only/client/src/pages/login.rs | projects/login_with_token_csr_only/client/src/pages/login.rs | use crate::{
api::{self, AuthorizedApi, UnauthorizedApi},
components::credentials::*,
Page,
};
use api_boundary::*;
use leptos::prelude::*;
use leptos_router::*;
#[component]
pub fn Login(
api: UnauthorizedApi,
#[prop(into)] on_success: Callback<AuthorizedApi>,
) -> impl IntoView {
let (login_error, set_login_error) = create_signal(None::<String>);
let (wait_for_response, set_wait_for_response) = create_signal(false);
let login_action =
create_action(move |(email, password): &(String, String)| {
log::debug!("Try to login with {email}");
let email = email.to_string();
let password = password.to_string();
let credentials = Credentials { email, password };
async move {
set_wait_for_response.update(|w| *w = true);
let result = api.login(&credentials).await;
set_wait_for_response.update(|w| *w = false);
match result {
Ok(res) => {
set_login_error.update(|e| *e = None);
on_success.call(res);
}
Err(err) => {
let msg = match err {
api::Error::Fetch(js_err) => {
format!("{js_err:?}")
}
api::Error::Api(err) => err.message,
};
log::error!(
"Unable to login with {}: {msg}",
credentials.email
);
set_login_error.update(|e| *e = Some(msg));
}
}
}
});
let disabled = Signal::derive(move || wait_for_response.get());
view! {
<CredentialsForm
title="Please login to your account"
action_label="Login"
action=login_action
error=login_error.into()
disabled
/>
<p>"Don't have an account?"</p>
<A href=Page::Register.path()>"Register"</A>
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/login_with_token_csr_only/client/src/pages/home.rs | projects/login_with_token_csr_only/client/src/pages/home.rs | use crate::Page;
use api_boundary::UserInfo;
use leptos::prelude::*;
use leptos_router::*;
#[component]
pub fn Home(user_info: Signal<Option<UserInfo>>) -> impl IntoView {
view! {
<h2>"Leptos Login example"</h2>
{move || match user_info.get() {
Some(info) => {
view! { <p>"You are logged in with " {info.email} "."</p> }
.into_view()
}
None => {
view! {
<p>"You are not logged in."</p>
<A href=Page::Login.path()>"Login now."</A>
}
.into_view()
}
}}
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/login_with_token_csr_only/client/src/pages/mod.rs | projects/login_with_token_csr_only/client/src/pages/mod.rs | pub mod home;
pub mod login;
pub mod register;
pub use self::{home::*, login::*, register::*};
#[derive(Debug, Clone, Copy, Default)]
pub enum Page {
#[default]
Home,
Login,
Register,
}
impl Page {
pub fn path(&self) -> &'static str {
match self {
Self::Home => "/",
Self::Login => "/login",
Self::Register => "/register",
}
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/login_with_token_csr_only/client/src/components/navbar.rs | projects/login_with_token_csr_only/client/src/components/navbar.rs | use crate::Page;
use leptos::prelude::*;
use leptos_router::*;
#[component]
pub fn NavBar(
logged_in: Signal<bool>,
#[prop(into)] on_logout: Callback<()>,
) -> impl IntoView {
view! {
<nav>
<Show
when=move || logged_in.get()
fallback=|| {
view! {
<A href=Page::Login.path()>"Login"</A>
" | "
<A href=Page::Register.path()>"Register"</A>
}
}
>
<a
href="#"
on:click=move |_| on_logout.call(())
>
"Logout"
</a>
</Show>
</nav>
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/login_with_token_csr_only/client/src/components/mod.rs | projects/login_with_token_csr_only/client/src/components/mod.rs | pub mod credentials;
pub mod navbar;
pub use self::navbar::*;
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/login_with_token_csr_only/client/src/components/credentials.rs | projects/login_with_token_csr_only/client/src/components/credentials.rs | use leptos::prelude::*;
#[component]
pub fn CredentialsForm(
title: &'static str,
action_label: &'static str,
action: Action<(String, String), ()>,
error: Signal<Option<String>>,
disabled: Signal<bool>,
) -> impl IntoView {
let (password, set_password) = create_signal(String::new());
let (email, set_email) = create_signal(String::new());
let dispatch_action =
move || action.dispatch((email.get(), password.get()));
let button_is_disabled = Signal::derive(move || {
disabled.get() || password.get().is_empty() || email.get().is_empty()
});
view! {
<form on:submit=|ev| ev.prevent_default()>
<p>{title}</p>
{move || {
error
.get()
.map(|err| {
view! { <p style="color:red;">{err}</p> }
})
}}
<input
type="email"
required
placeholder="Email address"
prop:disabled=move || disabled.get()
on:keyup=move |ev: ev::KeyboardEvent| {
let val = event_target_value(&ev);
set_email.update(|v| *v = val);
}
on:change=move |ev| {
let val = event_target_value(&ev);
set_email.update(|v| *v = val);
}
/>
<input
type="password"
required
placeholder="Password"
prop:disabled=move || disabled.get()
on:keyup=move |ev: ev::KeyboardEvent| {
match &*ev.key() {
"Enter" => {
dispatch_action();
}
_ => {
let val = event_target_value(&ev);
set_password.update(|p| *p = val);
}
}
}
on:change=move |ev| {
let val = event_target_value(&ev);
set_password.update(|p| *p = val);
}
/>
<button
prop:disabled=move || button_is_disabled.get()
on:click=move |_| dispatch_action()
>
{action_label}
</button>
</form>
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/hexagonal-architecture/src/config.rs | projects/hexagonal-architecture/src/config.rs | use super::server_types::*;
pub fn config() -> HandlerStructAlias {
cfg_if::cfg_if! {
if #[cfg(feature="config_1")] {
fn server_handler_config_1() -> HandlerStruct<
SubDomainStruct1<ExternalService1_1, ExternalService2_1>,
SubDomainStruct2<ExternalService1_1>,
> {
HandlerStruct::default()
}
server_handler_config_1()
} else {
fn server_handler_config_2() -> HandlerStruct<
SubDomainStruct1<ExternalService1_2, ExternalService2_2>,
SubDomainStruct2<ExternalService1_2>,
> {
HandlerStruct::new()
}
server_handler_config_2()
}
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/hexagonal-architecture/src/app.rs | projects/hexagonal-architecture/src/app.rs | use leptos::prelude::*;
use leptos_meta::{provide_meta_context, MetaTags, Stylesheet, Title};
use leptos_router::{
components::{Route, Router, Routes},
StaticSegment,
};
#[cfg(feature = "ssr")]
use super::{server_types::HandlerStructAlias, traits::HandlerTrait};
use crate::ui_types::*;
pub fn shell(options: LeptosOptions) -> impl IntoView {
view! {
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<AutoReload options=options.clone() />
<HydrationScripts options/>
<MetaTags/>
</head>
<body>
<App/>
</body>
</html>
}
}
#[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-hexagonal-design.css"/>
// sets the document title
<Title text="Welcome to Leptos"/>
// content for this welcome page
<Router>
<main>
<Routes fallback=|| "Page not found.".into_view()>
<Route path=StaticSegment("") view=HomePage/>
</Routes>
</main>
</Router>
}
}
/// Renders the home page of your application.
#[component]
fn HomePage() -> impl IntoView {
let server_fn_1 = ServerAction::<ServerFunction1>::new();
let server_fn_2 = ServerAction::<ServerFunction2>::new();
let server_fn_3 = ServerAction::<ServerFunction3>::new();
Effect::new(move |_| {
server_fn_1.dispatch(ServerFunction1 {});
server_fn_2.dispatch(ServerFunction2 {});
server_fn_3.dispatch(ServerFunction3 {});
});
}
#[server]
#[middleware(crate::middleware::SubDomain1Layer)]
pub async fn server_function_1() -> Result<UiMappingFromDomainData, ServerFnError> {
Ok(expect_context::<HandlerStructAlias>()
.server_fn_1()
.await?
.into())
}
#[server]
pub async fn server_function_2() -> Result<UiMappingFromDomainData2, ServerFnError> {
Ok(expect_context::<HandlerStructAlias>()
.server_fn_2()
.await?
.into())
}
#[server]
pub async fn server_function_3() -> Result<UiMappingFromDomainData3, ServerFnError> {
Ok(expect_context::<HandlerStructAlias>()
.server_fn_3()
.await?
.into())
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/hexagonal-architecture/src/lib.rs | projects/hexagonal-architecture/src/lib.rs | pub mod app;
pub mod ui_types;
#[cfg(feature = "ssr")]
pub mod config;
#[cfg(feature = "ssr")]
pub mod middleware;
#[cfg(feature = "ssr")]
pub mod server_types;
#[cfg(feature = "ssr")]
pub mod trait_impl;
#[cfg(feature = "ssr")]
pub mod traits;
#[cfg(feature = "hydrate")]
#[wasm_bindgen::prelude::wasm_bindgen]
pub fn hydrate() {
use crate::app::*;
console_error_panic_hook::set_once();
leptos::mount::hydrate_body(App);
}
#[cfg(test)]
pub mod tests {
use super::server_types::*;
use super::traits::*;
use std::error::Error;
#[tokio::test]
pub async fn test_subdomain_1_with_mocks() -> Result<(), Box<dyn Error>> {
let mut mock_external_service_1 = MockExternalServiceTrait1::new();
mock_external_service_1
.expect_external_service_1_method()
.returning(|| {
println!("Mock external service 1");
Ok(ExternalService1Data)
});
let mut mock_external_service_2 = MockExternalServiceTrait2::new();
mock_external_service_2
.expect_external_service_2_method()
.returning(|| {
println!("Mock external service 2");
Ok(ExternalService2Data)
});
let real_subdomain_1_with_mock_externals = SubDomainStruct1 {
external_service_1: mock_external_service_1,
external_service_2: mock_external_service_2,
};
let data = real_subdomain_1_with_mock_externals
.sub_domain_1_method()
.await?;
assert_eq!(data, SubDomain1Data);
Ok(())
}
#[tokio::test]
pub async fn test_subdomain_2_with_mocks() -> Result<(), Box<dyn Error>> {
let mut mock_external_service_1 = MockExternalServiceTrait1::new();
mock_external_service_1
.expect_external_service_1_method()
.returning(|| {
println!("Mock external service 1 AGAIN");
Ok(ExternalService1Data)
});
let real_subdomain_2_with_mock_externals = SubDomainStruct2 {
external_service_1: mock_external_service_1,
};
let data = real_subdomain_2_with_mock_externals
.sub_domain_2_method()
.await?;
assert_eq!(data, SubDomain2Data);
Ok(())
}
#[tokio::test]
pub async fn test_handler_with_mocks() -> Result<(), Box<dyn Error>> {
let mut mock_subdomain_1_trait = MockSubDomainTrait1::new();
mock_subdomain_1_trait
.expect_sub_domain_1_method()
.returning(|| {
println!("Mock Subdomain 1");
Ok(SubDomain1Data)
});
let mut mock_subdomain_2_trait = MockSubDomainTrait2::new();
mock_subdomain_2_trait
.expect_sub_domain_2_method()
.returning(|| {
println!("Mock Subdomain 2");
Ok(SubDomain2Data)
});
let real_handler_with_mock_subdomains = HandlerStruct {
sub_domain_1: mock_subdomain_1_trait,
sub_domain_2: mock_subdomain_2_trait,
};
let data = real_handler_with_mock_subdomains.server_fn_1().await?;
assert_eq!(data, DomainData);
let data = real_handler_with_mock_subdomains.server_fn_2().await?;
assert_eq!(data, DomainData2);
let data = real_handler_with_mock_subdomains.server_fn_3().await?;
assert_eq!(data, DomainData3);
Ok(())
}
fn mock_subdomain_1() -> SubDomainStruct1<MockExternalServiceTrait1, MockExternalServiceTrait2>
{
let mut mock_external_service_1 = MockExternalServiceTrait1::new();
mock_external_service_1
.expect_external_service_1_method()
.returning(|| {
println!("Mock external service 1");
Ok(ExternalService1Data)
});
let mut mock_external_service_2 = MockExternalServiceTrait2::new();
mock_external_service_2
.expect_external_service_2_method()
.returning(|| {
println!("Mock external service 2");
Ok(ExternalService2Data)
});
let real_subdomain_1_with_mock_externals = SubDomainStruct1 {
external_service_1: mock_external_service_1,
external_service_2: mock_external_service_2,
};
real_subdomain_1_with_mock_externals
}
#[tokio::test]
pub async fn test_handler_with_mock_and_real_mix() -> Result<(), Box<dyn Error>> {
let sub_domain_1 = mock_subdomain_1();
let mut mock_subdomain_2_trait = MockSubDomainTrait2::new();
mock_subdomain_2_trait
.expect_sub_domain_2_method()
.returning(|| {
println!("Mock Subdomain 2");
Ok(SubDomain2Data)
});
let real_handler = HandlerStruct {
sub_domain_1,
sub_domain_2: mock_subdomain_2_trait,
};
let data = real_handler.server_fn_1().await?;
assert_eq!(data, DomainData);
let data = real_handler.server_fn_2().await?;
assert_eq!(data, DomainData2);
let data = real_handler.server_fn_3().await?;
assert_eq!(data, DomainData3);
Ok(())
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/hexagonal-architecture/src/ui_types.rs | projects/hexagonal-architecture/src/ui_types.rs | use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
pub struct UiMappingFromDomainData;
#[derive(Serialize, Deserialize)]
pub struct UiMappingFromDomainData2;
#[derive(Serialize, Deserialize)]
pub struct UiMappingFromDomainData3;
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/hexagonal-architecture/src/server_types.rs | projects/hexagonal-architecture/src/server_types.rs | use super::traits::*;
use leptos::config::LeptosOptions;
use thiserror::Error;
#[derive(Clone)]
pub struct ServerState<Handler: HandlerTrait> {
pub handler: Handler,
pub leptos_options: LeptosOptions,
}
#[cfg(feature = "config_1")]
pub type HandlerStructAlias = HandlerStruct<
SubDomainStruct1<ExternalService1_1, ExternalService2_1>,
SubDomainStruct2<ExternalService1_1>,
>;
#[cfg(not(feature = "config_1"))]
pub type HandlerStructAlias = HandlerStruct<
SubDomainStruct1<ExternalService1_2, ExternalService2_2>,
SubDomainStruct2<ExternalService1_2>,
>;
#[derive(Clone, Default)]
pub struct HandlerStruct<SubDomain1: SubDomainTrait1, SubDomain2: SubDomainTrait2> {
pub sub_domain_1: SubDomain1,
pub sub_domain_2: SubDomain2,
}
#[derive(Clone, Default)]
pub struct SubDomainStruct1<
ExternalService1: ExternalServiceTrait1,
ExternalService2: ExternalServiceTrait2,
> {
pub external_service_1: ExternalService1,
pub external_service_2: ExternalService2,
}
#[derive(Clone, Default)]
pub struct SubDomainStruct2<ExternalService1: ExternalServiceTrait1> {
pub external_service_1: ExternalService1,
}
#[derive(Clone, Default)]
pub struct ExternalService1_1;
#[derive(Clone, Default)]
pub struct ExternalService1_2;
#[derive(Clone, Default)]
pub struct ExternalService2_1;
#[derive(Clone, Default)]
pub struct ExternalService2_2;
#[derive(Clone, Default)]
pub struct ExternalService1;
#[derive(Clone, PartialEq, Debug)]
pub struct DomainData;
#[derive(Clone, PartialEq, Debug)]
pub struct DomainData2;
#[derive(Clone, PartialEq, Debug)]
pub struct DomainData3;
#[derive(Clone, PartialEq, Debug)]
pub struct SubDomain1Data;
#[derive(Clone, PartialEq, Debug)]
pub struct SubDomain2Data;
#[derive(Clone)]
pub struct ExternalService1Data;
#[derive(Clone)]
pub struct ExternalService2Data;
#[derive(Clone, Error, Debug)]
pub enum DomainError {
#[error("Underlying Subdomain 1 Error")]
SubDomain1Error(#[from] SubDomain1Error),
#[error("Underlying Subdomain 2 Error")]
SubDomain2Error(#[from] SubDomain2Error),
}
#[derive(Clone, Error, Debug)]
pub enum SubDomain1Error {
#[error("Sub Domain 1 Error")]
SubDomain1Error,
#[error("Underlying Service 1")]
ExternalService1Error(#[from] ExternalService1Error),
#[error("Underlying Service 2")]
ExternalService2Error(#[from] ExternalService2Error),
}
#[derive(Clone, Error, Debug)]
pub enum SubDomain2Error {
#[error("Sub Domain 2 Error")]
SubDomain2Error,
#[error("Underlying Service 1")]
ExternalService1Error(#[from] ExternalService1Error),
}
#[derive(Clone, Error, Debug)]
pub enum ExternalService1Error {
#[error("Service 1 Error")]
Error,
}
#[derive(Clone, Error, Debug)]
pub enum ExternalService2Error {
#[error("Service 2 Error")]
Error,
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/hexagonal-architecture/src/middleware.rs | projects/hexagonal-architecture/src/middleware.rs | use axum::{
body::Body,
http::{Request, Response},
};
use leptos::prelude::expect_context;
use std::{
future::Future,
pin::Pin,
task::{Context, Poll},
};
use tower::{Layer, Service};
use crate::{
server_types::{HandlerStructAlias, ServerState},
traits::SubDomainTrait1,
};
use pin_project_lite::pin_project;
#[derive(Clone)]
pub struct SubDomain1Layer;
impl<S> Layer<S> for SubDomain1Layer {
type Service = SubDomain1MiddleWare<S>;
fn layer(&self, inner: S) -> Self::Service {
SubDomain1MiddleWare { inner }
}
}
pub struct SubDomain1MiddleWare<S> {
inner: S,
}
impl<S, ReqBody> Service<Request<ReqBody>> for SubDomain1MiddleWare<S>
where
S: Service<Request<ReqBody>, Response = Response<Body>>,
S::Error: std::fmt::Debug,
S::Future: Send + 'static,
{
type Response = S::Response;
type Error = S::Error;
type Future = SubDomain1Future<S::Future>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.inner.poll_ready(cx)
}
fn call(&mut self, req: Request<ReqBody>) -> Self::Future {
let req_fut = self.inner.call(req);
SubDomain1Future { req_fut }
}
}
pin_project! {
pub struct SubDomain1Future<F> {
#[pin]
req_fut: F,
}
}
impl<F, Err> Future for SubDomain1Future<F>
where
F: Future<Output = Result<Response<Body>, Err>>,
{
type Output = Result<Response<Body>, Err>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.project();
let subdomain_1 = expect_context::<ServerState<HandlerStructAlias>>()
.handler
.sub_domain_1;
let mut subdomain_1_fut = subdomain_1.sub_domain_1_method();
match Pin::as_mut(&mut subdomain_1_fut).poll(cx) {
Poll::Ready(Ok(_)) => {
println!("Middleware for Subdomain 1 Passed, calling request...");
this.req_fut.poll(cx)
}
Poll::Ready(Err(_)) => Poll::Ready(Ok(Response::builder()
.status(http::StatusCode::FORBIDDEN)
.body(Body::from("Access denied"))
.unwrap())),
Poll::Pending => Poll::Pending,
}
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/hexagonal-architecture/src/trait_impl.rs | projects/hexagonal-architecture/src/trait_impl.rs | use crate::ui_types::*;
use super::server_types::*;
use super::traits::*;
use axum::async_trait;
use axum::extract::FromRef;
use leptos::config::LeptosOptions;
// So we can pass our server state as state into our leptos router.
impl<Handler: HandlerTrait + Clone> FromRef<ServerState<Handler>> for LeptosOptions {
fn from_ref(input: &ServerState<Handler>) -> Self {
input.leptos_options.clone()
}
}
#[async_trait]
impl<SubDomain1, SubDomain2> HandlerTrait for HandlerStruct<SubDomain1, SubDomain2>
where
SubDomain1: SubDomainTrait1 + Send + Sync,
SubDomain2: SubDomainTrait2 + Send + Sync,
{
async fn server_fn_1(&self) -> Result<DomainData, DomainError> {
Ok(self.sub_domain_1.sub_domain_1_method().await?.into())
}
async fn server_fn_2(&self) -> Result<DomainData2, DomainError> {
Ok(self.sub_domain_2.sub_domain_2_method().await?.into())
}
async fn server_fn_3(&self) -> Result<DomainData3, DomainError> {
Ok((
self.sub_domain_1.sub_domain_1_method().await?,
self.sub_domain_2.sub_domain_2_method().await?,
)
.into())
}
}
#[async_trait]
impl<ExternalService1, ExternalService2> SubDomainTrait1
for SubDomainStruct1<ExternalService1, ExternalService2>
where
ExternalService1: ExternalServiceTrait1 + Send + Sync,
ExternalService2: ExternalServiceTrait2 + Send + Sync,
{
async fn sub_domain_1_method(&self) -> Result<SubDomain1Data, SubDomain1Error> {
Ok((
self.external_service_1.external_service_1_method().await?,
self.external_service_2.external_service_2_method().await?,
)
.into())
}
}
#[async_trait]
impl<ExternalService1> SubDomainTrait2 for SubDomainStruct2<ExternalService1>
where
ExternalService1: ExternalServiceTrait1 + Send + Sync,
{
async fn sub_domain_2_method(&self) -> Result<SubDomain2Data, SubDomain2Error> {
Ok(self
.external_service_1
.external_service_1_method()
.await?
.into())
}
}
#[async_trait]
impl ExternalServiceTrait1 for ExternalService1_1 {
async fn external_service_1_method(
&self,
) -> Result<ExternalService1Data, ExternalService1Error> {
println!("External Service 1 From External Service 1_1");
Ok(ExternalService1Data)
}
}
#[async_trait]
impl ExternalServiceTrait1 for ExternalService1_2 {
async fn external_service_1_method(
&self,
) -> Result<ExternalService1Data, ExternalService1Error> {
println!("External Service 1 From External Service 1_2");
Ok(ExternalService1Data)
}
}
#[async_trait]
impl ExternalServiceTrait2 for ExternalService2_1 {
async fn external_service_2_method(
&self,
) -> Result<ExternalService2Data, ExternalService2Error> {
println!("External Service 2 From External Service 2_1");
Ok(ExternalService2Data)
}
}
#[async_trait]
impl ExternalServiceTrait2 for ExternalService2_2 {
async fn external_service_2_method(
&self,
) -> Result<ExternalService2Data, ExternalService2Error> {
println!("External Service 2 From External Service 2_2");
Ok(ExternalService2Data)
}
}
// Sub Domain mapping
impl From<(ExternalService1Data, ExternalService2Data)> for SubDomain1Data {
fn from(_: (ExternalService1Data, ExternalService2Data)) -> Self {
Self
}
}
impl From<ExternalService1Data> for SubDomain2Data {
fn from(_: ExternalService1Data) -> Self {
Self
}
}
// Domain Mapping
impl From<SubDomain1Data> for DomainData {
fn from(_: SubDomain1Data) -> Self {
Self
}
}
impl From<SubDomain2Data> for DomainData2 {
fn from(_: SubDomain2Data) -> Self {
Self
}
}
impl From<(SubDomain1Data, SubDomain2Data)> for DomainData3 {
fn from(_: (SubDomain1Data, SubDomain2Data)) -> Self {
Self
}
}
// Ui Mapping
impl From<DomainData> for UiMappingFromDomainData {
fn from(_: DomainData) -> Self {
Self
}
}
impl From<DomainData2> for UiMappingFromDomainData2 {
fn from(_: DomainData2) -> Self {
Self
}
}
impl From<DomainData3> for UiMappingFromDomainData3 {
fn from(_: DomainData3) -> Self {
Self
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/hexagonal-architecture/src/main.rs | projects/hexagonal-architecture/src/main.rs | #[cfg(feature = "ssr")]
#[tokio::main]
async fn main() {
use axum::Router;
use leptos::logging::log;
use leptos::prelude::*;
use leptos_axum::{generate_route_list, LeptosRoutes};
use leptos_hexagonal_design::{
app::*,
config::config,
server_types::{HandlerStructAlias, ServerState},
};
let conf = get_configuration(None).unwrap();
let addr = conf.leptos_options.site_addr;
let leptos_options = conf.leptos_options;
let routes = generate_route_list(App);
let handler = config();
let handler_c = handler.clone();
let server_state = ServerState {
handler,
leptos_options: leptos_options.clone(),
};
let app = Router::new()
.leptos_routes_with_context(
&server_state,
routes,
move || provide_context(handler_c.clone()),
{
let leptos_options = leptos_options.clone();
move || shell(leptos_options.clone())
},
)
.fallback(leptos_axum::file_and_error_handler::<
ServerState<HandlerStructAlias>,
_,
>(shell))
.with_state(server_state);
log!("listening on http://{}", &addr);
let listener = tokio::net::TcpListener::bind(&addr).await.unwrap();
axum::serve(listener, app.into_make_service())
.await
.unwrap();
}
#[cfg(not(feature = "ssr"))]
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
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/hexagonal-architecture/src/traits.rs | projects/hexagonal-architecture/src/traits.rs | use super::server_types::*;
use axum::async_trait;
use mockall::automock;
pub trait New {
fn new() -> Self;
}
#[automock]
#[async_trait]
pub trait HandlerTrait {
async fn server_fn_1(&self) -> Result<DomainData, DomainError>;
async fn server_fn_2(&self) -> Result<DomainData2, DomainError>;
async fn server_fn_3(&self) -> Result<DomainData3, DomainError>;
}
#[automock]
#[async_trait]
pub trait SubDomainTrait1 {
async fn sub_domain_1_method(&self) -> Result<SubDomain1Data, SubDomain1Error>;
}
#[automock]
#[async_trait]
pub trait SubDomainTrait2 {
async fn sub_domain_2_method(&self) -> Result<SubDomain2Data, SubDomain2Error>;
}
#[automock]
#[async_trait]
pub trait ExternalServiceTrait1 {
async fn external_service_1_method(
&self,
) -> Result<ExternalService1Data, ExternalService1Error>;
}
#[automock]
#[async_trait]
pub trait ExternalServiceTrait2 {
async fn external_service_2_method(
&self,
) -> Result<ExternalService2Data, ExternalService2Error>;
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/meilisearch-searchbar/src/lib.rs | projects/meilisearch-searchbar/src/lib.rs | use leptos::*;
use leptos_meta::*;
use leptos_router::*;
#[cfg(feature = "ssr")]
pub mod fallback;
#[cfg(feature = "hydrate")]
#[wasm_bindgen::prelude::wasm_bindgen]
pub fn hydrate() {
// initializes logging using the `log` crate
_ = console_log::init_with_level(log::Level::Debug);
console_error_panic_hook::set_once();
leptos::mount_to_body(App);
}
#[component]
pub fn App() -> impl IntoView {
provide_meta_context();
// Provide this two our search components, they'll share a read and write handle to a Vec<StockRow>.
let search_results = create_rw_signal(Vec::<StockRow>::new());
provide_context(search_results);
view! {
<Link rel="shortcut icon" type_="image/ico" href="/favicon.ico"/>
<Meta name="description" content="Leptos implementation of a Meilisearch backed Searchbar."/>
<Router>
<main>
<Routes>
<Route path="/" view=||view!{
<SearchBar/>
<SearchResults/>
}/>
</Routes>
</main>
</Router>
}
}
#[derive(Clone, serde::Deserialize, serde::Serialize, Debug)]
pub struct StockRow {
id: u32,
name: String,
last: String,
high: String,
low: String,
absolute_change: f32,
percentage_change: f32,
volume: u64,
}
#[leptos::server]
pub async fn search_query(query: String) -> Result<Vec<StockRow>, ServerFnError> {
use leptos_axum::extract;
// Wow, so ergonomic!
let axum::Extension::<meilisearch_sdk::Client>(client) = extract().await?;
// Meilisearch has great defaults, lots of things are thought of for out of the box utility.
// They limit the result length automatically (to 20), and have user friendly typo corrections and return similar words.
let hits = client
.get_index("stock_prices")
.await
.unwrap()
.search()
.with_query(query.as_str())
.execute::<StockRow>()
.await
.map_err(|err| ServerFnError::new(err.to_string()))?
.hits;
Ok(hits
.into_iter()
.map(|search_result| search_result.result)
.collect())
}
#[component]
pub fn SearchBar() -> impl IntoView {
let write_search_results = expect_context::<RwSignal<Vec<StockRow>>>().write_only();
let search_query = create_server_action::<SearchQuery>();
create_effect(move |_| {
if let Some(value) = search_query.value()() {
match value {
Ok(search_results) => {
write_search_results.set(search_results);
}
Err(err) => {
leptos::logging::log!("{err}")
}
}
}
});
view! {
<div>
<label for="search">Search</label>
<input id="search" on:input=move|e|{
let query = event_target_value(&e);
search_query.dispatch(SearchQuery{query});
}/>
</div>
}
}
#[component]
pub fn SearchResults() -> impl IntoView {
let read_search_results = expect_context::<RwSignal<Vec<StockRow>>>().read_only();
view! {
<ul>
<For
each=read_search_results
key=|row| row.name.clone()
children=move |StockRow{name,last,high,low,absolute_change,percentage_change,volume,..}: StockRow| {
view! {
<li>
{format!("{name}; last: {last}; high: {high}; low: {low}; chg.: {absolute_change}; chg...:{percentage_change}; volume:{volume}")}
</li>
}
}
/>
</ul>
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/meilisearch-searchbar/src/main.rs | projects/meilisearch-searchbar/src/main.rs | #[cfg(feature = "ssr")]
#[tokio::main]
async fn main() {
use axum::{routing::get, Extension, Router};
use leptos::get_configuration;
use leptos_axum::{generate_route_list, LeptosRoutes};
use meilisearch_searchbar::StockRow;
use meilisearch_searchbar::{fallback::file_and_error_handler, *};
// simple_logger is a lightweight alternative to tracing, when you absolutely have to trace, use tracing.
simple_logger::SimpleLogger::new()
.with_level(log::LevelFilter::Debug)
.init()
.unwrap();
let mut rdr = csv::Reader::from_path("data_set.csv").unwrap();
// Our data set doesn't have a good id for the purposes of meilisearch, Name is unique but it's not formatted correctly because it may have spaces.
let documents: Vec<StockRow> = rdr
.records()
.enumerate()
.map(|(i, rec)| {
// There's probably a better way to do this.
let mut record = csv::StringRecord::new();
record.push_field(&i.to_string());
for field in rec.unwrap().iter() {
record.push_field(field);
}
record
.deserialize::<StockRow>(None)
.expect(&format!("{:?}", record))
})
.collect();
// My own check. I know how long I expect it to be, if it's not this length something is wrong.
assert_eq!(documents.len(), 503);
let client = meilisearch_sdk::Client::new(
std::env::var("MEILISEARCH_URL").unwrap(),
std::env::var("MEILISEARCH_API_KEY").ok(),
);
// An index is where the documents are stored.
let task = client
.create_index("stock_prices", Some("id"))
.await
.unwrap();
// Meilisearch may take some time to execute the request so we are going to wait till it's completed
client.wait_for_task(task, None, None).await.unwrap();
let task_2 = client
.get_index("stock_prices")
.await
.unwrap()
.add_documents(&documents, Some("id"))
.await
.unwrap();
client.wait_for_task(task_2, None, None).await.unwrap();
drop(documents);
let conf = get_configuration(Some("Cargo.toml")).unwrap();
let leptos_options = conf.leptos_options;
let addr = leptos_options.site_addr;
let routes = generate_route_list(App);
// build our application with a route
let app = Router::new()
.route("/favicon.ico", get(file_and_error_handler))
.leptos_routes(&leptos_options, routes, App)
.fallback(file_and_error_handler)
.layer(Extension(client))
.with_state(leptos_options);
// run our app with hyper
// `axum::Server` is a re-export of `hyper::Server`
println!("listening on {}", addr);
let listener = tokio::net::TcpListener::bind(&addr).await.unwrap();
axum::serve(listener, app.into_make_service())
.await
.unwrap();
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/meilisearch-searchbar/src/fallback.rs | projects/meilisearch-searchbar/src/fallback.rs | use axum::{
body::Body,
extract::State,
http::{Request, Response, StatusCode, Uri},
response::{IntoResponse, Response as AxumResponse},
};
use leptos::{view, LeptosOptions};
use tower::ServiceExt;
use tower_http::services::ServeDir;
pub async fn file_and_error_handler(
uri: Uri,
State(options): State<LeptosOptions>,
req: Request<Body>,
) -> AxumResponse {
let root = options.site_root.clone();
log::debug!("uri = {uri:?} root = {root} ");
let res = get_static_file(uri.clone(), &root).await.unwrap();
if res.status() == StatusCode::OK {
res.into_response()
} else {
let handler = leptos_axum::render_app_to_stream(
options.to_owned(),
|| view! {"Error! Error! Error!"},
);
handler(req).await.into_response()
}
}
async fn get_static_file(uri: Uri, root: &str) -> Result<Response<Body>, (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.into_response()),
Err(err) => Err((
StatusCode::INTERNAL_SERVER_ERROR,
format!("Something went wrong: {}", err),
)),
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/nginx-mpmc/app-2/src/app.rs | projects/nginx-mpmc/app-2/src/app.rs | use crate::error_template::{AppError, ErrorTemplate};
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="/pkg2/app-2.css"/>
// sets the document title
<Title text="Welcome to Leptos"/>
// content for this welcome page
<Router fallback=|| {
let mut outside_errors = Errors::default();
outside_errors.insert_with_default_key(AppError::NotFound);
view! {
<ErrorTemplate outside_errors/>
}
.into_view()
}>
<main>
<Routes>
<Route path="app2" view=HomePage/>
</Routes>
</main>
</Router>
}
}
/// Renders the home page of your application.
#[component]
fn HomePage() -> impl IntoView {
use shared_server::SharedServerFunction;
use shared_server_2::SharedServerFunction2;
let hello_1_action = Action::<SharedServerFunction,_>::server();
let hello_2_action = Action::<SharedServerFunction2,_>::server();
let value_1 = create_rw_signal(String::from("waiting for update from shared server."));
let value_2 = create_rw_signal(String::from("waiting for update from shared server 2."));
//let hello_2 = create_resource(move || (), shared_server_2::shared_server_function);
create_effect(move|_|{if let Some(Ok(msg)) = hello_1_action.value().get(){value_1.set(msg)}});
create_effect(move|_|{if let Some(Ok(msg)) = hello_2_action.value().get(){value_2.set(msg)}});
view! {
<h1> App 2</h1>
<div> action response from server 1 </div>
<button on:click=move|_|hello_1_action.dispatch(SharedServerFunction{})>request from shared server 1</button>
{move || value_1.get()}
<div> action response from server 2 </div>
<button on:click=move|_|hello_2_action.dispatch(SharedServerFunction2{})>request from shared server 2</button>
{move || value_2.get()}
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/nginx-mpmc/app-2/src/fileserv.rs | projects/nginx-mpmc/app-2/src/fileserv.rs | use axum::{
body::Body,
extract::State,
response::IntoResponse,
http::{Request, Response, StatusCode, Uri},
};
use axum::response::Response as AxumResponse;
use tower::ServiceExt;
use tower_http::services::ServeDir;
use leptos::*;
use crate::app::App;
pub async fn file_and_error_handler(uri: Uri, State(options): State<LeptosOptions>, req: Request<Body>) -> AxumResponse {
let root = options.site_root.clone();
tracing::debug!("APP 2");
let res = get_static_file(uri.clone(), &root).await.unwrap();
if res.status() == StatusCode::OK {
res.into_response()
} else {
let handler = leptos_axum::render_app_to_stream(options.to_owned(), App);
handler(req).await.into_response()
}
}
async fn get_static_file(
uri: Uri,
root: &str,
) -> Result<Response<Body>, (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.into_response()),
Err(err) => Err((
StatusCode::INTERNAL_SERVER_ERROR,
format!("Something went wrong: {err}"),
)),
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/nginx-mpmc/app-2/src/lib.rs | projects/nginx-mpmc/app-2/src/lib.rs | pub mod app;
pub mod error_template;
#[cfg(feature = "ssr")]
pub mod fileserv;
#[cfg(feature = "hydrate")]
#[wasm_bindgen::prelude::wasm_bindgen]
pub fn hydrate() {
use crate::app::*;
console_error_panic_hook::set_once();
leptos::mount_to_body(App);
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/nginx-mpmc/app-2/src/error_template.rs | projects/nginx-mpmc/app-2/src/error_template.rs | use http::status::StatusCode;
use leptos::*;
use thiserror::Error;
#[derive(Clone, Debug, Error)]
pub enum AppError {
#[error("Not Found")]
NotFound,
}
impl AppError {
pub fn status_code(&self) -> StatusCode {
match self {
AppError::NotFound => StatusCode::NOT_FOUND,
}
}
}
// A basic function to display errors served by the error boundaries.
// Feel free to do more complicated things here than just displaying the error.
#[component]
pub fn ErrorTemplate(
#[prop(optional)] outside_errors: Option<Errors>,
#[prop(optional)] errors: Option<RwSignal<Errors>>,
) -> impl IntoView {
let errors = match outside_errors {
Some(e) => create_rw_signal(e),
None => match errors {
Some(e) => e,
None => panic!("No Errors found and we expected errors!"),
},
};
// Get Errors from Signal
let errors = errors.get_untracked();
// 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(feature = "ssr")]
{
use leptos_axum::ResponseOptions;
let response = use_context::<ResponseOptions>();
if let Some(response) = response {
response.set_status(errors[0].status_code());
}
}
view! {
<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
children=move |error| {
let error_string = error.1.to_string();
let error_code= error.1.status_code();
view! {
<h2>{error_code.to_string()}</h2>
<p>"Error: " {error_string}</p>
}
}
/>
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/nginx-mpmc/app-2/src/main.rs | projects/nginx-mpmc/app-2/src/main.rs | #[cfg(feature = "ssr")]
#[tokio::main]
async fn main() {
use axum::{
Router,
routing::get,
};
use leptos::*;
use leptos_axum::{generate_route_list, LeptosRoutes};
use app_2::app::*;
use app_2::fileserv::file_and_error_handler;
// Setting get_configuration(None) means we'll be using cargo-leptos's env values
// For deployment these variables are:
// <https://github.com/leptos-rs/start-axum#executing-a-server-on-a-remote-machine-without-the-toolchain>
// Alternately a file can be specified such as Some("Cargo.toml")
// The file would need to be included with the executable when moved to deployment
let conf = get_configuration(Some("Cargo.toml")).unwrap();
let leptos_options = conf.leptos_options;
let addr = leptos_options.site_addr;
let routes = generate_route_list(App);
let app = Router::new()
.leptos_routes(&leptos_options, routes, App)
.fallback(file_and_error_handler)
.layer(tower_http::trace::TraceLayer::new_for_http())
.with_state(leptos_options);
let listener = tokio::net::TcpListener::bind(&addr).await.unwrap();
logging::log!("listening on http://{}", &addr);
axum::serve(listener, app.into_make_service())
.await
.unwrap();
}
#[cfg(not(feature = "ssr"))]
pub fn main() {
// no client-side main function
// unless we want this to work with e.g., Trunk for a purely client-side app
// see lib.rs for hydration function instead
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/nginx-mpmc/app-1/src/app.rs | projects/nginx-mpmc/app-1/src/app.rs | use crate::error_template::{AppError, ErrorTemplate};
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/app-1.css"/>
// sets the document title
<Title text="Welcome to Leptos"/>
// content for this welcome page
<Router fallback=|| {
let mut outside_errors = Errors::default();
outside_errors.insert_with_default_key(AppError::NotFound);
view! {
<ErrorTemplate outside_errors/>
}
.into_view()
}>
<main>
<Routes>
<Route path="" view=HomePage/>
</Routes>
</main>
</Router>
}
}
/// Renders the home page of your application.
#[component]
fn HomePage() -> impl IntoView {
use shared_server::SharedServerFunction;
use shared_server_2::SharedServerFunction2;
// A local resource will wait for the client to load before attempting to initialize.
let hello_1 = create_local_resource(move || (), |_| shared_server::shared_server_function());
// this won't work : let hello_1 = create_resource(move || (), |_| shared_server::shared_server_function());
// A resource is initialized on the rendering server when using SSR.
let hello_1_action = Action::<SharedServerFunction,_>::server();
let hello_2_action = Action::<SharedServerFunction2,_>::server();
let value_1 = create_rw_signal(String::from("waiting for update from shared server."));
let value_2 = create_rw_signal(String::from("waiting for update from shared server 2."));
//let hello_2 = create_resource(move || (), shared_server_2::shared_server_function);
create_effect(move|_|{if let Some(Ok(msg)) = hello_1_action.value().get(){value_1.set(msg)}});
create_effect(move|_|{if let Some(Ok(msg)) = hello_2_action.value().get(){value_2.set(msg)}});
view! {
<h1> App 1</h1>
<div>Suspense</div>
<Suspense fallback=move || view! { <p>"Loading (Suspense Fallback)..."</p> }>
{move || {
hello_1.get().map(|data| match data {
Err(_) => view! { <pre>"Error"</pre> }.into_view(),
Ok(hello) => hello.into_view(),
})
}
}
</Suspense>
<div> action response from server 1 </div>
<button on:click=move|_|hello_1_action.dispatch(SharedServerFunction{})>request from shared server 1</button>
{move || value_1.get()}
<div> action response from server 2 </div>
<button on:click=move|_|hello_2_action.dispatch(SharedServerFunction2{})>request from shared server 2</button>
{move || value_2.get()}
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/nginx-mpmc/app-1/src/fileserv.rs | projects/nginx-mpmc/app-1/src/fileserv.rs | use axum::{
body::Body,
extract::State,
response::IntoResponse,
http::{Request, Response, StatusCode, Uri},
};
use axum::response::Response as AxumResponse;
use tower::ServiceExt;
use tower_http::services::ServeDir;
use leptos::*;
use crate::app::App;
pub async fn file_and_error_handler(uri: Uri, State(options): State<LeptosOptions>, req: Request<Body>) -> AxumResponse {
let root = options.site_root.clone();
tracing::debug!("APP 1");
let res = get_static_file(uri.clone(), &root).await.unwrap();
if res.status() == StatusCode::OK {
res.into_response()
} else {
let handler = leptos_axum::render_app_to_stream(options.to_owned(), App);
handler(req).await.into_response()
}
}
async fn get_static_file(
uri: Uri,
root: &str,
) -> Result<Response<Body>, (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.into_response()),
Err(err) => Err((
StatusCode::INTERNAL_SERVER_ERROR,
format!("Something went wrong: {err}"),
)),
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/nginx-mpmc/app-1/src/lib.rs | projects/nginx-mpmc/app-1/src/lib.rs | pub mod app;
pub mod error_template;
#[cfg(feature = "ssr")]
pub mod fileserv;
#[cfg(feature = "hydrate")]
#[wasm_bindgen::prelude::wasm_bindgen]
pub fn hydrate() {
use crate::app::*;
console_error_panic_hook::set_once();
leptos::mount_to_body(App);
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/nginx-mpmc/app-1/src/error_template.rs | projects/nginx-mpmc/app-1/src/error_template.rs | use http::status::StatusCode;
use leptos::*;
use thiserror::Error;
#[derive(Clone, Debug, Error)]
pub enum AppError {
#[error("Not Found")]
NotFound,
}
impl AppError {
pub fn status_code(&self) -> StatusCode {
match self {
AppError::NotFound => StatusCode::NOT_FOUND,
}
}
}
// A basic function to display errors served by the error boundaries.
// Feel free to do more complicated things here than just displaying the error.
#[component]
pub fn ErrorTemplate(
#[prop(optional)] outside_errors: Option<Errors>,
#[prop(optional)] errors: Option<RwSignal<Errors>>,
) -> impl IntoView {
let errors = match outside_errors {
Some(e) => create_rw_signal(e),
None => match errors {
Some(e) => e,
None => panic!("No Errors found and we expected errors!"),
},
};
// Get Errors from Signal
let errors = errors.get_untracked();
// 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(feature = "ssr")]
{
use leptos_axum::ResponseOptions;
let response = use_context::<ResponseOptions>();
if let Some(response) = response {
response.set_status(errors[0].status_code());
}
}
view! {
<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
children=move |error| {
let error_string = error.1.to_string();
let error_code= error.1.status_code();
view! {
<h2>{error_code.to_string()}</h2>
<p>"Error: " {error_string}</p>
}
}
/>
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/nginx-mpmc/app-1/src/main.rs | projects/nginx-mpmc/app-1/src/main.rs | #[cfg(feature = "ssr")]
#[tokio::main]
async fn main() {
use axum::Router;
use leptos::*;
use leptos_axum::{generate_route_list, LeptosRoutes};
use app_1::app::*;
use app_1::fileserv::file_and_error_handler;
use axum::routing::post;
tracing_subscriber::fmt()
.pretty()
.with_thread_names(true)
// enable everything
.with_max_level(tracing::Level::TRACE)
// sets this to be the default, global collector for this application.
.init();
// Setting get_configuration(None) means we'll be using cargo-leptos's env values
// For deployment these variables are:
// <https://github.com/leptos-rs/start-axum#executing-a-server-on-a-remote-machine-without-the-toolchain>
// Alternately a file can be specified such as Some("Cargo.toml")
// The file would need to be included with the executable when moved to deployment
let conf = get_configuration(Some("Cargo.toml")).unwrap();
let leptos_options = conf.leptos_options;
let addr = leptos_options.site_addr;
let routes = generate_route_list(App);
// build our application with a route
let app = Router::new()
.route("/api_app1/*fn_name", post(leptos_axum::handle_server_fns))
.leptos_routes(&leptos_options, routes, App)
.fallback(file_and_error_handler)
.layer(tower_http::trace::TraceLayer::new_for_http())
.with_state(leptos_options);
let listener = tokio::net::TcpListener::bind(&addr).await.unwrap();
logging::log!("listening on http://{}", &addr);
axum::serve(listener, app.into_make_service())
.await
.unwrap();
}
#[cfg(not(feature = "ssr"))]
pub fn main() {
// no client-side main function
// unless we want this to work with e.g., Trunk for a purely client-side app
// see lib.rs for hydration function instead
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/nginx-mpmc/shared-server-1/src/lib.rs | projects/nginx-mpmc/shared-server-1/src/lib.rs | use leptos::*;
#[cfg(feature="ssr")]
#[derive(Clone)]
pub struct SharedServerState;
#[tracing::instrument]
#[server(prefix="/api_shared",endpoint="/a")]
pub async fn shared_server_function() -> Result<String,ServerFnError> {
tracing::debug!("SHARED SERVER 1");
let _ : axum::Extension<SharedServerState> = leptos_axum::extract().await?;
Ok("This message is from the shared server.".to_string())
}
//http://127.0.0.1:3002/api/shared/shared_server_function
// No hydrate function on a server function only server. | rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/nginx-mpmc/shared-server-1/src/main.rs | projects/nginx-mpmc/shared-server-1/src/main.rs | #[cfg(feature = "ssr")]
#[tokio::main]
async fn main() {
use axum::Router;
use axum::routing::post;
tracing_subscriber::fmt()
.pretty()
.with_thread_names(true)
// enable everything
.with_max_level(tracing::Level::TRACE)
// sets this to be the default, global collector for this application.
.init();
// In production you wouldn't want to use a hardcoded address like this.
let addr = "127.0.0.1:3002";
// build our application with a route
let app = Router::new()
.route("/api_shared/*fn_name", post(leptos_axum::handle_server_fns))
.layer(tower_http::trace::TraceLayer::new_for_http())
.layer(axum::Extension(shared_server::SharedServerState));
let listener = tokio::net::TcpListener::bind(addr).await.unwrap();
println!("shared server listening on http://{}", addr);
axum::serve(listener, app.into_make_service())
.await
.unwrap();
}
#[cfg(not(feature = "ssr"))]
pub fn main() {
// no client-side main function
// our server is SSR only, we have no client pair.
// We'll only ever run this with cargo run --features ssr
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/nginx-mpmc/shared-server-2/src/lib.rs | projects/nginx-mpmc/shared-server-2/src/lib.rs | use leptos::*;
#[cfg(feature="ssr")]
#[derive(Clone)]
pub struct SharedServerState2;
#[tracing::instrument]
#[server(prefix="/api_shared2",endpoint="/a")]
pub async fn shared_server_function2() -> Result<String,ServerFnError> {
tracing::debug!("SHARED SERVER 2");
let _ : axum::Extension<SharedServerState2> = leptos_axum::extract().await?;
Ok("This message is from the shared server 2.".to_string())
}
//http://127.0.0.1:3002/api/shared/shared_server_function
// No hydrate function on a server function only server. | rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/nginx-mpmc/shared-server-2/src/main.rs | projects/nginx-mpmc/shared-server-2/src/main.rs | #[cfg(feature = "ssr")]
#[tokio::main]
async fn main() {
use axum::Router;
use axum::routing::post;
// In production you wouldn't want to use a hardcoded address like this.
let addr = "127.0.0.1:3003";
// build our application with a route
let app = Router::new()
.route("/api_shared2/*fn_name", post(leptos_axum::handle_server_fns))
.layer(tower_http::trace::TraceLayer::new_for_http())
.layer(axum::Extension(shared_server_2::SharedServerState2));
let listener = tokio::net::TcpListener::bind(addr).await.unwrap();
println!("shared server listening on http://{}", addr);
axum::serve(listener, app.into_make_service())
.await
.unwrap();
}
#[cfg(not(feature = "ssr"))]
pub fn main() {
// no client-side main function
// our server is SSR only, we have no client pair.
// We'll only ever run this with cargo run --features ssr
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/openapi-openai-api-swagger-ui/src/app.rs | projects/openapi-openai-api-swagger-ui/src/app.rs | use crate::error_template::{AppError, ErrorTemplate};
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/openapi-swagger-ui.css"/>
// sets the document title
<Title text="Welcome to Leptos"/>
// content for this welcome page
<Router fallback=|| {
let mut outside_errors = Errors::default();
outside_errors.insert_with_default_key(AppError::NotFound);
view! {
<ErrorTemplate outside_errors/>
}
.into_view()
}>
<main>
<Routes>
<Route path="" view=HomePage/>
</Routes>
</main>
</Router>
}
}
/// Renders the home page of your application.
#[component]
fn HomePage() -> impl IntoView {
let hello = Action::<HelloWorld,_>::server();
view! {
<button on:click = move |_| hello.dispatch(HelloWorld{say_whut:SayHello{say:true}})>
"hello world"
</button>
<ErrorBoundary
fallback=|err| view! { <p>{format!("{err:#?}")}</p>}>
{
move || hello.value().get().map(|h|match h {
Ok(h) => h.into_view(),
err => err.into_view()
})
}
</ErrorBoundary>
<AiSayHello/>
}
}
#[cfg_attr(feature="ssr",derive(utoipa::ToSchema))]
#[derive(Debug,Copy,Clone,serde::Serialize,serde::Deserialize)]
pub struct SayHello {
say:bool,
}
// the following function comment is what our GPT will get
/// Call to say hello world, or call to not say hello world.
#[cfg_attr(feature="ssr",utoipa::path(
post,
path = "/api/hello_world",
responses(
(status = 200, description = "Hello world from server or maybe not?", body = String),
),
params(
("say_whut" = SayHello, description = "If true then say hello, if false then don't."),
)
))]
#[server(
// we need to encoude our server functions as json because that's what openai generates
input=server_fn::codec::Json,
endpoint="hello_world"
)]
pub async fn hello_world(say_whut:SayHello) -> Result<String,ServerFnError> {
if say_whut.say {
Ok("hello world".to_string())
} else {
Ok("not hello".to_string())
}
}
/// Takes a list of names
#[cfg_attr(feature="ssr",utoipa::path(
post,
path = "/api/name_list",
responses(
(status = 200, description = "The same list you got back", body = String),
),
params(
("list" = Vec<String>, description = "A list of names"),
)
))]
#[server(
input=server_fn::codec::Json,
endpoint="name_list"
)]
pub async fn name_list(list:Vec<String>) -> Result<Vec<String>,ServerFnError> {
Ok(list)
}
#[derive(Clone,Debug,PartialEq,serde::Serialize,serde::Deserialize)]
pub struct AiServerCall{
pub path:String,
pub args:String,
}
// Don't include our AI function in the OpenAPI
#[server]
pub async fn ai_msg(msg:String) -> Result<AiServerCall,ServerFnError> {
crate::open_ai::call_gpt_with_api(msg).await.get(0).cloned().ok_or(ServerFnError::new("No first message"))
}
#[component]
pub fn AiSayHello() -> impl IntoView {
let ai_msg = Action::<AiMsg, _>::server();
let result = create_rw_signal(Vec::new());
view!{
<ActionForm action=ai_msg>
<label> "Tell the AI what function to call."
<input name="msg"/>
</label>
<input type="submit"/>
</ActionForm>
<div>
{
move || if let Some(Ok(AiServerCall{path,args})) = ai_msg.value().get() {
spawn_local(async move {
let text =
reqwest::Client::new()
.post(format!("http://127.0.0.1:3000/api/{}",path))
.header("content-type","application/json")
.body(args)
.send()
.await
.unwrap()
.text()
.await
.unwrap();
result.update(|list|
list.push(
text
)
);
});
}
}
<For
each=move || result.get()
key=|_| uuid::Uuid::new_v4()
children=move |s:String| {
view! {
<p>{s}</p>
}
}
/>
</div>
}
} | rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/openapi-openai-api-swagger-ui/src/fileserv.rs | projects/openapi-openai-api-swagger-ui/src/fileserv.rs | use axum::{
body::Body,
extract::State,
response::IntoResponse,
http::{Request, Response, StatusCode, Uri},
};
use axum::response::Response as AxumResponse;
use tower::ServiceExt;
use tower_http::services::ServeDir;
use leptos::*;
use crate::app::App;
pub async fn file_and_error_handler(uri: Uri, State(options): State<LeptosOptions>, req: Request<Body>) -> AxumResponse {
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 handler = leptos_axum::render_app_to_stream(options.to_owned(), App);
handler(req).await.into_response()
}
}
async fn get_static_file(
uri: Uri,
root: &str,
) -> Result<Response<Body>, (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.into_response()),
Err(err) => Err((
StatusCode::INTERNAL_SERVER_ERROR,
format!("Something went wrong: {err}"),
)),
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/openapi-openai-api-swagger-ui/src/lib.rs | projects/openapi-openai-api-swagger-ui/src/lib.rs | pub mod app;
pub mod error_template;
#[cfg(feature = "ssr")]
pub mod fileserv;
#[cfg(feature="ssr")]
pub mod open_ai;
#[cfg(feature = "hydrate")]
#[wasm_bindgen::prelude::wasm_bindgen]
pub fn hydrate() {
use crate::app::*;
console_error_panic_hook::set_once();
leptos::mount_to_body(App);
}
#[cfg(feature="ssr")]
pub mod api_doc {
use crate::app::__path_hello_world;
use crate::app::SayHello;
use crate::app::__path_name_list;
#[derive(utoipa::OpenApi)]
#[openapi(
info(description = "My Api description"),
paths(hello_world,name_list), components(schemas(SayHello)),
)]
pub struct ApiDoc;
} | rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/openapi-openai-api-swagger-ui/src/open_ai.rs | projects/openapi-openai-api-swagger-ui/src/open_ai.rs | /*
Follows
https://cookbook.openai.com/examples/function_calling_with_an_openapi_spec
closely
*/
pub static SYSTEM_MESSAGE :&'static str = "
You are a helpful assistant.
Respond to the following prompt by using function_call and then summarize actions.
Ask for clarification if a user request is ambiguous.
";
use serde_json::Map;
use openai_dive::v1::api::Client;
use openai_dive::v1::models::Gpt4Engine;
use std::env;
use openai_dive::v1::resources::chat::{
ChatCompletionFunction, ChatCompletionParameters, ChatCompletionTool, ChatCompletionToolType, ChatMessage,
ChatMessageContent,Role,
};
use utoipa::openapi::schema::Array;
use serde_json::Value;
use utoipa::openapi::schema::SchemaType;
use utoipa::openapi::schema::Schema;
use utoipa::OpenApi;
use serde_json::json;
use utoipa::openapi::path::{PathItemType,Parameter};
use utoipa::openapi::Required;
use utoipa::openapi::schema::Object;
use utoipa::openapi::RefOr;
pub fn make_openapi_call_via_gpt(message:String) -> ChatCompletionParameters {
let docs = super::api_doc::ApiDoc::openapi();
let mut functions = vec![];
// get each path and it's path item object
for (path,path_item) in docs.paths.paths.iter(){
// all our server functions are post.
let operation = path_item.operations.get(&PathItemType::Post).expect("Expect POST op");
// This name will be given to the OpenAI API as part of our functions
let name = operation.operation_id.clone().expect("Each operation to have an operation id");
// we'll use the description
let desc = operation.description.clone().expect("Each operation to have a description, this is how GPT knows what the functiond does and it is helpful for calling it.");
let mut required_list = vec![];
let mut properties = serde_json::Map::new();
if let Some(params) = operation.parameters.clone() {
leptos::logging::log!("{params:#?}");
for Parameter{name,description,required,schema,..} in params.into_iter() {
if required == Required::True {
required_list.push(name.clone());
}
let description = description.unwrap_or_default();
if let Some(RefOr::Ref(utoipa::openapi::schema::Ref{ref_location,..})) = schema {
let schema_name = ref_location.split('/').last().expect("Expecting last after split");
let RefOr::T(schema) = docs.components
.as_ref()
.expect("components")
.schemas
.get(schema_name)
.cloned()
.expect("{schema_name} to be in components as a schema") else {panic!("expecting T")};
let mut output = Map::new();
parse_schema_into_openapi_property(name.clone(),schema,&mut output);
properties.insert(name,serde_json::Value::Object(output));
} else if let Some(RefOr::T(schema)) = schema {
let mut output = Map::new();
parse_schema_into_openapi_property(name.clone(),schema,&mut output);
properties.insert(name.clone(),serde_json::Value::Object(output));
}
}
}
let parameters = json!({
"type": "object",
"properties": properties,
"required": required_list,
});
leptos::logging::log!("{parameters}");
functions.push(
ChatCompletionFunction {
name,
description: Some(desc),
parameters,
}
)
}
ChatCompletionParameters {
model: Gpt4Engine::Gpt41106Preview.to_string(),
messages: vec![
ChatMessage {
role:Role::System,
content: ChatMessageContent::Text(SYSTEM_MESSAGE.to_string()),
..Default::default()
},
ChatMessage {
role:Role::User,
content: ChatMessageContent::Text(message),
..Default::default()
}],
tools: Some(functions.into_iter().map(|function|{
ChatCompletionTool {
r#type: ChatCompletionToolType::Function,
function,
}
}).collect::<Vec<ChatCompletionTool>>()),
..Default::default()
}
}
pub fn parse_schema_into_openapi_property(
name:String,
schema:Schema,
output: &mut serde_json::Map::<String,serde_json::Value>) {
let docs = super::api_doc::ApiDoc::openapi();
match schema {
Schema::Object(Object{
schema_type,
required,
properties,
..
}) => match schema_type{
SchemaType::Object => {
output.insert("type".to_string(),Value::String("object".to_string()));
output.insert("required".to_string(),Value::Array(required.into_iter()
.map(|s|Value::String(s))
.collect::<Vec<Value>>()));
output.insert("properties".to_string(),{
let mut map = Map::new();
for (key,val) in properties
.into_iter()
.map(|(key,val)|{
let RefOr::T(schema) = val else {panic!("expecting t")};
let mut output = Map::new();
parse_schema_into_openapi_property(name.clone(),schema,&mut output);
(key,output)
}) {
map.insert(key,Value::Object(val));
}
Value::Object(map)
});
},
SchemaType::Value => {
panic!("not expecting Value here.");
},
SchemaType::String => {
output.insert("type".to_string(),serde_json::Value::String("string".to_string()));
},
SchemaType::Integer => {
output.insert("type".to_string(),serde_json::Value::String("integer".to_string()));
},
SchemaType::Number => {
output.insert("type".to_string(),serde_json::Value::String("number".to_string()));
},
SchemaType::Boolean => {
output.insert("type".to_string(),serde_json::Value::String("boolean".to_string()));
},
SchemaType::Array => {
output.insert("type".to_string(),serde_json::Value::String("array".to_string()));
},
},
Schema::Array(Array{schema_type,items,..}) => {
match schema_type {
SchemaType::Array => {
let mut map = Map::new();
if let RefOr::Ref(utoipa::openapi::schema::Ref{ref_location,..}) = *items {
let schema_name = ref_location.split('/').last().expect("Expecting last after split");
let RefOr::T(schema) = docs.components
.as_ref()
.expect("components")
.schemas
.get(schema_name)
.cloned()
.expect("{schema_name} to be in components as a schema") else {panic!("expecting T")};
let mut map = Map::new();
parse_schema_into_openapi_property(name.clone(),schema,&mut map);
output.insert(name.clone(),serde_json::Value::Object(map));
} else if let RefOr::T(schema) = *items {
let mut map = Map::new();
parse_schema_into_openapi_property(name.clone(),schema,&mut map);
output.insert(name,serde_json::Value::Object(map));
}
},
_ => panic!("if schema is an array, then I'm expecting schema type to be an array ")
}
}
_ => panic!("I don't know how to handle this yet.")
}
}
// let docs = super::api_doc::ApiDoc::openapi();
use crate::app::AiServerCall;
pub async fn call_gpt_with_api(message:String) -> Vec<AiServerCall> {
let api_key = std::env::var("OPENAI_API_KEY").expect("$OPENAI_API_KEY is not set");
let client = Client::new(api_key);
let completion_parameters = make_openapi_call_via_gpt(message);
let result = client.chat().create(completion_parameters).await.unwrap();
let message = result.choices[0].message.clone();
let mut res = vec![];
if let Some(tool_calls) = message.clone().tool_calls {
for tool_call in tool_calls {
let name = tool_call.function.name;
let arguments = tool_call.function.arguments;
res.push(AiServerCall{
path:name,
args:arguments,
});
}
}
res
}
/*
def openapi_to_functions(openapi_spec):
functions = []
for path, methods in openapi_spec["paths"].items():
for method, spec_with_ref in methods.items():
# 1. Resolve JSON references.
spec = jsonref.replace_refs(spec_with_ref)
# 2. Extract a name for the functions.
function_name = spec.get("operationId")
# 3. Extract a description and parameters.
desc = spec.get("description") or spec.get("summary", "")
schema = {"type": "object", "properties": {}}
req_body = (
spec.get("requestBody", {})
.get("content", {})
.get("application/json", {})
.get("schema")
)
if req_body:
schema["properties"]["requestBody"] = req_body
params = spec.get("parameters", [])
if params:
param_properties = {
param["name"]: param["schema"]
for param in params
if "schema" in param
}
schema["properties"]["parameters"] = {
"type": "object",
"properties": param_properties,
}
functions.append(
{"type": "function", "function": {"name": function_name, "description": desc, "parameters": schema}}
)
return functions */ | rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/openapi-openai-api-swagger-ui/src/error_template.rs | projects/openapi-openai-api-swagger-ui/src/error_template.rs | use http::status::StatusCode;
use leptos::*;
use thiserror::Error;
#[derive(Clone, Debug, Error)]
pub enum AppError {
#[error("Not Found")]
NotFound,
}
impl AppError {
pub fn status_code(&self) -> StatusCode {
match self {
AppError::NotFound => StatusCode::NOT_FOUND,
}
}
}
// A basic function to display errors served by the error boundaries.
// Feel free to do more complicated things here than just displaying the error.
#[component]
pub fn ErrorTemplate(
#[prop(optional)] outside_errors: Option<Errors>,
#[prop(optional)] errors: Option<RwSignal<Errors>>,
) -> impl IntoView {
let errors = match outside_errors {
Some(e) => create_rw_signal(e),
None => match errors {
Some(e) => e,
None => panic!("No Errors found and we expected errors!"),
},
};
// Get Errors from Signal
let errors = errors.get_untracked();
// 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(feature = "ssr")]
{
use leptos_axum::ResponseOptions;
let response = use_context::<ResponseOptions>();
if let Some(response) = response {
response.set_status(errors[0].status_code());
}
}
view! {
<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
children=move |error| {
let error_string = error.1.to_string();
let error_code= error.1.status_code();
view! {
<h2>{error_code.to_string()}</h2>
<p>"Error: " {error_string}</p>
}
}
/>
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/openapi-openai-api-swagger-ui/src/main.rs | projects/openapi-openai-api-swagger-ui/src/main.rs | #[cfg(feature = "ssr")]
#[tokio::main]
async fn main() {
use axum::Router;
use leptos::*;
use leptos_axum::{generate_route_list, LeptosRoutes};
use openapi_swagger_ui::app::*;
use openapi_swagger_ui::api_doc::ApiDoc;
use openapi_swagger_ui::fileserv::file_and_error_handler;
use utoipa::OpenApi;
// Setting get_configuration(None) means we'll be using cargo-leptos's env values
// For deployment these variables are:
// <https://github.com/leptos-rs/start-axum#executing-a-server-on-a-remote-machine-without-the-toolchain>
// Alternately a file can be specified such as Some("Cargo.toml")
// The file would need to be included with the executable when moved to deployment
let conf = get_configuration(None).unwrap();
let leptos_options = conf.leptos_options;
let addr = leptos_options.site_addr;
let routes = generate_route_list(App);
// build our application with a route
let app = Router::new()
.leptos_routes(&leptos_options, routes, App)
.fallback(file_and_error_handler)
.merge(utoipa_swagger_ui::SwaggerUi::new("/swagger-ui")
.url("/api-docs/openapi.json", ApiDoc::openapi()))
.with_state(leptos_options);
let listener = tokio::net::TcpListener::bind(&addr).await.unwrap();
logging::log!("listening on http://{}", &addr);
axum::serve(listener, app.into_make_service())
.await
.unwrap();
}
#[cfg(not(feature = "ssr"))]
pub fn main() {
// no client-side main function
// unless we want this to work with e.g., Trunk for a purely client-side app
// see lib.rs for hydration function instead
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/ory-kratos/app/src/lib.rs | projects/ory-kratos/app/src/lib.rs | #![feature(box_patterns)]
use crate::error_template::{AppError, ErrorTemplate};
use leptos::*;
use leptos_meta::*;
use leptos_router::*;
pub mod auth;
#[cfg(feature = "ssr")]
pub mod database_calls;
pub mod error_template;
use auth::*;
pub mod posts;
pub use posts::*;
#[derive(Clone, Copy, PartialEq, Debug, Default)]
pub struct IsLoggedIn(RwSignal<bool>);
#[component]
pub fn App() -> impl IntoView {
// Provides context that manages stylesheets, titles, meta tags, etc.
provide_meta_context();
view! {
<Stylesheet id="leptos" href="/pkg/ory-auth-example.css"/>
// sets the document title
<Title text="Welcome to Leptos"/>
// content for this welcome page
<Router fallback=|| {
let mut outside_errors = Errors::default();
outside_errors.insert_with_default_key(AppError::NotFound);
view! { <ErrorTemplate outside_errors/> }.into_view()
}>
<main>
<Routes>
<Route path="" view=HomePage/>
<Route path=ids::REGISTER_ROUTE view=RegistrationPage/>
<Route path=ids::VERIFICATION_ROUTE view=VerificationPage/>
<Route path=ids::LOGIN_ROUTE view=LoginPage/>
<Route path=ids::KRATOS_ERROR_ROUTE view=KratosErrorPage/>
<Route path=ids::RECOVERY_ROUTE view=RecoveryPage/>
<Route path=ids::SETTINGS_ROUTE view=SettingsPage/>
</Routes>
</main>
</Router>
}
}
/// Renders the home page of your application.
#[component]
fn HomePage() -> impl IntoView {
let clear_cookies = Action::<ClearCookies, _>::server();
view! {
<h1>"Welcome to Leptos!"</h1>
<div>
<a href=ids::REGISTER_ROUTE id=ids::REGISTER_BUTTON_ID>Register</a>
</div>
<div>
<a href=ids::LOGIN_ROUTE id=ids::LOGIN_BUTTON_ID>"Login"</a>
</div>
<div>
<LogoutButton/>
</div>
<div>
<button id=ids::CLEAR_COOKIES_BUTTON_ID
on:click=move|_|clear_cookies.dispatch(ClearCookies{})>Clear cookies </button>
</div>
<div>
<HasSession/>
</div>
<div>
<PostPage/>
</div>
<div>
<a href=ids::RECOVERY_ROUTE id=ids::RECOVER_EMAIL_BUTTON_ID>"Recovery Email"</a>
</div>
<div>
<a href=ids::SETTINGS_ROUTE>"Settings"</a>
</div>
}
}
#[cfg(feature = "ssr")]
pub async fn clear_cookies_inner() -> Result<(), ServerFnError> {
let opts = expect_context::<leptos_axum::ResponseOptions>();
let cookie_jar = leptos_axum::extract::<axum_extra::extract::CookieJar>().await?;
for cookie in cookie_jar.iter() {
let mut cookie = cookie.clone();
cookie.set_expires(
time::OffsetDateTime::now_utc()
.checked_sub(time::Duration::hours(24 * 356 * 10))
.unwrap(),
);
cookie.set_max_age(time::Duration::seconds(0));
cookie.set_path("/");
// To clear an http only cookie, one must set an http only cookie.
cookie.set_http_only(true);
cookie.set_secure(true);
let cookie = cookie.to_string();
opts.append_header(
axum::http::HeaderName::from_static("set-cookie"),
axum::http::HeaderValue::from_str(&cookie)?,
);
}
Ok(())
}
#[tracing::instrument(ret)]
#[server]
pub async fn clear_cookies() -> Result<(), ServerFnError> {
clear_cookies_inner().await?;
Ok(())
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/ory-kratos/app/src/error_template.rs | projects/ory-kratos/app/src/error_template.rs | use cfg_if::cfg_if;
use http::status::StatusCode;
use leptos::*;
#[cfg(feature = "ssr")]
use leptos_axum::ResponseOptions;
use thiserror::Error;
#[derive(Clone, Debug, Error)]
pub enum AppError {
#[error("Not Found")]
NotFound,
}
impl AppError {
pub fn status_code(&self) -> StatusCode {
match self {
AppError::NotFound => StatusCode::NOT_FOUND,
}
}
}
// A basic function to display errors served by the error boundaries.
// Feel free to do more complicated things here than just displaying the error.
#[component]
pub fn ErrorTemplate(
#[prop(optional)] outside_errors: Option<Errors>,
#[prop(optional)] errors: Option<RwSignal<Errors>>,
) -> impl IntoView {
let basic_err_msg = if let Some(errors_sig) = errors {
format!("{:#?}", errors_sig.get_untracked())
} else {
"No errors produced by signal".to_string()
};
let errors = match outside_errors {
Some(e) => create_rw_signal(e),
None => match errors {
Some(e) => e,
None => panic!("No Errors found and we expected errors!"),
},
};
// Get Errors from Signal
let errors = errors.get_untracked();
// 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>();
if let Some(response) = response {
if let Some(error) = errors.get(0) {
response.set_status(error.status_code());
} else {
response.set_status(StatusCode::INTERNAL_SERVER_ERROR)
}
}
}}
view! {
<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
children=move |error| {
let error_string = error.1.to_string();
let error_code = error.1.status_code();
view! {
<h2>{error_code.to_string()}</h2>
<p >"Error: " {error_string}</p>
}
}
/>
<p id=ids::ERROR_ERROR_ID>{basic_err_msg}</p>
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/ory-kratos/app/src/database_calls.rs | projects/ory-kratos/app/src/database_calls.rs | use leptos::ServerFnError;
use serde::{Deserialize, Serialize};
use sqlx::{sqlite::SqlitePool, FromRow};
// This will just map into ServerFnError when we call it in our serverfunctions with ? error handling
use sqlx::Error;
use crate::posts_page::PostData;
#[tracing::instrument(err)]
pub async fn create_user(
pool: &SqlitePool,
identity_id: &String,
email: &String,
) -> Result<(), Error> {
let id = uuid::Uuid::new_v4().to_string();
sqlx::query!(
"INSERT INTO users (user_id,identity_id,email) VALUES (?,?,?)",
id,
identity_id,
email
)
.execute(pool)
.await?;
Ok(())
}
/// Returns the POST ROW
#[tracing::instrument(ret)]
pub async fn create_post(
pool: &SqlitePool,
user_id: &String,
content: &String,
) -> Result<PostData, Error> {
let id = uuid::Uuid::new_v4().to_string();
sqlx::query_as!(
PostData,
"INSERT INTO posts (post_id,user_id,content) VALUES (?,?,?) RETURNING *",
id,
user_id,
content
)
.fetch_one(pool)
.await
}
#[tracing::instrument(ret)]
pub async fn edit_post(
pool: &SqlitePool,
post_id: &String,
content: &String,
user_id: &String,
) -> Result<(), Error> {
sqlx::query!(
"
UPDATE posts
SET content = ?
WHERE post_id = ?
AND EXISTS (
SELECT 1
FROM post_permissions
WHERE post_permissions.post_id = posts.post_id
AND post_permissions.user_id = ?
AND post_permissions.write = TRUE
)",
content,
post_id,
user_id
)
.execute(pool)
.await?;
Ok(())
}
#[tracing::instrument(ret)]
pub async fn delete_post(pool: &SqlitePool, post_id: &String) -> Result<(), Error> {
sqlx::query!("DELETE FROM posts where post_id = ?", post_id)
.execute(pool)
.await?;
Ok(())
}
#[tracing::instrument(ret)]
pub async fn list_users(pool: &SqlitePool) -> Result<Vec<UserRow>, Error> {
sqlx::query_as::<_, UserRow>("SELECT user_id, identity_id FROM users")
.fetch_all(pool)
.await
}
#[tracing::instrument(ret)]
pub async fn read_user(pool: &SqlitePool, user_id: &String) -> Result<UserRow, Error> {
sqlx::query_as::<_, UserRow>("SELECT * FROM users WHERE user_id = ?")
.bind(user_id)
.fetch_one(pool)
.await
}
#[tracing::instrument(ret)]
pub async fn read_user_by_identity_id(
pool: &SqlitePool,
identity_id: &String,
) -> Result<UserRow, Error> {
sqlx::query_as::<_, UserRow>("SELECT * FROM users WHERE identity_id = ?")
.bind(identity_id)
.fetch_one(pool)
.await
}
#[tracing::instrument(ret)]
pub async fn read_user_by_email(pool: &SqlitePool, email: &String) -> Result<UserRow, Error> {
sqlx::query_as::<_, UserRow>("SELECT * FROM users WHERE email = ?")
.bind(email)
.fetch_one(pool)
.await
}
#[tracing::instrument(ret)]
pub async fn list_posts(pool: &SqlitePool, user_id: &String) -> Result<Vec<PostData>, Error> {
sqlx::query_as::<_, PostData>(
"
SELECT posts.*
FROM posts
JOIN post_permissions ON posts.post_id = post_permissions.post_id
AND post_permissions.user_id = ?
WHERE post_permissions.read = TRUE
",
)
.bind(user_id)
.fetch_all(pool)
.await
}
#[tracing::instrument(ret)]
pub async fn update_post_permission(
pool: &SqlitePool,
post_id: &String,
user_id: &String,
PostPermission {
read,
write,
delete,
}: PostPermission,
) -> Result<(), Error> {
sqlx::query!(
"
INSERT INTO post_permissions (post_id, user_id, read, write, `delete`)
VALUES (?, ?, ?, ?, ?)
ON CONFLICT (post_id, user_id) DO UPDATE SET
read = excluded.read,
write = excluded.write,
`delete` = excluded.`delete`;
",
post_id,
user_id,
read,
write,
delete
)
.execute(pool)
.await?;
Ok(())
}
#[tracing::instrument(ret)]
pub async fn create_post_permissions(
pool: &SqlitePool,
post_id: &String,
user_id: &String,
PostPermission {
read,
write,
delete,
}: PostPermission,
) -> Result<(), Error> {
sqlx::query!(
"INSERT INTO post_permissions (post_id,user_id,read,write,`delete`) VALUES (?,?,?,?,?)",
post_id,
user_id,
read,
write,
delete
)
.execute(pool)
.await?;
Ok(())
}
#[derive(Debug, PartialEq, Clone, Copy, Default)]
pub struct PostPermission {
pub read: bool,
pub write: bool,
pub delete: bool,
}
impl PostPermission {
#[tracing::instrument(ret)]
pub async fn from_db_call(
pool: &SqlitePool,
user_id: &String,
post_id: &String,
) -> Result<Self, Error> {
if let Ok(row) = sqlx::query_as!(
PostPermissionRow,
"SELECT * FROM post_permissions WHERE post_id = ? AND user_id = ?",
post_id,
user_id
)
.fetch_one(pool)
.await
{
Ok(Self::from(row))
} else {
Ok(Self::default())
}
}
pub fn new_full() -> Self {
Self {
read: true,
write: true,
delete: true,
}
}
pub fn is_full(&self) -> Result<(), ServerFnError> {
if &Self::new_full() != self {
Err(ServerFnError::new("Unauthorized, not full permissions. "))
} else {
Ok(())
}
}
pub fn can_read(&self) -> Result<(), ServerFnError> {
if !self.read {
Err(ServerFnError::new("Unauthorized to read"))
} else {
Ok(())
}
}
pub fn can_write(&self) -> Result<(), ServerFnError> {
if !self.write {
Err(ServerFnError::new("Unauthorized to write"))
} else {
Ok(())
}
}
pub fn can_delete(&self) -> Result<(), ServerFnError> {
if !self.delete {
Err(ServerFnError::new("Unauthorized to delete"))
} else {
Ok(())
}
}
}
impl From<PostPermissionRow> for PostPermission {
fn from(value: PostPermissionRow) -> Self {
Self {
read: value.read,
write: value.write,
delete: value.delete,
}
}
}
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone, FromRow)]
pub struct PostPermissionRow {
pub post_id: String,
pub user_id: String,
pub read: bool,
pub write: bool,
pub delete: bool,
}
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone, FromRow)]
pub struct UserRow {
pub user_id: String,
pub identity_id: String,
pub email: String,
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/ory-kratos/app/src/auth/settings.rs | projects/ory-kratos/app/src/auth/settings.rs | use std::collections::HashMap;
use super::*;
use ory_kratos_client::models::{SettingsFlow, UiContainer, UiText};
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
pub struct ViewableSettingsFlow(SettingsFlow);
impl IntoView for ViewableSettingsFlow {
fn into_view(self) -> View {
format!("{self:#?}").into_view()
}
}
#[tracing::instrument(ret)]
#[server]
pub async fn init_settings_flow(
flow_id: Option<String>,
) -> Result<ViewableSettingsFlow, ServerFnError> {
use reqwest::StatusCode;
let cookie_jar = leptos_axum::extract::<axum_extra::extract::CookieJar>().await?;
let session_cookie = cookie_jar
.iter()
.filter_map(|cookie| {
if cookie.name().contains("ory_kratos_session") {
Some(format!("{}={}", cookie.name(), cookie.value()))
} else {
None
}
})
.next()
.ok_or(ServerFnError::new("Expecting session cookie"))?;
let csrf_token = cookie_jar
.iter()
.filter_map(|cookie| {
if cookie.name().contains("csrf_token") {
Some(format!("{}={}", cookie.name(), cookie.value()))
} else {
None
}
})
.next()
.ok_or(ServerFnError::new("Expecting csrf token cookie."))?;
let client = reqwest::ClientBuilder::new()
.cookie_store(true)
.redirect(reqwest::redirect::Policy::none())
.build()?;
let opts = expect_context::<leptos_axum::ResponseOptions>();
opts.insert_header(
axum::http::HeaderName::from_static("cache-control"),
axum::http::HeaderValue::from_str("private, no-cache, no-store, must-revalidate")?,
);
if let Some(flow_id) = flow_id {
// use flow id to get pre-existing session flow
let resp = client
.get("http://127.0.0.1:4433/self-service/settings/flows")
.query(&[("id", flow_id)])
.header("accept", "application/json")
.header("cookie", format!("{}; {}",csrf_token,session_cookie))
.send()
.await?;
/*let cookie = resp
.headers()
.get("set-cookie")
.ok_or(ServerFnError::new("Expecting a cookie"))?
.to_str()?;
tracing::error!("set cookie init {cookie}");
let opts = expect_context::<leptos_axum::ResponseOptions>();
opts.append_header(
axum::http::HeaderName::from_static("set-cookie"),
axum::http::HeaderValue::from_str(cookie)?,
);*/
// expecting 200:settingsflow ok 401,403,404,410:errorGeneric
let status = resp.status();
if status == StatusCode::OK {
let flow = resp.json::<SettingsFlow>().await?;
Ok(ViewableSettingsFlow(flow))
} else if status == StatusCode::UNAUTHORIZED
|| status == StatusCode::FORBIDDEN
|| status == StatusCode::NOT_FOUND
|| status == StatusCode::GONE
{
// 401 should really redirect to login form...
let err = resp
.json::<ory_kratos_client::models::ErrorGeneric>()
.await?;
Err(ServerFnError::new(format!("{err:#?}")))
} else {
tracing::error!("UHHANDLED STATUS : {status}");
Err(ServerFnError::new("This is a helpful error message."))
}
} else {
// create a new flow
let resp = client
.get("http://127.0.0.1:4433/self-service/settings/browser")
.header("accept", "application/json")
.header("cookie", format!("{}; {}",csrf_token,session_cookie))
.send()
.await?;
if resp.headers().get_all("set-cookie").iter().count() == 0 {
tracing::error!("init set set-cookie is empty");
}
let cookie = resp
.headers()
.get("set-cookie")
.ok_or(ServerFnError::new("Expecting a cookie"))?
.to_str()?;
let opts = expect_context::<leptos_axum::ResponseOptions>();
opts.append_header(
axum::http::HeaderName::from_static("set-cookie"),
axum::http::HeaderValue::from_str(cookie)?,
);
// expecting 200:settingsflow ok 400,401,403:errorGeneric
let status = resp.status();
if status == StatusCode::OK {
let flow = resp.json::<SettingsFlow>().await?;
Ok(ViewableSettingsFlow(flow))
} else if status == StatusCode::BAD_REQUEST
|| status == StatusCode::UNAUTHORIZED
|| status == StatusCode::FORBIDDEN
{
let err = resp
.json::<ory_kratos_client::models::ErrorGeneric>()
.await?;
Err(ServerFnError::new(format!("{err:#?}")))
} else {
tracing::error!("UHHANDLED STATUS : {status}");
Err(ServerFnError::new("This is a helpful error message."))
}
}
}
#[tracing::instrument(ret)]
#[server]
pub async fn update_settings(
flow_id: String,
mut body: HashMap<String, String>,
) -> Result<ViewableSettingsFlow, ServerFnError> {
use ory_kratos_client::models::{
ErrorBrowserLocationChangeRequired, ErrorGeneric, GenericError,
};
use reqwest::StatusCode;
let session = leptos_axum::extract::<extractors::ExtractSession>().await?.0;
tracing::error!("{session:#?}");
let action = body
.remove("action")
.ok_or(ServerFnError::new("Can't find action on body."))?;
let cookie_jar = leptos_axum::extract::<axum_extra::extract::CookieJar>().await?;
let csrf_cookie = cookie_jar
.iter()
.filter(|cookie| cookie.name().contains("csrf_token"))
.next()
.ok_or(ServerFnError::new(
"Expecting a csrf_token cookie to already be set if fetching a pre-existing flow",
))?;
let ory_kratos_session = cookie_jar
.get("ory_kratos_session")
.ok_or(ServerFnError::new(
"No `ory_kratos_session` cookie found. Logout shouldn't be visible.",
))?;
let client = reqwest::ClientBuilder::new()
.redirect(reqwest::redirect::Policy::none())
.build()?;
let req = client
.post(&action)
.header("accept", "application/json")
.header("cookie",format!("{}={}",csrf_cookie.name(),csrf_cookie.value()))
.header("cookie",format!("{}={}",ory_kratos_session.name(),ory_kratos_session.value()))
.json(&body)
.build()?;
tracing::error!("{req:#?}");
let resp = client.execute(req).await?;
let opts = expect_context::<leptos_axum::ResponseOptions>();
opts.insert_header(
axum::http::HeaderName::from_static("cache-control"),
axum::http::HeaderValue::from_str("private, no-cache, no-store, must-revalidate")?,
);
if resp.headers().get_all("set-cookie").iter().count() == 0 {
tracing::error!("update set-cookie is empty");
}
for value in resp.headers().get_all("set-cookie").iter() {
tracing::error!("update set cookie {value:#?}");
opts.append_header(
axum::http::HeaderName::from_static("set-cookie"),
axum::http::HeaderValue::from_str(value.to_str()?)?,
);
}
// https://www.ory.sh/docs/reference/api#tag/frontend/operation/updateSettingsFlow
// expecting 400,200:settingsflow ok 401,403,404,410:errorGeneric 422:ErrorBrowserLocationChangeRequired
let status = resp.status();
if status == StatusCode::OK || status == StatusCode::BAD_REQUEST {
let flow = resp.json::<SettingsFlow>().await?;
Ok(ViewableSettingsFlow(flow))
} else if status == StatusCode::UNAUTHORIZED
|| status == StatusCode::FORBIDDEN
|| status == StatusCode::NOT_FOUND
|| status == StatusCode::GONE
{
/*
let ErrorGeneric {
error: box GenericError { id, message, .. },
} = resp.json::<ErrorGeneric>().await?;
if let Some(id) = id {
match id.as_str() {
"session_refresh_required" =>
/*
session_refresh_required: The identity requested to change something that needs a privileged session.
Redirect the identity to the login init endpoint with
query parameters ?refresh=true&return_to=<the-current-browser-url>,
or initiate a refresh login flow otherwise.
*/
{}
"security_csrf_violation" =>
/*
Unable to fetch the flow because a CSRF violation occurred.
*/
{}
"session_inactive" =>
/*
No Ory Session was found - sign in a user first.
*/
{}
"security_identity_mismatch" =>
/*
The flow was interrupted with session_refresh_required
but apparently some other identity logged in instead.
or
The requested ?return_to address is not allowed to be used.
Adjust this in the configuration!
?
*/
{}
"browser_location_change_required" =>
/*
Usually sent when an AJAX request indicates that the browser
needs to open a specific URL. Most likely used in Social Sign In flows.
*/
{}
_ => {}
}
}
*/
let err = resp.json::<ErrorGeneric>().await?;
let err = format!("{err:#?}");
Err(ServerFnError::new(err))
} else if status == StatusCode::UNPROCESSABLE_ENTITY {
let body = resp.json::<ErrorBrowserLocationChangeRequired>().await?;
tracing::error!("{body:#?}");
Err(ServerFnError::new("Unprocessable."))
} else {
tracing::error!("UHHANDLED STATUS : {status}");
Err(ServerFnError::new("This is a helpful error message."))
}
}
#[component]
pub fn SettingsPage() -> impl IntoView {
// get flow id from url
// if flow id doesn't exist we create a settings flow
// otherwise we fetch the settings flow with the flow id
// we update the settings page with the ui nodes
// we handle update settings
// if we are not logged in we'll be redirect to a login page
let init_settings_flow_resource = create_local_resource(
// use untracked here because we don't expect the url to change after resource has been fetched.
|| use_query_map().get_untracked().get("flow").cloned(),
|flow_id| init_settings_flow(flow_id),
);
let update_settings_action = Action::<UpdateSettings, _>::server();
let flow = Signal::derive(move || {
if let Some(flow) = update_settings_action.value().get() {
Some(flow)
} else {
init_settings_flow_resource.get()
}
});
let body = create_rw_signal(HashMap::new());
view! {
<Suspense fallback=||"loading settings...".into_view()>
<ErrorBoundary fallback=|errors|view!{<ErrorTemplate errors/>}>
{
move || flow.get().map(|resp|
match resp {
Ok(
ViewableSettingsFlow(SettingsFlow{id,ui:box UiContainer{nodes,action,messages,..},..})
) => {
let form_inner_html = nodes.into_iter().map(|node|kratos_html(node,body)).collect_view();
body.update(move|map|{_=map.insert(String::from("action"),action);});
let id = create_rw_signal(id);
view!{
<form id=ids::SETTINGS_FORM_ID
on:submit=move|e|{
e.prevent_default();
e.stop_propagation();
update_settings_action.dispatch(UpdateSettings{flow_id:id.get_untracked(),body:body.get_untracked()});
}>
{form_inner_html}
{messages.map(|messages|{
view!{
<For
each=move || messages.clone().into_iter()
key=|text| text.id
children=move |text: UiText| {
view! {
<p id=text.id>{text.text}</p>
}
}
/>
}
}).unwrap_or_default()}
</form>
}.into_view()
},
err => err.into_view()
})
}
</ErrorBoundary>
</Suspense>
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/ory-kratos/app/src/auth/extractors.rs | projects/ory-kratos/app/src/auth/extractors.rs | use axum::{async_trait, extract::FromRequestParts, RequestPartsExt};
use axum_extra::extract::CookieJar;
use http::request::Parts;
use ory_kratos_client::models::session::Session;
use sqlx::SqlitePool;
use crate::database_calls::UserRow;
#[derive(Clone, Debug, PartialEq)]
pub struct ExtractSession(pub Session);
#[async_trait]
impl<S> FromRequestParts<S> for ExtractSession
where
S: Send + Sync,
{
type Rejection = String;
#[tracing::instrument(err(Debug), skip_all)]
async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
let cookie_jar = parts.extract::<CookieJar>().await.unwrap();
let csrf_cookie = cookie_jar
.iter()
.filter(|cookie| cookie.name().contains("csrf_token"))
.next()
.ok_or(
"Expecting a csrf_token cookie to already be set if fetching a pre-existing flow"
.to_string(),
)?;
let session_cookie = cookie_jar
.get("ory_kratos_session")
.ok_or("Ory Kratos Session cookie does not exist.".to_string())?;
let client = reqwest::ClientBuilder::new()
.redirect(reqwest::redirect::Policy::none())
.build()
.unwrap();
let resp = client
.get("http://127.0.0.1:4433/sessions/whoami")
.header("accept", "application/json")
.header(
"cookie",
format!("{}={}", csrf_cookie.name(), csrf_cookie.value()),
)
.header(
"cookie",
format!("{}={}", session_cookie.name(), session_cookie.value()),
)
.send()
.await
.map_err(|err| format!("Error sending resp to whoami err:{:#?}", err).to_string())?;
let session = resp
.json::<Session>()
.await
.map_err(|err| format!("Error getting json from body err:{:#?}", err).to_string())?;
Ok(Self(session))
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct ExtractUserRow(pub UserRow);
#[async_trait]
impl<S> FromRequestParts<S> for ExtractUserRow
where
S: Send + Sync,
{
type Rejection = String;
#[tracing::instrument(err(Debug), skip_all)]
async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
let identity_id = parts
.extract::<ExtractSession>()
.await?
.0
.identity
.ok_or("No identity")?
.id;
let pool = parts
.extract::<axum::Extension<SqlitePool>>()
.await
.map_err(|err| format!("{err:#?}"))?
.0;
let user = crate::database_calls::read_user_by_identity_id(&pool, &identity_id)
.await
.map_err(|err| format!("{err:#?}"))?;
Ok(Self(user))
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/ory-kratos/app/src/auth/session.rs | projects/ory-kratos/app/src/auth/session.rs | use super::*;
use ory_kratos_client::models::session::Session;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ViewableSession(pub Session);
impl IntoView for ViewableSession {
fn into_view(self) -> View {
format!("{:#?}", self).into_view()
}
}
#[tracing::instrument]
#[server]
pub async fn session_who_am_i() -> Result<ViewableSession, ServerFnError> {
use self::extractors::ExtractSession;
let session = leptos_axum::extract::<ExtractSession>().await?.0;
Ok(ViewableSession(session))
}
#[component]
pub fn HasSession() -> impl IntoView {
let check_session = Action::<SessionWhoAmI, _>::server();
view! {
<button on:click=move|_|check_session.dispatch(SessionWhoAmI{})>
Check Session Status
<ErrorBoundary fallback=|errors|view!{<ErrorTemplate errors/>}>
{ move || check_session.value().get().map(|sesh|sesh.into_view()) }
</ErrorBoundary>
</button>
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/ory-kratos/app/src/auth/login.rs | projects/ory-kratos/app/src/auth/login.rs | use super::*;
use ory_kratos_client::models::LoginFlow;
use ory_kratos_client::models::UiContainer;
use ory_kratos_client::models::UiText;
use std::collections::HashMap;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ViewableLoginFlow(LoginFlow);
impl IntoView for ViewableLoginFlow {
fn into_view(self) -> View {
format!("{:?}", self).into_view()
}
}
#[tracing::instrument]
#[server]
pub async fn init_login() -> Result<LoginResponse, ServerFnError> {
let client = reqwest::ClientBuilder::new()
.cookie_store(true)
.redirect(reqwest::redirect::Policy::none())
.build()?;
// Get the csrf_token cookie.
let resp = client
.get("http://127.0.0.1:4433/self-service/login/browser")
.send()
.await?;
let first_cookie = resp
.cookies()
.next()
.ok_or(ServerFnError::new("Expecting a first cookie"))?;
let csrf_token = first_cookie.value();
let location = resp
.headers()
.get("Location")
.ok_or(ServerFnError::new("expecting location in headers"))?
.to_str()?;
// Parses the url and takes first query which will be flow=FLOW_ID and we get FLOW_ID at .1
let location_url = url::Url::parse(location)?;
let id = location_url
.query_pairs()
.next()
.ok_or(ServerFnError::new(
"Expecting query in location header value",
))?
.1;
let set_cookie = resp
.headers()
.get("set-cookie")
.ok_or(ServerFnError::new("expecting set-cookie in headers"))?
.to_str()?;
let flow = client
.get("http://127.0.0.1:4433/self-service/login/flows")
.query(&[("id", id)])
.header("x-csrf-token", csrf_token)
.send()
.await?
.json::<ViewableLoginFlow>()
.await?;
let opts = expect_context::<leptos_axum::ResponseOptions>();
opts.append_header(
axum::http::HeaderName::from_static("set-cookie"),
axum::http::HeaderValue::from_str(set_cookie)?,
);
Ok(LoginResponse::Flow(flow))
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum LoginResponse {
Flow(ViewableLoginFlow),
Success,
}
impl IntoView for LoginResponse {
fn into_view(self) -> View {
match self {
Self::Flow(view) => view.into_view(),
_ => ().into_view(),
}
}
}
#[tracing::instrument]
#[server]
pub async fn login(mut body: HashMap<String, String>) -> Result<LoginResponse, ServerFnError> {
use ory_kratos_client::models::error_browser_location_change_required::ErrorBrowserLocationChangeRequired;
use ory_kratos_client::models::generic_error::GenericError;
use reqwest::StatusCode;
let action = body
.remove("action")
.ok_or(ServerFnError::new("Can't find action on body."))?;
let cookie_jar = leptos_axum::extract::<axum_extra::extract::CookieJar>().await?;
let csrf_cookie = cookie_jar
.iter()
.filter(|cookie| cookie.name().contains("csrf_token"))
.next()
.ok_or(ServerFnError::new(
"Expecting a csrf_token cookie to already be set if fetching a pre-existing flow",
))?;
let client = reqwest::ClientBuilder::new()
.redirect(reqwest::redirect::Policy::none())
.build()?;
let resp = client
.post(&action)
.header("content-type", "application/json")
.header(
"cookie",
format!("{}={}", csrf_cookie.name(), csrf_cookie.value()),
)
.body(serde_json::to_string(&body)?)
.send()
.await?;
let opts = expect_context::<leptos_axum::ResponseOptions>();
opts.insert_header(
axum::http::HeaderName::from_static("cache-control"),
axum::http::HeaderValue::from_str("private, no-cache, no-store, must-revalidate")?,
);
for value in resp.headers().get_all("set-cookie").iter() {
opts.append_header(
axum::http::HeaderName::from_static("set-cookie"),
axum::http::HeaderValue::from_str(value.to_str()?)?,
);
}
if resp.status() == StatusCode::BAD_REQUEST {
Ok(LoginResponse::Flow(resp.json::<ViewableLoginFlow>().await?))
} else if resp.status() == StatusCode::OK {
// ory_kratos_session cookie set above.
Ok(LoginResponse::Success)
} else if resp.status() == StatusCode::GONE {
let err = resp.json::<GenericError>().await?;
let err = format!("{:#?}", err);
Err(ServerFnError::new(err))
} else if resp.status() == StatusCode::UNPROCESSABLE_ENTITY {
let err = resp.json::<ErrorBrowserLocationChangeRequired>().await?;
let err = format!("{:#?}", err);
Err(ServerFnError::new(err))
} else if resp.status() == StatusCode::TEMPORARY_REDIRECT {
let text = format!("{:#?}", resp);
Err(ServerFnError::new(text))
} else {
// this is a status code that isn't covered by the documentation
// https://www.ory.sh/docs/reference/api#tag/frontend/operation/updateLoginFlow
let status_code = resp.status().as_u16();
Err(ServerFnError::new(format!(
"{status_code} is not covered under the ory documentation?"
)))
}
}
#[component]
pub fn LoginPage() -> impl IntoView {
let login = Action::<Login, _>::server();
let login_flow = create_local_resource(|| (), |_| async move { init_login().await });
let login_resp = create_rw_signal(None::<Result<LoginResponse, ServerFnError>>);
// after user tries to login we update the signal resp.
create_effect(move |_| {
if let Some(resp) = login.value().get() {
login_resp.set(Some(resp))
}
});
let login_flow = Signal::derive(move || {
if let Some(resp) = login_resp.get() {
Some(resp)
} else {
login_flow.get()
}
});
let body = create_rw_signal(HashMap::new());
view! {
<Suspense fallback=||view!{Loading Login Details}>
<ErrorBoundary fallback=|errors|view!{<ErrorTemplate errors/>}>
{
move ||
login_flow.get().map(|resp|
match resp {
Ok(resp) => {
match resp {
LoginResponse::Flow(ViewableLoginFlow(LoginFlow{ui:box UiContainer{nodes,action,messages,..},..})) => {
let form_inner_html = nodes.into_iter().map(|node|kratos_html(node,body)).collect_view();
body.update(move|map|{_=map.insert(String::from("action"),action);});
view!{
<form id=ids::LOGIN_FORM_ID
on:submit=move|e|{
e.prevent_default();
e.stop_propagation();
login.dispatch(Login{body:body.get_untracked()});
}>
{form_inner_html}
{messages.map(|messages|{
view!{
<For
each=move || messages.clone().into_iter()
key=|text| text.id
children=move |text: UiText| {
view! {
<p id=text.id>{text.text}</p>
}
}
/>
}
}).unwrap_or_default()}
</form>
}.into_view()
},
LoginResponse::Success => {
view!{<Redirect path="/"/>}.into_view()
}
}
}
err => err.into_view(),
})
}
</ErrorBoundary>
</Suspense>
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/ory-kratos/app/src/auth/verification.rs | projects/ory-kratos/app/src/auth/verification.rs | use std::collections::HashMap;
use super::*;
use ory_kratos_client::models::{UiContainer, UiText, VerificationFlow};
#[cfg(feature = "ssr")]
use tracing::debug;
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ViewableVerificationFlow(VerificationFlow);
impl IntoView for ViewableVerificationFlow {
fn into_view(self) -> View {
format!("{:#?}", self.0).into_view()
}
}
// https://{project}.projects.oryapis.com/self-service/verification/flows?id={}
#[tracing::instrument]
#[server]
pub async fn init_verification(
flow_id: String,
) -> Result<Option<ViewableVerificationFlow>, ServerFnError> {
let cookie_jar = leptos_axum::extract::<axum_extra::extract::CookieJar>().await?;
let csrf_cookie = cookie_jar
.iter()
.filter(|cookie| cookie.name().contains("csrf_token"))
.next()
.ok_or(ServerFnError::new(
"Expecting a csrf_token cookie to already be set if fetching a pre-existing flow",
))?;
let client = reqwest::ClientBuilder::new()
.redirect(reqwest::redirect::Policy::none())
.build()?;
// https://www.ory.sh/docs/reference/api#tag/frontend/operation/getVerificationFlow
let resp = client
.get("http://127.0.0.1:4433/self-service/verification/flows")
.query(&[("id", flow_id)])
//.header("x-csrf-token", csrf_token)
//.header("content-type","application/json")
.header(
"cookie",
format!("{}={}", csrf_cookie.name(), csrf_cookie.value()),
)
.send()
.await?;
if resp.status().as_u16() == 403 {
debug!("{:#?}", resp.text().await?);
Ok(None)
} else {
let flow = resp.json::<ViewableVerificationFlow>().await?;
Ok(Some(flow))
}
}
// verification flow complete POST
//http://127.0.0.1:4433/self-service/verification
#[tracing::instrument]
#[server]
pub async fn verify(
mut body: HashMap<String, String>,
) -> Result<Option<ViewableVerificationFlow>, ServerFnError> {
let action = body
.remove("action")
.ok_or(ServerFnError::new("Can't find action on body."))?;
let cookie_jar = leptos_axum::extract::<axum_extra::extract::CookieJar>().await?;
let csrf_cookie = cookie_jar
.iter()
.filter(|cookie| cookie.name().contains("csrf_token"))
.next()
.ok_or(ServerFnError::new(
"Expecting a csrf_token cookie to already be set if fetching a pre-existing flow",
))?;
let client = reqwest::ClientBuilder::new()
.redirect(reqwest::redirect::Policy::none())
.build()?;
let resp = client
.post(&action)
.header("accept", "application/json")
.header(
"cookie",
format!("{}={}", csrf_cookie.name(), csrf_cookie.value()),
)
.json(&body)
.send()
.await?;
let opts = expect_context::<leptos_axum::ResponseOptions>();
opts.insert_header(
axum::http::HeaderName::from_static("cache-control"),
axum::http::HeaderValue::from_str("private, no-cache, no-store, must-revalidate")?,
);
match resp.json::<ViewableVerificationFlow>().await {
Ok(flow) => Ok(Some(flow)),
Err(_err) => Ok(None),
}
}
#[component]
pub fn VerificationPage() -> impl IntoView {
let verify = Action::<Verify, _>::server();
let params_map = use_query_map();
let init_verification = create_local_resource(
move || params_map().get("flow").cloned().unwrap_or_default(),
|flow_id| async move { init_verification(flow_id).await },
);
let verfication_resp =
create_rw_signal(None::<Result<Option<ViewableVerificationFlow>, ServerFnError>>);
create_effect(move |_| {
if let Some(resp) = verify.value().get() {
verfication_resp.set(Some(resp))
}
});
let verification_flow = Signal::derive(move || {
if let Some(flow) = verfication_resp.get() {
Some(flow)
} else {
init_verification.get()
}
});
let body = create_rw_signal(HashMap::new());
view! {
<Suspense fallback=||view!{Loading Verification Details}>
<ErrorBoundary fallback=|errors|format!("ERRORS: {:?}",errors.get_untracked()).into_view()>
{
move ||
verification_flow.get().map(|resp|{
match resp {
Ok(Some(ViewableVerificationFlow(VerificationFlow{ui:box UiContainer{nodes,messages,action,..},..}))) => {
let form_inner_html = nodes.into_iter().map(|node|kratos_html(node,body)).collect_view();
body.update(|map|{_=map.insert(String::from("action"),action);});
view!{
<form on:submit=move|e|{
e.prevent_default();
e.stop_propagation();
verify.dispatch(Verify{body:body.get_untracked()});
}
id=ids::VERIFICATION_FORM_ID
>
{form_inner_html}
{messages.map(|messages|{
view!{
<For
each=move || messages.clone().into_iter()
key=|text| text.id
children=move |text: UiText| {
view! {
<p id=text.id>{text.text}</p>
}
}
/>
}
}).unwrap_or_default()}
</form>
}.into_view()
},
err => err.into_view(),
}
})
}
</ErrorBoundary>
</Suspense>
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/ory-kratos/app/src/auth/kratos_html.rs | projects/ory-kratos/app/src/auth/kratos_html.rs | use super::*;
use ory_kratos_client::models::ui_node_attributes::UiNodeAttributes;
use ory_kratos_client::models::ui_node_attributes::UiNodeAttributesTypeEnum;
use ory_kratos_client::models::UiNode;
use ory_kratos_client::models::UiText;
use std::collections::HashMap;
/// https://www.ory.sh/docs/kratos/concepts/ui-user-interface
pub fn kratos_html(node: UiNode, body: RwSignal<HashMap<String, String>>) -> impl IntoView {
// the label that goes as the child of our label
let label_text = node.meta.label.map(|text| text.text);
// each node MAY have messages (i.e password is bad, email is wrong form etc)
let messages_html = view! {
<For
// a function that returns the items we're iterating over; a signal is fine
each=move || node.messages.clone()
// a unique key for each item
key=|ui_text| ui_text.id
// renders each item to a view
children=move |UiText { text,_type,.. }: UiText| {
// colored red, because we assume _type == error...
view!{<p style="color:red;">{text}</p>}
}
/>
};
let node_html = match *node.attributes {
UiNodeAttributes::UiNodeInputAttributes {
autocomplete,
disabled,
name,
required,
_type,
value,
// this is often empty for some reason?
label: _label,
..
} => {
let autocomplete =
autocomplete.map_or(String::new(), |t| serde_json::to_string(&t).unwrap());
let label = label_text.unwrap_or(String::from("Unlabeled Input"));
let required = required.unwrap_or_default();
let _type_str = serde_json::to_string(&_type).unwrap();
let name_clone = name.clone();
let name_clone_2 = name.clone();
let value = if let Some(serde_json::Value::String(value)) = value {
value
} else if value.is_none() {
"".to_string()
} else {
match serde_json::to_string(&value) {
Ok(value) => value,
Err(err) => {
leptos::logging::log!("ERROR: not value? {:?}", err);
"".to_string()
}
}
};
if _type == UiNodeAttributesTypeEnum::Submit {
body.update(|map| {
_ = map.insert(name.clone(), value.clone());
});
view! {
// will be something like value="password" name="method"
// or value="oidc" name="method"
<input type="hidden" value=value name=name/>
<input type="submit" value=label/>
}
.into_view()
} else if _type != UiNodeAttributesTypeEnum::Hidden {
let id = ids::match_name_to_id(name.clone());
view! {
<label>
<span>{&label}</span>
<input name=name
id=id
// we use replace here and in autocomplete because serde_json adds double quotes for some reason?
type=_type_str.replace("\"","")
value=move||body.get().get(&name_clone_2).cloned().unwrap_or_default()
autocomplete=autocomplete.replace("\"","")
disabled=disabled
required=required placeholder=label
on:input=move |ev|{
let name = name_clone.clone();
body.update(|map|{_=map.insert(name,event_target_value(&ev));})
}
/>
</label>
}
.into_view()
} else {
body.update(|map| {
_ = map.insert(name.clone(), value.clone());
});
// this expects the identifier to be an email, but it could be telephone etc so code is extra fragile
view! {<input type="hidden" value=value name=name /> }.into_view()
}
}
UiNodeAttributes::UiNodeAnchorAttributes { href, id, title } => {
let inner = title.text;
view! {<a href=href id=id>{inner}</a>}.into_view()
}
UiNodeAttributes::UiNodeImageAttributes {
height,
id,
src,
width,
} => view! {<img src=src height=height width=width id=id/>}.into_view(),
UiNodeAttributes::UiNodeScriptAttributes { .. } => view! {script not supported}.into_view(),
UiNodeAttributes::UiNodeTextAttributes {
id,
text:
box UiText {
// not sure how to make use of context yet.
context: _context,
// redundant id?
id: _id,
text,
// This could be, info, error, success. i.e context for msg responses on bad input etc
_type,
},
} => view! {<p id=id>{text}</p>}.into_view(),
};
view! {
{node_html}
{messages_html}
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/ory-kratos/app/src/auth/mod.rs | projects/ory-kratos/app/src/auth/mod.rs | use super::error_template::ErrorTemplate;
use leptos::*;
use leptos_router::*;
use leptos_meta::*;
pub mod kratos_html;
use kratos_html::kratos_html;
pub mod registration;
pub use registration::RegistrationPage;
pub mod verification;
use serde::{Deserialize, Serialize};
pub use verification::VerificationPage;
pub mod login;
pub use login::LoginPage;
pub mod session;
pub use session::HasSession;
#[cfg(feature = "ssr")]
pub mod extractors;
pub mod kratos_error;
pub use kratos_error::KratosErrorPage;
pub mod logout;
pub use logout::LogoutButton;
pub mod recovery;
pub use recovery::RecoveryPage;
pub mod settings;
pub use settings::SettingsPage;
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/ory-kratos/app/src/auth/logout.rs | projects/ory-kratos/app/src/auth/logout.rs | use super::*;
#[tracing::instrument]
#[server]
pub async fn logout() -> Result<(), ServerFnError> {
use ory_kratos_client::models::logout_flow::LogoutFlow;
use ory_kratos_client::models::ErrorGeneric;
use reqwest::StatusCode;
let cookie_jar = leptos_axum::extract::<axum_extra::extract::CookieJar>().await?;
let ory_kratos_session = cookie_jar
.get("ory_kratos_session")
.ok_or(ServerFnError::new(
"No `ory_kratos_session` cookie found. Logout shouldn't be visible.",
))?;
let client = reqwest::ClientBuilder::new()
.cookie_store(true)
.redirect(reqwest::redirect::Policy::none())
.build()?;
// get logout url
let resp = client
.get("http://127.0.0.1:4433/self-service/logout/browser")
.header(
"cookie",
format!(
"{}={}",ory_kratos_session.name(),ory_kratos_session.value()
),
)
.send()
.await?;
let status = resp.status();
if status == StatusCode::NO_CONTENT || status == StatusCode::OK {
let LogoutFlow {
logout_token,
logout_url,
} = resp.json::<LogoutFlow>().await?;
tracing::error!("token : {logout_token} url : {logout_url}");
let resp = client
.get(logout_url)
.query(&[("token", logout_token), ("return_to", "/".to_string())])
.header("accept","application/json")
.header(
"cookie",
format!(
"{}={}",
ory_kratos_session.name(),
ory_kratos_session.value()
),
)
.send()
.await?;
let status = resp.status();
if status != StatusCode::OK && status != StatusCode::NO_CONTENT{
let error = resp.json::<ErrorGeneric>().await?;
return Err(ServerFnError::new(format!("{error:#?}")));
}
// set cookies to clear on the client.
crate::clear_cookies_inner().await?;
Ok(())
} else {
let location = resp
.headers()
.get("Location")
.ok_or(ServerFnError::new("expecting location in headers"))?
.to_str()?;
// Parses the url and takes first query which will be flow=FLOW_ID and we get FLOW_ID at .1
let location_url = url::Url::parse(location)?;
tracing::debug!("{}", location_url);
let id = location_url
.query_pairs()
.next()
.ok_or(ServerFnError::new(
"Expecting query in location header value",
))?
.1;
let kratos_err = kratos_error::fetch_error(id.to_string()).await?;
//let error = resp.json::<ory_keto_client::models::ErrorGeneric>().await?;
Err(ServerFnError::new(kratos_err.to_err_msg()))
}
}
#[component]
pub fn LogoutButton() -> impl IntoView {
let logout = Action::<Logout, _>::server();
view! {
<button id=ids::LOGOUT_BUTTON_ID on:click=move|_|logout.dispatch(Logout{})>
Logout
<ErrorBoundary fallback=|errors|view!{<ErrorTemplate errors/>}>
{ move || logout.value().get().map(|resp|resp.into_view())}
</ErrorBoundary>
</button>
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/ory-kratos/app/src/auth/kratos_error.rs | projects/ory-kratos/app/src/auth/kratos_error.rs | use super::*;
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct KratosError {
code: Option<usize>,
message: Option<String>,
reason: Option<String>,
debug: Option<String>,
}
impl KratosError {
pub fn to_err_msg(self) -> String {
format!(
"{}\n{}\n{}\n{}\n",
self.code
.map(|code| code.to_string())
.unwrap_or("No Code included in error message".to_string()),
self.message
.unwrap_or("No message in Kratos Error".to_string()),
self.reason
.unwrap_or("No reason included in Kratos Error".to_string()),
self.debug
.unwrap_or("No debug included in Kratos Error".to_string())
)
}
}
impl IntoView for KratosError {
fn into_view(self) -> View {
view!{
<div>{self.code.map(|code|code.to_string()).unwrap_or("No Code included in error message".to_string())}</div>
<div>{self.message.unwrap_or("No message in Kratos Error".to_string())}</div>
<div>{self.reason.unwrap_or("No reason included in Kratos Error".to_string())}</div>
<div>{self.debug.unwrap_or("No debug included in Kratos Error".to_string())}</div>
}.into_view()
}
}
#[server]
pub async fn fetch_error(id: String) -> Result<KratosError, ServerFnError> {
use ory_kratos_client::models::flow_error::FlowError;
let client = reqwest::ClientBuilder::new()
.redirect(reqwest::redirect::Policy::none())
.build()?;
//https://www.ory.sh/docs/kratos/self-service/flows/user-facing-errors
let flow_error = client
.get("http://127.0.0.1:4433/self-service/errors")
.query(&[("id", id)])
.send()
.await?
.json::<FlowError>()
.await?;
let error = flow_error.error.ok_or(ServerFnError::new(
"Flow error does not contain an actual error. This is a server error.",
))?;
Ok(serde_json::from_value::<KratosError>(error)?)
}
#[component]
pub fn KratosErrorPage() -> impl IntoView {
let id = move || use_query_map().get().get("id").cloned().unwrap_or_default();
let fetch_error_resource = create_resource(move || id(), |id| fetch_error(id));
view! {
<Suspense fallback=||"Error loading...".into_view()>
<ErrorBoundary fallback=|errors|view!{<ErrorTemplate errors/>}>
{ move ||
fetch_error_resource.get().map(|resp| match resp {
// kratos error isn't an error type, it's just a ui/data representation of a kratos error.
Ok(kratos_error) => kratos_error.into_view(),
// notice how we don't deconstruct i.e Err(err), this will bounce up to the error boundary
server_error => server_error.into_view()
})
}
</ErrorBoundary>
</Suspense>
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/ory-kratos/app/src/auth/recovery.rs | projects/ory-kratos/app/src/auth/recovery.rs | use std::collections::HashMap;
use super::*;
use ory_kratos_client::models::{
ContinueWith, ContinueWithSettingsUiFlow, ErrorGeneric, RecoveryFlow, UiContainer, UiText,
};
/*
User clicks recover account button and is directed to the initiate recovery page
On the initiate recovery page they are asked for their email
We send an email to them with a recovery code to recover the identity
and a link to the recovery page which will prompt them for the code.
We validate the code
and we then direct them to the settings page for them to change their password.
*/
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct ViewableRecoveryFlow(RecoveryFlow);
// Implment IntoView, not because we want to use IntoView - but, just so we can use ErrorBoundary on the error.
impl IntoView for ViewableRecoveryFlow {
fn into_view(self) -> View {
format!("{:?}", self).into_view()
}
}
pub struct ViewableContinueWith(pub Vec<ContinueWith>);
impl IntoView for ViewableContinueWith {
fn into_view(self) -> View {
if let Some(first) = self.0.first() {
match first {
ContinueWith::ContinueWithSetOrySessionToken { ory_session_token } => todo!(),
ContinueWith::ContinueWithRecoveryUi { flow } => todo!(),
ContinueWith::ContinueWithSettingsUi {
flow: box ContinueWithSettingsUiFlow { id },
} => view! {<Redirect path=format!("/settings?flow={id}")/>}.into_view(),
ContinueWith::ContinueWithVerificationUi { flow } => todo!(),
}
} else {
().into_view()
}
}
}
#[tracing::instrument]
#[server]
pub async fn init_recovery_flow() -> Result<ViewableRecoveryFlow, ServerFnError> {
let client = reqwest::ClientBuilder::new()
.cookie_store(true)
.redirect(reqwest::redirect::Policy::none())
.build()?;
// Get the csrf_token cookie.
let resp = client
.get("http://127.0.0.1:4433/self-service/recovery/browser")
.header("accept", "application/json")
.send()
.await?;
let cookie = resp
.headers()
.get("set-cookie")
.ok_or(ServerFnError::new("Expecting a cookie"))?
.to_str()?;
let opts = expect_context::<leptos_axum::ResponseOptions>();
opts.append_header(
axum::http::HeaderName::from_static("set-cookie"),
axum::http::HeaderValue::from_str(cookie)?,
);
let status = resp.status();
if status == reqwest::StatusCode::OK {
let flow = resp.json::<RecoveryFlow>().await?;
Ok(ViewableRecoveryFlow(flow))
} else if status == reqwest::StatusCode::BAD_REQUEST {
let error = resp.json::<ErrorGeneric>().await?;
Err(ServerFnError::new(format!("{error:#?}")))
} else {
tracing::error!(
" UNHANDLED STATUS: {} \n text: {}",
status,
resp.text().await?
);
Err(ServerFnError::new("Developer made an oopsies."))
}
}
#[tracing::instrument(ret)]
#[server]
pub async fn process_recovery(
mut body: HashMap<String, String>,
) -> Result<ViewableRecoveryFlow, ServerFnError> {
use ory_kratos_client::models::error_browser_location_change_required::ErrorBrowserLocationChangeRequired;
use ory_kratos_client::models::generic_error::GenericError;
use reqwest::StatusCode;
let action = body
.remove("action")
.ok_or(ServerFnError::new("Can't find action on body."))?;
let cookie_jar = leptos_axum::extract::<axum_extra::extract::CookieJar>().await?;
let csrf_cookie = cookie_jar
.iter()
.filter(|cookie| cookie.name().contains("csrf_token"))
.next()
.ok_or(ServerFnError::new(
"Expecting a csrf_token cookie to already be set if fetching a pre-existing flow",
))?;
let csrf_token = csrf_cookie.value();
let client = reqwest::ClientBuilder::new()
.redirect(reqwest::redirect::Policy::none())
.build()?;
let resp = client
.post(&action)
.header("x-csrf-token", csrf_token)
.header("content-type", "application/json")
.header("accept", "application/json")
.header(
"cookie",
format!("{}={}", csrf_cookie.name(), csrf_cookie.value()),
)
.body(serde_json::to_string(&body)?)
.send()
.await?;
let opts = expect_context::<leptos_axum::ResponseOptions>();
opts.insert_header(
axum::http::HeaderName::from_static("cache-control"),
axum::http::HeaderValue::from_str("private, no-cache, no-store, must-revalidate")?,
);
for value in resp.headers().get_all("set-cookie").iter() {
opts.append_header(
axum::http::HeaderName::from_static("set-cookie"),
axum::http::HeaderValue::from_str(value.to_str()?)?,
);
}
if resp.status() == StatusCode::BAD_REQUEST || resp.status() == StatusCode::OK {
Ok(resp.json::<ViewableRecoveryFlow>().await?)
} else if resp.status() == StatusCode::SEE_OTHER {
let see_response = format!("{resp:#?}");
let resp_text = resp.text().await?;
let err = format!("Developer needs to handle 303 SEE OTHER resp : \n {see_response} \n body: \n {resp_text}");
Err(ServerFnError::new(err))
} else if resp.status() == StatusCode::GONE {
let err = resp.json::<GenericError>().await?;
let err = format!("{:#?}", err);
Err(ServerFnError::new(err))
} else if resp.status() == StatusCode::UNPROCESSABLE_ENTITY {
let err = resp.json::<ErrorBrowserLocationChangeRequired>().await?;
let err = format!("{:#?}", err);
Err(ServerFnError::new(err))
} else {
// this is a status code that isn't covered by the documentation
// https://www.ory.sh/docs/reference/api#tag/frontend/operation/updateRecoveryFlow
let status_code = resp.status().as_u16();
Err(ServerFnError::new(format!(
"{status_code} is not covered under the ory documentation?"
)))
}
}
#[component]
pub fn RecoveryPage() -> impl IntoView {
let recovery_flow = create_local_resource(|| (), |_| init_recovery_flow());
let recovery = Action::<ProcessRecovery, _>::server();
let recovery_resp = create_rw_signal(None::<Result<ViewableRecoveryFlow, ServerFnError>>);
create_effect(move |_| {
if let Some(resp) = recovery.value().get() {
recovery_resp.set(Some(resp))
}
});
let recovery_flow = Signal::derive(move || {
if let Some(resp) = recovery_resp.get() {
Some(resp)
} else {
recovery_flow.get()
}
});
let body = create_rw_signal(HashMap::new());
view! {
<Suspense fallback=||view!{}>
<ErrorBoundary fallback=|errors|view!{<ErrorTemplate errors/>}>
{
move ||
recovery_flow.get().map(|resp|
match resp {
Ok(ViewableRecoveryFlow(RecoveryFlow{
continue_with,
ui:box UiContainer{nodes,action,messages,..},..})) => {
if let Some(continue_with) = continue_with {
return ViewableContinueWith(continue_with).into_view();
}
let form_inner_html = nodes.into_iter().map(|node|kratos_html(node,body)).collect_view();
body.update(move|map|{_=map.insert(String::from("action"),action);});
view!{
<form id=ids::RECOVERY_FORM_ID
on:submit=move|e|{
if body.get().get(&String::from("code")).is_some() {
// if we have a code we need to drop the email which will be stored from earlier.
// if we include the email then ory kratos server will not try to validate the code.
// but instead send another recovery email.
body.update(move|map|{_=map.remove(&String::from("email"));});
}
e.prevent_default();
e.stop_propagation();
recovery.dispatch(ProcessRecovery{body:body.get_untracked()});
}>
{form_inner_html}
{messages.map(|messages|{
view!{
<For
each=move || messages.clone().into_iter()
key=|text| text.id
children=move |text: UiText| {
view! {
<p id=text.id>{text.text}</p>
}
}
/>
}
}).unwrap_or_default()}
</form>
}.into_view()
},
err => err.into_view(),
})
}
</ErrorBoundary>
</Suspense>
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/ory-kratos/app/src/auth/registration.rs | projects/ory-kratos/app/src/auth/registration.rs | use super::kratos_html;
use super::*;
use ory_kratos_client::models::RegistrationFlow;
use ory_kratos_client::models::UiContainer;
use ory_kratos_client::models::UiText;
use std::collections::HashMap;
#[cfg(feature = "ssr")]
use reqwest::StatusCode;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ViewableRegistrationFlow(RegistrationFlow);
impl IntoView for ViewableRegistrationFlow {
fn into_view(self) -> View {
format!("{:?}", self).into_view()
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum RegistrationResponse {
Flow(ViewableRegistrationFlow),
Success,
}
impl IntoView for RegistrationResponse {
fn into_view(self) -> View {
match self {
Self::Flow(view) => view.into_view(),
_ => ().into_view(),
}
}
}
#[tracing::instrument]
#[server]
pub async fn init_registration() -> Result<RegistrationResponse, ServerFnError> {
let client = reqwest::ClientBuilder::new()
.cookie_store(true)
.redirect(reqwest::redirect::Policy::none())
.build()?;
// Get the csrf_token cookie.
let resp = client
.get("http://127.0.0.1:4433/self-service/registration/browser")
.send()
.await?;
let first_cookie = resp
.cookies()
.filter(|c| c.name().contains("csrf_token"))
.next()
.ok_or(ServerFnError::new(
"Expecting a cookie with csrf_token in name",
))?;
let csrf_token = first_cookie.value();
let location = resp
.headers()
.get("Location")
.ok_or(ServerFnError::new("expecting location in headers"))?
.to_str()?;
// Parses the url and takes first query which will be flow=FLOW_ID and we get FLOW_ID at .1
let location_url = url::Url::parse(location)?;
let id = location_url
.query_pairs()
.next()
.ok_or(ServerFnError::new(
"Expecting query in location header value",
))?
.1;
let set_cookie = resp
.headers()
.get("set-cookie")
.ok_or(ServerFnError::new("expecting set-cookie in headers"))?
.to_str()?;
let resp = client
.get("http://127.0.0.1:4433/self-service/registration/flows")
.query(&[("id", id)])
.header("x-csrf-token", csrf_token)
.send()
.await?;
let flow = resp.json::<ViewableRegistrationFlow>().await?;
let opts = expect_context::<leptos_axum::ResponseOptions>();
opts.insert_header(
axum::http::HeaderName::from_static("cache-control"),
axum::http::HeaderValue::from_str("private, no-cache, no-store, must-revalidate")?,
);
opts.append_header(
axum::http::HeaderName::from_static("set-cookie"),
axum::http::HeaderValue::from_str(set_cookie)?,
);
Ok(RegistrationResponse::Flow(flow))
}
#[tracing::instrument(err)]
#[server]
pub async fn register(
mut body: HashMap<String, String>,
) -> Result<RegistrationResponse, ServerFnError> {
use ory_kratos_client::models::error_browser_location_change_required::ErrorBrowserLocationChangeRequired;
use ory_kratos_client::models::generic_error::GenericError;
use ory_kratos_client::models::successful_native_registration::SuccessfulNativeRegistration;
let pool = leptos_axum::extract::<axum::Extension<sqlx::SqlitePool>>().await?;
let action = body
.remove("action")
.ok_or(ServerFnError::new("Can't find action on body."))?;
let email = body
.get("traits.email")
.cloned()
.ok_or(ServerFnError::new("Can't find traits.email on body."))?;
let cookie_jar = leptos_axum::extract::<axum_extra::extract::CookieJar>().await?;
let csrf_cookie = cookie_jar
.iter()
.filter(|cookie| cookie.name().contains("csrf_token"))
.next()
.ok_or(ServerFnError::new(
"Expecting a csrf_token cookie to already be set if fetching a pre-existing flow",
))?;
let client = reqwest::ClientBuilder::new()
.redirect(reqwest::redirect::Policy::none())
.build()?;
let resp = client
.post(&action)
//.header("content-type", "application/json")
.header(
"cookie",
format!("{}={}", csrf_cookie.name(), csrf_cookie.value()),
)
.json(&body)
.send()
.await?;
let opts = expect_context::<leptos_axum::ResponseOptions>();
opts.insert_header(
axum::http::HeaderName::from_static("cache-control"),
axum::http::HeaderValue::from_str("private, no-cache, no-store, must-revalidate")?,
);
for value in resp.headers().get_all("set-cookie").iter() {
opts.append_header(
axum::http::HeaderName::from_static("set-cookie"),
axum::http::HeaderValue::from_str(value.to_str()?)?,
);
}
if resp.status() == StatusCode::BAD_REQUEST {
Ok(RegistrationResponse::Flow(
resp.json::<ViewableRegistrationFlow>().await?,
))
} else if resp.status() == StatusCode::OK {
// get identity, session, session token
let SuccessfulNativeRegistration { identity, .. } =
resp.json::<SuccessfulNativeRegistration>().await?;
let identity_id = identity.id;
crate::database_calls::create_user(&pool, &identity_id, &email).await?;
//discard all? what about session_token? I guess we aren't allowing logging in after registration without verification..
Ok(RegistrationResponse::Success)
} else if resp.status() == StatusCode::GONE {
let err = resp.json::<GenericError>().await?;
let err = format!("{:#?}", err);
Err(ServerFnError::new(err))
} else if resp.status() == StatusCode::UNPROCESSABLE_ENTITY {
let err = resp.json::<ErrorBrowserLocationChangeRequired>().await?;
let err = format!("{:#?}", err);
Err(ServerFnError::new(err))
} else if resp.status() == StatusCode::TEMPORARY_REDIRECT {
let text = format!("{:#?}", resp);
Err(ServerFnError::new(text))
} else {
// this is a status code that isn't covered by the documentation
// https://www.ory.sh/docs/reference/api#tag/frontend/operation/updateRegistrationFlow
let status_code = resp.status().as_u16();
Err(ServerFnError::new(format!(
"{status_code} is not covered under the ory documentation?"
)))
}
}
#[component]
pub fn RegistrationPage() -> impl IntoView {
let register = Action::<Register, _>::server();
// when we hit the page initiate a flow with kratos and get back data for ui renering.
let registration_flow =
create_local_resource(|| (), |_| async move { init_registration().await });
// Is none if user hasn't submitted data.
let register_resp = create_rw_signal(None::<Result<RegistrationResponse, ServerFnError>>);
// after user tries to register we update the signal resp.
create_effect(move |_| {
if let Some(resp) = register.value().get() {
register_resp.set(Some(resp))
}
});
// Merge our resource and our action results into a single signal.
// if the user hasn't tried to register yet we'll render the initial flow.
// if they have, we'll render the updated flow (including error messages etc).
let registration_flow = Signal::derive(move || {
if let Some(resp) = register_resp.get() {
Some(resp)
} else {
registration_flow.get()
}
});
// this is the body of our registration form, we don't know what the inputs are so it's a stand in for some
// json map of unknown argument length with type of string.
let body = create_rw_signal(HashMap::new());
view! {
// we'll render the fallback when the user hits the page for the first time
<Suspense fallback=||view!{Loading Registration Details}>
// if we get any errors, from either server functions we've merged we'll render them here.
<ErrorBoundary fallback=|errors|view!{<ErrorTemplate errors/>}>
{
move ||
// this is the resource XOR the results of the register action.
registration_flow.get().map(|resp|{
match resp {
// TODO add Oauth using the flow args (see type docs)
Ok(resp) => {
match resp {
RegistrationResponse::Flow(ViewableRegistrationFlow(RegistrationFlow{ui:box UiContainer{nodes,action,messages,..},..}))
=> {
let form_inner_html = nodes.into_iter().map(|node|kratos_html(node,body)).collect_view();
body.update(move|map|{_=map.insert(String::from("action"),action);});
view!{
<form
on:submit=move|e|{
e.prevent_default();
e.stop_propagation();
register.dispatch(Register{body:body.get_untracked()});
}
id=ids::REGISTRATION_FORM_ID
>
{form_inner_html}
// kratos_html renders messages for each node and these are the messages attached to the entire form.
{messages.map(|messages|{
view!{
<For
each=move || messages.clone().into_iter()
key=|text| text.id
children=move |text: UiText| {
view! {
<p id=text.id>{text.text}</p>
}
}
/>
}
}).unwrap_or_default()}
</form>
}.into_view()
},
RegistrationResponse::Success => {
view!{<div id=ids::VERIFY_EMAIL_DIV_ID>"Check Email for Verification"</div>}.into_view()
}
}
},
err => err.into_view(),
}
})
}
</ErrorBoundary>
</Suspense>
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/ory-kratos/app/src/posts/posts_page.rs | projects/ory-kratos/app/src/posts/posts_page.rs | use serde::{Deserialize, Serialize};
use super::*;
#[derive(Serialize, Deserialize, Debug, Clone)]
#[cfg_attr(feature = "ssr", derive(sqlx::FromRow))]
pub struct PostData {
pub post_id: String,
pub user_id: String,
pub content: String,
}
impl IntoView for PostData {
fn into_view(self) -> View {
view! {<Post post=self/>}
}
}
#[tracing::instrument(ret)]
#[server]
pub async fn get_post_list() -> Result<Vec<PostData>, ServerFnError> {
use crate::database_calls::list_posts;
let pool = leptos_axum::extract::<axum::Extension<sqlx::SqlitePool>>()
.await?
.0;
let user_id = leptos_axum::extract::<crate::auth::extractors::ExtractUserRow>()
.await?
.0
.user_id;
Ok(list_posts(&pool, &user_id).await?)
}
#[component]
pub fn PostPage() -> impl IntoView {
view! {
<PostsList/>
<CreatePost/>
}
}
#[component]
pub fn PostsList() -> impl IntoView {
let list_posts = Action::<GetPostList, _>::server();
view! {
<button on:click=move|_|list_posts.dispatch(GetPostList{}) id=ids::POST_SHOW_LIST_BUTTON_ID>Show List</button>
<Suspense fallback=||"Post list loading...".into_view()>
<ErrorBoundary fallback=|errors|view!{<ErrorTemplate errors/>}>
{
move || list_posts.value().get().map(|resp|
match resp {
Ok(list) => view!{
<For
each=move || list.clone()
key=|_| uuid::Uuid::new_v4()
children=move |post: PostData| {
post.into_view()
}
/>
}.into_view(),
err => err.into_view()
})
}
</ErrorBoundary>
</Suspense>
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/ory-kratos/app/src/posts/mod.rs | projects/ory-kratos/app/src/posts/mod.rs | use super::*;
mod post;
use post::Post;
pub mod posts_page;
pub use posts_page::PostPage;
mod create_posts;
use crate::posts_page::PostData;
use create_posts::CreatePost;
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/ory-kratos/app/src/posts/post.rs | projects/ory-kratos/app/src/posts/post.rs | use self::posts_page::PostData;
use super::*;
// This is the post, contains all other functionality.
#[component]
pub fn Post(post: PostData) -> impl IntoView {
let PostData {
post_id, content, ..
} = post;
view! {
<div>{content}</div>
<AddEditor post_id=post_id.clone()/>
<EditPost post_id=post_id.clone()/>
}
}
// Only the owner can add an an editor.
#[tracing::instrument(ret)]
#[server]
pub async fn server_add_editor(post_id: String, email: String) -> Result<(), ServerFnError> {
use crate::database_calls::{read_user_by_email, update_post_permission, PostPermission};
let pool: sqlx::Pool<sqlx::Sqlite> =
leptos_axum::extract::<axum::Extension<sqlx::SqlitePool>>()
.await?
.0;
let user_id = leptos_axum::extract::<crate::auth::extractors::ExtractUserRow>()
.await?
.0
.user_id;
let caller_permissions = PostPermission::from_db_call(&pool, &user_id, &post_id).await?;
caller_permissions.is_full()?;
// get other id
let user_id = read_user_by_email(&pool, &email).await?.user_id;
// make an idempotent update to the other users permissions;
let mut permissions = PostPermission::from_db_call(&pool, &post_id, &user_id).await?;
permissions.write = true;
permissions.read = true;
update_post_permission(&pool, &post_id, &user_id, permissions).await?;
Ok(())
}
#[component]
pub fn AddEditor(post_id: String) -> impl IntoView {
let add_editor = Action::<ServerAddEditor, _>::server();
view! {
<ActionForm action=add_editor>
<label value="Add Editor Email">
<input type="text" name="email" id=ids::POST_ADD_EDITOR_INPUT_ID/>
<input type="hidden" name="post_id" value=post_id/>
</label>
<input type="submit" id=ids::POST_ADD_EDITOR_SUBMIT_ID/>
</ActionForm>
<Suspense fallback=||view!{}>
<ErrorBoundary fallback=|errors|view!{<ErrorTemplate errors/>}>
{ move || add_editor.value().get()}
</ErrorBoundary>
</Suspense>
}
}
// Only the owner and editors can edit a post.
#[tracing::instrument(ret)]
#[server]
pub async fn server_edit_post(post_id: String, content: String) -> Result<(), ServerFnError> {
let pool: sqlx::Pool<sqlx::Sqlite> =
leptos_axum::extract::<axum::Extension<sqlx::SqlitePool>>()
.await?
.0;
let user_id = leptos_axum::extract::<crate::auth::extractors::ExtractUserRow>()
.await?
.0
.user_id;
crate::database_calls::edit_post(&pool, &post_id, &content, &user_id).await?;
Ok(())
}
#[component]
pub fn EditPost(post_id: String) -> impl IntoView {
let edit_post = Action::<ServerEditPost, _>::server();
view! {
<ActionForm action=edit_post>
<label value="New Content:">
<textarea name="content" id=ids::POST_EDIT_TEXT_AREA_ID/>
<input type="hidden" name="post_id" value=post_id/>
</label>
<input type="submit" id=ids::POST_EDIT_SUBMIT_ID/>
</ActionForm>
<Suspense fallback=||view!{}>
<ErrorBoundary fallback=|errors|view!{<ErrorTemplate errors/>}>
{ move || edit_post.value().get()}
</ErrorBoundary>
</Suspense>
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/ory-kratos/app/src/posts/create_posts.rs | projects/ory-kratos/app/src/posts/create_posts.rs | use super::*;
// An user can post a post. Technically all server functions are POST, so this is a Post Post Post.
#[tracing::instrument(ret)]
#[server]
pub async fn post_post(content: String) -> Result<(), ServerFnError> {
use crate::database_calls::{create_post, create_post_permissions, PostPermission};
let pool = leptos_axum::extract::<axum::Extension<sqlx::SqlitePool>>()
.await?
.0;
let user_id = leptos_axum::extract::<crate::auth::extractors::ExtractUserRow>()
.await?
.0
.user_id;
let PostData { post_id, .. } = create_post(&pool, &user_id, &content).await?;
create_post_permissions(&pool, &post_id, &user_id, PostPermission::new_full()).await?;
Ok(())
}
#[component]
pub fn CreatePost() -> impl IntoView {
let post_post = Action::<PostPost, _>::server();
view! {
<ActionForm action=post_post>
<textarea type="text" name="content" id=ids::POST_POST_TEXT_AREA_ID/>
<input type="submit" value="Post Post" id=ids::POST_POST_SUBMIT_ID/>
</ActionForm>
<Suspense fallback=move||view!{}>
<ErrorBoundary fallback=|errors|view!{<ErrorTemplate errors/>}>
{ move || post_post.value().get()}
</ErrorBoundary>
</Suspense>
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/ory-kratos/e2e/tests/app_suite.rs | projects/ory-kratos/e2e/tests/app_suite.rs | #![feature(never_type)]
mod fixtures;
use anyhow::anyhow;
use anyhow::Result;
use chromiumoxide::cdp::browser_protocol::log::EventEntryAdded;
use chromiumoxide::cdp::js_protocol::runtime::EventConsoleApiCalled;
use chromiumoxide::{
browser::{Browser, BrowserConfig},
cdp::browser_protocol::{
network::{EventRequestWillBeSent, EventResponseReceived, Request, Response},
page::NavigateParams,
},
element::Element,
page::ScreenshotParams,
Page,
};
use cucumber::World;
use futures::channel::mpsc::Sender;
use futures_util::stream::StreamExt;
use std::sync::LazyLock;
use serde::{Deserialize, Serialize};
use std::{collections::HashMap, sync::Arc, time::Duration};
use tokio::sync::RwLock;
use tokio_tungstenite::connect_async;
use uuid::Uuid;
static EMAIL_ID_MAP: LazyLock<RwLock<HashMap<String, String>>> =
LazyLock::new(|| RwLock::new(HashMap::new()));
#[derive(Clone, Debug, PartialEq)]
pub struct RequestPair {
req: Option<Request>,
redirect_resp: Option<Response>,
resp: Option<Response>,
cookies_before_request: String,
cookies_after_response: String,
ts: std::time::Instant,
}
/*
let screenshot = world
.page
.screenshot(
ScreenshotParams::builder()
.capture_beyond_viewport(true)
.full_page(true)
.build(),
)
.await
.unwrap();
world.screenshots.push(screenshot);
*/
#[derive(Clone, Debug)]
pub enum CookieEnum {
BeforeReq(String),
AfterResp(String),
}
impl RequestPair {
pub fn to_string(&self) -> String {
let (top_req, req_headers) = if let Some(req) = &self.req {
(
format!("{} : {} \n", req.method, req.url,),
format!("{} :\n{:#?} \n", req.url, req.headers),
)
} else {
("NO REQ".to_string(), "NO REQ".to_string())
};
let (top_redirect_resp, _redirect_resp_headers) = if let Some(resp) = &self.redirect_resp {
(
format!("{} : {}", resp.status, resp.url),
format!("{} :\n {:#?}", resp.url, resp.headers),
)
} else {
("".to_string(), "".to_string())
};
let (top_resp, resp_headers) = if let Some(resp) = &self.resp {
(
format!("{} : {}", resp.status, resp.url),
format!("{} :\n {:#?}", resp.url, resp.headers),
)
} else {
("NO RESP".to_string(), "NO RESP".to_string())
};
format!(
"REQ: {}\n RESP: {}\n \n REDIRECT {} \n REQ_HEADERS: {} \n REQ_COOKIES: \n{}\n RESP_HEADERS:{} \n RESP_COOKIES: \n{}\n ",
top_req, top_resp,top_redirect_resp, req_headers, self.cookies_before_request,resp_headers,self.cookies_after_response
)
}
}
#[tokio::main]
async fn main() -> Result<()> {
// create a thread and store a
// tokio-tungstenite client that connectsto http://127.0.0.1:1080/ws
// and then stores the recieved messages in a std::sync::LazyLock<RwLock<Vec<MailCrabMsg>>>
// or a custom struct that matches the body or has specific impls for verify codes, links etc.
let _ = tokio::spawn(async move {
let (mut socket, _) = connect_async(
url::Url::parse("ws://127.0.0.1:1080/ws").expect("Can't connect to case count URL"),
)
.await
.unwrap();
while let Some(msg) = socket.next().await {
if let Ok(tokio_tungstenite::tungstenite::Message::Text(text)) = msg {
let Email { id, to } = serde_json::from_str::<Email>(&text).unwrap();
let email = to[0].email.clone();
EMAIL_ID_MAP.write().await.insert(email, id.to_string());
}
}
});
AppWorld::cucumber()
.init_tracing()
.fail_on_skipped()
.max_concurrent_scenarios(1)
.fail_fast()
.before(|_feature, _rule, scenario, world| {
Box::pin(async move {
let screenshot_directory_name = format!("./screenshots/{}", scenario.name);
if let Ok(sc_dir) = std::fs::read_dir(&screenshot_directory_name) {
for file in sc_dir {
if let Ok(file) = file {
std::fs::remove_file(file.path()).unwrap();
}
}
} else {
std::fs::create_dir(&screenshot_directory_name).unwrap();
}
// take the page from world
// add network event listener, tracking requests and pairing them with responses
// store them somewhere inside of the world.
let page = world.page.clone();
let mut req_events = page
.event_listener::<EventRequestWillBeSent>()
.await
.unwrap();
let mut resp_events = page
.event_listener::<EventResponseReceived>()
.await
.unwrap();
world.page.enable_log().await.unwrap();
// get log events generated by the browser
let mut log_events = page.event_listener::<EventEntryAdded>().await.unwrap();
// get log events generated by leptos or other console.log() calls..
let mut runtime_events = page
.event_listener::<EventConsoleApiCalled>()
.await
.unwrap();
let console_logs = world.console_logs.clone();
let console_logs_2 = world.console_logs.clone();
tokio::task::spawn(async move {
while let Some(event) = log_events.next().await {
if let Some(EventEntryAdded { entry }) =
Arc::<EventEntryAdded>::into_inner(event) {
console_logs.write().await.push(format!(" {entry:#?} "));
} else {
tracing::error!("tried to into inner but none")
}
}
});
tokio::task::spawn(async move {
while let Some(event) = runtime_events.next().await {
if let Some(event) =Arc::<EventConsoleApiCalled>::into_inner(event) {
console_logs_2
.write()
.await
.push(format!(" CONSOLE_LOG: {:#?}", event.args));
} else {
tracing::error!("tried to into inner but none")
}
}
});
let (tx, mut rx) = futures::channel::mpsc::channel::<Option<CookieEnum>>(1000);
let mut tx_c = tx.clone();
let mut tx_c_2 = tx.clone();
world.cookie_sender = Some(tx);
let req_resp = world.req_resp.clone();
// Ideally you'd send the message for the Page to get the cookies from inside of the event stream loop,
// but for some reason that doesn't always work (but sometimes it does),
// but putting it in it's own thread makes it always work. Not sure why at the moment... ,
// something about async, about senders, about trying to close the browser but keeping senders around.
// we need to close the loop and drop the task to close the browser (I think)...
tokio::task::spawn(async move {
while let Some(some_request_id) = rx.next().await {
if let Some(cookie_enum) = some_request_id {
match cookie_enum {
CookieEnum::BeforeReq(req_id) => {
let cookies = page
.get_cookies()
.await
.unwrap_or_default()
.iter()
.map(|cookie| {
format!("name={}\n value={}", cookie.name, cookie.value)
})
.collect::<Vec<String>>()
.join("\n");
if let Some(thing) = req_resp
.write()
.await
.get_mut(&req_id) {
thing.cookies_before_request = cookies;
}
}
CookieEnum::AfterResp(req_id) => {
let cookies = page
.get_cookies()
.await
.unwrap_or_default()
.iter()
.map(|cookie| {
format!("name={}\n value={}", cookie.name, cookie.value)
})
.collect::<Vec<String>>()
.join("\n");
if let Some(thing) = req_resp
.write()
.await
.get_mut(&req_id) {
thing.cookies_after_response = cookies;
}
}
}
} else {
break;
}
}
});
let req_resp = world.req_resp.clone();
tokio::task::spawn(async move {
while let Some(event) = req_events.next().await {
if let Some(event) = Arc::<EventRequestWillBeSent>::into_inner(event) {
if event.request.url.contains("/pkg/") {
continue;
}
let req_id = event.request_id.inner().clone();
req_resp.write().await.insert(
req_id.clone(),
RequestPair {
req: Some(event.request),
redirect_resp: event.redirect_response,
resp: None,
cookies_before_request: "".to_string(),
cookies_after_response: "".to_string(),
ts: std::time::Instant::now(),
},
);
if let Err(msg) = tx_c.try_send(Some(CookieEnum::BeforeReq(req_id.clone()))) {
tracing::error!(" oopsies on the {msg:#?}");
}
} else {
tracing::error!("into inner err")
}
}
});
let req_resp = world.req_resp.clone();
tokio::task::spawn(async move {
while let Some(event) = resp_events.next().await {
if let Some(event) = Arc::<EventResponseReceived>::into_inner(event){
if event.response.url.contains("/pkg/") {
continue;
}
let req_id = event.request_id.inner().clone();
if let Err(msg) = tx_c_2
.try_send(Some(CookieEnum::AfterResp(req_id.clone()))) {
tracing::error!("err sending {msg:#?}");
}
if let Some(request_pair) = req_resp.write().await.get_mut(&req_id) {
request_pair.resp = Some(event.response);
} else {
req_resp.write().await.insert(
req_id.clone(),
RequestPair {
req: None,
redirect_resp: None,
resp: Some(event.response),
cookies_before_request: "No cookie?".to_string(),
cookies_after_response: "No cookie?".to_string(),
ts: std::time::Instant::now(),
},
);
}
} else {
tracing::error!(" uhh err here")
}
}
});
// We don't need to join on our join handles, they will run detached and clean up whenever.
})
})
.after(|_feature, _rule, scenario, ev, world| {
Box::pin(async move {
let screenshot_directory_name = format!("./screenshots/{}", scenario.name);
let world = world.unwrap();
// screenshot the last step
if let Ok(screenshot) = world
.page
.screenshot(
ScreenshotParams::builder()
.capture_beyond_viewport(true)
.full_page(true)
.build(),
)
.await {
world.screenshots.push(screenshot);
}
if let cucumber::event::ScenarioFinished::StepFailed(_, _, _) = ev {
// close the cookie task.
if world
.cookie_sender
.as_mut()
.unwrap()
.try_send(None).is_err() {
tracing::error!("can't close cookie sender");
}
// print any applicable screenshots (just the last one of the failed step if there was none taken during the scenario)
for (i, screenshot) in world.screenshots.iter().enumerate() {
// i.e ./screenshots/login/1.png
_ =std::fs::write(
screenshot_directory_name.clone()
+ "/"
+ i.to_string().as_str()
+ ".png",
screenshot,
);
}
// print network
let mut network_output = world
.req_resp
.read()
.await
.values()
.map(|val| val.clone())
.collect::<Vec<RequestPair>>();
network_output.sort_by(|a, b| a.ts.cmp(&b.ts));
let network_output = network_output
.into_iter()
.map(|val| val.to_string())
.collect::<Vec<String>>()
.join("\n");
_ = std::fs::write("./network_output", network_output.as_bytes());
let console_logs = world.console_logs.read().await.join("\n");
_ =std::fs::write("./console_logs", console_logs.as_bytes());
// print html
if let Ok(html) = world.page.content().await {
_ = std::fs::write("./html", html.as_bytes());
}
}
if let Err(err) = world.browser.close().await {
tracing::error!("{err:#?}");
}
if let Err(err) = world.browser.wait().await {
tracing::error!("{err:#?}");
}
})
})
.run_and_exit("./features")
.await;
Ok(())
}
#[tracing::instrument]
async fn build_browser() -> Result<Browser, Box<dyn std::error::Error>> {
let (browser, mut handler) = Browser::launch(
BrowserConfig::builder()
//.enable_request_intercept()
.disable_cache()
.request_timeout(Duration::from_secs(1))
//.with_head()
//.arg("--remote-debugging-port=9222")
.build()?,
)
.await?;
tokio::task::spawn(async move {
while let Some(h) = handler.next().await {
if h.is_err() {
tracing::info!("{h:?}");
break;
}
}
});
Ok(browser)
}
pub const HOST: &str = "https://127.0.0.1:3000";
#[derive(World)]
#[world(init = Self::new)]
pub struct AppWorld {
pub browser: Browser,
pub page: Page,
pub req_resp: Arc<RwLock<HashMap<String, RequestPair>>>,
pub clipboard: HashMap<&'static str, String>,
pub cookie_sender: Option<Sender<Option<CookieEnum>>>,
pub screenshots: Vec<Vec<u8>>,
pub console_logs: Arc<RwLock<Vec<String>>>,
}
impl std::fmt::Debug for AppWorld {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("AppWorld").finish()
}
}
impl AppWorld {
async fn new() -> Result<Self, anyhow::Error> {
let browser = build_browser().await.unwrap();
let page = browser.new_page("about:blank").await?;
Ok(Self {
browser,
page,
req_resp: Arc::new(RwLock::new(HashMap::new())),
clipboard: HashMap::new(),
cookie_sender: None,
screenshots: Vec::new(),
console_logs: Arc::new(RwLock::new(Vec::new())),
})
}
pub async fn errors(&mut self) -> Result<()> {
if let Ok(error) = self.find(ids::ERROR_ERROR_ID).await {
Err(anyhow!("{}", error.inner_text().await?.unwrap_or(String::from("no error in inner template?"))))
} else {
Ok(())
}
}
pub async fn find(&self, id: &'static str) -> Result<Element> {
for _ in 0..4 {
if let Ok(el) = self.page.find_element(format!("#{id}")).await {
return Ok(el);
}
crate::fixtures::wait().await;
}
Err(anyhow!("Can't find {id}"))
}
pub async fn find_submit(&mut self) -> Result<Element> {
for _ in 0..4 {
if let Ok(el) = self.page.find_element(format!("input[type=submit]")).await {
return Ok(el);
}
crate::fixtures::wait().await;
}
Err(anyhow!("Can't find input type=submit"))
}
/*pub async fn find_all(&mut self, id: &'static str) -> Result<ElementList> {
Ok(ElementList(
self.page.find_elements(format!("#{id}")).await?,
))
}*/
pub async fn goto_url(&mut self, url: &str) -> Result<()> {
self.page
.goto(
NavigateParams::builder()
.url(url)
.build()
.map_err(|err| anyhow!(err))?,
)
.await?
.wait_for_navigation()
.await?;
self.screenshot().await?;
Ok(())
}
pub async fn goto_path(&mut self, path: &str) -> Result<()> {
let url = format!("{}{}", HOST, path);
self.page
.goto(
NavigateParams::builder()
.url(url)
.build()
.map_err(|err| anyhow!(err))?,
)
.await?;
self.screenshot().await?;
Ok(())
}
pub async fn screenshot(&mut self) -> Result<()> {
let sc = self.page.screenshot(ScreenshotParams::default()).await?;
self.screenshots.push(sc);
Ok(())
}
pub async fn set_field<S: AsRef<str> + std::fmt::Display>(
&mut self,
id: &'static str,
value: S,
) -> Result<()> {
let element = self.find(id).await?;
element.focus().await?.type_str(value).await?;
self.screenshot().await?;
Ok(())
}
pub async fn click(&mut self, id: &'static str) -> Result<()> {
self.find(id).await?.click().await?;
Ok(())
}
#[tracing::instrument(err)]
pub async fn submit(&mut self) -> Result<()> {
self.screenshot().await?;
self.find_submit().await?.click().await?;
Ok(())
}
pub async fn find_text(&self, text: String) -> Result<Element> {
let selector: String = format!("//*[contains(text(), '{text}') or @*='{text}']");
let mut count = 0;
loop {
let result = self.page.find_xpath(&selector).await;
if result.is_err() && count < 4 {
count += 1;
crate::fixtures::wait().await;
} else {
let result = result?;
return Ok(result);
}
}
}
pub async fn url_contains(&self, s: &'static str) -> Result<()> {
if let Some(current) = self.page.url().await? {
if !current.contains(s) {
return Err(anyhow!("{current} does not contains {s}"));
}
} else {
return Err(anyhow!("NO CURRENT URL FOUND"));
}
Ok(())
}
pub async fn verify_route(&self, path: &'static str) -> Result<()> {
let url = format!("{}{}", HOST, path);
if let Some(current) = self.page.url().await? {
if current != url {
return Err(anyhow!(
"EXPECTING ROUTE: {path}\n but FOUND:\n {current:#?}"
));
}
} else {
return Err(anyhow!(
"EXPECTING ROUTE: {path}\n but NO CURRENT URL FOUND"
));
}
Ok(())
}
}
/*
#[derive(Debug)]
pub struct ElementList(Vec<Element>);
impl ElementList {
/// iterates over elements, finds first element whose text (as rendered) contains text given as function's argument.
pub async fn find_by_text(&self,text:&'static str) -> Result<Element> {
for element in self.0.iter() {
if let Ok(Some(inner_text)) = element.inner_text().await {
if inner_text.contains(text) {
return Ok(element);
}
}
}
Err(anyhow!(format!("given text {} no element found",text)))
}
}*/
#[derive(Serialize, Deserialize, Debug)]
struct Email {
id: Uuid,
to: Vec<Recipient>,
}
#[derive(Serialize, Deserialize, Debug)]
struct Recipient {
name: Option<String>,
email: String,
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/ory-kratos/e2e/tests/fixtures/mod.rs | projects/ory-kratos/e2e/tests/fixtures/mod.rs | pub mod steps;
use anyhow::{anyhow, Result};
pub async fn wait() {
tokio::time::sleep(tokio::time::Duration::from_millis(75)).await;
}
use regex::Regex;
fn extract_code_and_link(text: &str) -> Result<(String, String)> {
// Regex pattern for a six-digit number
let number_regex = Regex::new(r"\b\d{6}\b").unwrap();
// Regex pattern for a URL
let url_regex = Regex::new(r">(https?://[^<]+)<").unwrap(); // Simplified URL pattern
// Search for a six-digit number
let number = number_regex
.find(text)
.map(|match_| match_.as_str().to_string())
.ok_or(anyhow!("Can't find number match"))?;
// Search for a URL
let url = url_regex
.find(text)
.map(|match_| match_.as_str().to_string())
.ok_or(anyhow!("Can't find url match in \n {text}"))?;
let url = url.trim_matches(|c| c == '>' || c == '<').to_string();
let url = url.replace("amp;", "");
Ok((number, url))
}
fn extract_code(text: &str) -> Result<String> {
// Regex pattern for a six-digit number
let number_regex = Regex::new(r"\b\d{6}\b").unwrap();
// Search for a six-digit number
let number = number_regex
.find(text)
.map(|match_| match_.as_str().to_string())
.ok_or(anyhow!("Can't find number match"))?;
Ok(number)
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/ory-kratos/e2e/tests/fixtures/steps.rs | projects/ory-kratos/e2e/tests/fixtures/steps.rs | use crate::{AppWorld, EMAIL_ID_MAP};
use anyhow::anyhow;
use anyhow::{Ok, Result};
use chromiumoxide::cdp::browser_protocol::input::TimeSinceEpoch;
use chromiumoxide::cdp::browser_protocol::network::{CookieParam, DeleteCookiesParams};
use cucumber::{given, then, when};
use fake::locales::EN;
use fake::{faker::internet::raw::FreeEmail, Fake};
use super::wait;
#[given("I pass")]
pub async fn i_pass(_world: &mut AppWorld) -> Result<()> {
tracing::info!("I pass and I trace.");
Ok(())
}
#[given("I am on the homepage")]
pub async fn navigate_to_homepage(world: &mut AppWorld) -> Result<()> {
world.goto_path("/").await?;
Ok(())
}
#[then("I am on the homepage")]
pub async fn check_url_for_homepage(world: &mut AppWorld) -> Result<()> {
world.verify_route("/").await?;
Ok(())
}
#[given("I click register")]
#[when("I click register")]
pub async fn click_register(world: &mut AppWorld) -> Result<()> {
world.click(ids::REGISTER_BUTTON_ID).await?;
Ok(())
}
#[given("I see the registration form")]
#[when("I see the registration form")]
#[then("I see the registration form")]
pub async fn find_registration_form(world: &mut AppWorld) -> Result<()> {
world.find(ids::REGISTRATION_FORM_ID).await?;
Ok(())
}
#[given("I see the login form")]
#[when("I see the login form")]
#[then("I see the login form")]
pub async fn find_login_form(world: &mut AppWorld) -> Result<()> {
world.find(ids::LOGIN_FORM_ID).await?;
Ok(())
}
#[given("I am on the registration page")]
pub async fn navigate_to_register(world: &mut AppWorld) -> Result<()> {
world.goto_path("/register").await?;
Ok(())
}
#[given("I enter valid credentials")]
pub async fn fill_form_fields_with_credentials(world: &mut AppWorld) -> Result<()> {
let email = FreeEmail(EN).fake::<String>();
world
.set_field(ids::EMAIL_INPUT_ID, &email)
.await
.expect(&format!(
"To find element with id {} BUT ERROR : ",
ids::EMAIL_INPUT_ID
));
world.clipboard.insert("email", email);
world
.set_field(ids::PASSWORD_INPUT_ID, ids::PASSWORD)
.await
.expect(&format!(
"To find element with id {} BUT ERROR : ",
ids::PASSWORD_INPUT_ID
));
world.submit().await?;
world.errors().await?;
wait().await;
Ok(())
}
#[given("I enter valid other credentials")]
pub async fn fill_form_fields_with_other_credentials(world: &mut AppWorld) -> Result<()> {
let email = FreeEmail(EN).fake::<String>();
world
.set_field(ids::EMAIL_INPUT_ID, &email)
.await
.expect(&format!(
"To find element with id {} BUT ERROR : ",
ids::EMAIL_INPUT_ID
));
world.clipboard.insert("other_email", email);
world
.set_field(ids::PASSWORD_INPUT_ID, ids::PASSWORD)
.await
.expect(&format!(
"To find element with id {} BUT ERROR : ",
ids::PASSWORD_INPUT_ID
));
world.submit().await?;
world.errors().await?;
wait().await;
Ok(())
}
#[given("I re-enter other valid credentials")]
#[when("I re-enter other valid credentials")]
pub async fn fill_form_fields_with_previous_other_credentials(world: &mut AppWorld) -> Result<()> {
let email = world
.clipboard
.get("other_email")
.cloned()
.ok_or(anyhow!("Can't find other credentials in clipboard"))?;
world
.set_field(ids::EMAIL_INPUT_ID, &email)
.await
.expect("set email field");
world
.set_field(ids::PASSWORD_INPUT_ID, ids::PASSWORD)
.await
.expect("set password field");
world.submit().await?;
world.errors().await?;
Ok(())
}
#[when("I enter valid credentials")]
#[when("I re-enter valid credentials")]
#[given("I re-enter valid credentials")]
pub async fn fill_form_fields_with_previous_credentials(world: &mut AppWorld) -> Result<()> {
let email = world.clipboard.get("email").cloned();
let email = if let Some(email) = email {
email
} else {
let email = FreeEmail(EN).fake::<String>();
world.clipboard.insert("email", email.clone());
email
};
world
.set_field(ids::EMAIL_INPUT_ID, &email)
.await
.expect("set email field");
world
.set_field(ids::PASSWORD_INPUT_ID, ids::PASSWORD)
.await
.expect("set password field");
world.submit().await?;
world.errors().await?;
Ok(())
}
#[then("I am on the verify email page")]
pub async fn check_url_to_be_verify_page(world: &mut AppWorld) -> Result<()> {
world.find(ids::VERIFY_EMAIL_DIV_ID).await?;
Ok(())
}
#[given("I check my other email for the verification link and code")]
#[when("I check my other email for the verification link and code")]
pub async fn check_email_other_for_verification_link_and_code(world: &mut AppWorld) -> Result<()> {
tokio::time::sleep(std::time::Duration::from_secs(2)).await;
// we've stored the email with the id
// so we get the id with our email from our clipboard
let email = world
.clipboard
.get("other_email")
.ok_or(anyhow!("email not found in clipboard"))?;
let id = EMAIL_ID_MAP
.read()
.await
.get(email)
.ok_or(anyhow!("{email} not found in EMAIL_ID_MAP"))?
.clone();
// then we use the id to get the message from mailcrab
let body = reqwest::get(format!("http://127.0.0.1:1080/api/message/{}/body", id))
.await
.unwrap()
.text()
.await
.unwrap();
let (code, link) = super::extract_code_and_link(&body)?;
world.clipboard.insert("code", code);
world.clipboard.insert("link", link);
Ok(())
}
#[given("I check my email for the verification link and code")]
#[when("I check my email for the verification link and code")]
pub async fn check_email_for_verification_link_and_code(world: &mut AppWorld) -> Result<()> {
tokio::time::sleep(std::time::Duration::from_secs(2)).await;
// we've stored the email with the id
// so we get the id with our email from our clipboard
let email = world
.clipboard
.get("email")
.ok_or(anyhow!("email not found in clipboard"))?;
let id = EMAIL_ID_MAP
.read()
.await
.get(email)
.ok_or(anyhow!("{email} not found in EMAIL_ID_MAP"))?
.clone();
// then we use the id to get the message from mailcrab
let body = reqwest::get(format!("http://127.0.0.1:1080/api/message/{}/body", id))
.await
.unwrap()
.text()
.await
.unwrap();
let (code, link) = super::extract_code_and_link(&body)?;
world.clipboard.insert("code", code);
world.clipboard.insert("link", link);
Ok(())
}
#[given("I copy the code onto the verification link page")]
#[when("I copy the code onto the verification link page")]
pub async fn copy_code_onto_verification_page(world: &mut AppWorld) -> Result<()> {
let link = world
.clipboard
.get("link")
.ok_or(anyhow!("link not found in clipboard"))?
.clone();
world.goto_url(&link).await?;
let code = world
.clipboard
.get("code")
.ok_or(anyhow!("link not found in clipboard"))?
.clone();
world
.set_field(ids::VERFICATION_CODE_ID, code)
.await
.expect(&format!("Can't find {}", ids::VERFICATION_CODE_ID));
world.submit().await?;
world.click("continue").await?;
wait().await;
Ok(())
}
#[when("I click login")]
#[given("I click login")]
pub async fn click_login(world: &mut AppWorld) -> Result<()> {
world.click(ids::LOGIN_BUTTON_ID).await?;
wait().await;
Ok(())
}
#[given("I click logout")]
#[when("I click logout")]
pub async fn click_logout(world: &mut AppWorld) -> Result<()> {
world.click(ids::LOGOUT_BUTTON_ID).await?;
wait().await;
world.errors().await?;
Ok(())
}
#[tracing::instrument]
#[given("I am logged out")]
#[then("I am logged out")]
pub async fn check_ory_kratos_cookie_doesnt_exist(world: &mut AppWorld) -> Result<()> {
let cookies = world.page.get_cookies().await?;
if !cookies
.iter()
.filter(|c| c.name.contains("ory_kratos_session"))
.collect::<Vec<_>>()
.is_empty()
{
tracing::error!("{cookies:#?}");
Err(anyhow!("Ory kratos cookie exists."))
} else {
Ok(())
}
}
#[then("I am logged in")]
#[given("I am logged in")]
pub async fn check_ory_kratos_cookie_exists(world: &mut AppWorld) -> Result<()> {
if world
.page
.get_cookies()
.await?
.iter()
.filter(|c| c.name.contains("ory_kratos_session"))
.collect::<Vec<_>>()
.is_empty()
{
Err(anyhow!("Ory kratos cookie doesn't exists."))
} else {
Ok(())
}
}
#[given("I add example post")]
#[when("I add example post")]
pub async fn add_content_to_box(world: &mut AppWorld) -> Result<()> {
let content: Vec<String> = fake::faker::lorem::en::Words(0..10).fake();
let content = content.join(" ");
world.clipboard.insert("content", content.clone());
world
.set_field(ids::POST_POST_TEXT_AREA_ID, content)
.await?;
world.click(ids::POST_POST_SUBMIT_ID).await?;
Ok(())
}
#[given("I see example content posted")]
#[then("I see example content posted")]
#[when("I see example content posted")]
pub async fn see_my_content_posted(world: &mut AppWorld) -> Result<()> {
world.click(ids::POST_SHOW_LIST_BUTTON_ID).await?;
let content = world
.clipboard
.get("content")
.cloned()
.ok_or(anyhow!("Can't find content in clipboard"))?;
world.errors().await?;
let _ = world.find_text(content).await?;
Ok(())
}
#[when("I see error")]
#[then("I see error")]
pub async fn see_err(world: &mut AppWorld) -> Result<()> {
wait().await;
if world.errors().await.is_ok() {
return Err(anyhow!("Expecting an error."));
}
Ok(())
}
#[when("I don't see error")]
#[then("I don't see error")]
pub async fn dont_see_err(world: &mut AppWorld) -> Result<()> {
world.errors().await?;
Ok(())
}
#[given("I add other email as editor")]
#[when("I add other email as editor")]
pub async fn add_other_email_as_editor(world: &mut AppWorld) -> Result<()> {
let other_email = world
.clipboard
.get("other_email")
.cloned()
.ok_or(anyhow!("Can't find other email."))?;
world
.set_field(ids::POST_ADD_EDITOR_INPUT_ID, other_email)
.await?;
world.click(ids::POST_ADD_EDITOR_SUBMIT_ID).await?;
Ok(())
}
#[when("I logout")]
pub async fn i_logout(world: &mut AppWorld) -> Result<()> {
world.click(ids::LOGOUT_BUTTON_ID).await?;
world.errors().await?;
Ok(())
}
#[when("I edit example post")]
pub async fn add_new_edit_content_to_previous(world: &mut AppWorld) -> Result<()> {
let edit_content: Vec<String> = fake::faker::lorem::en::Words(0..10).fake();
let edit_content = edit_content.join(" ");
world.clipboard.insert("edit_content", edit_content.clone());
world
.set_field(ids::POST_EDIT_TEXT_AREA_ID, edit_content)
.await?;
world.click(ids::POST_EDIT_SUBMIT_ID).await?;
Ok(())
}
#[then("I see my new content posted")]
pub async fn new_content_boom_ba_da_boom(world: &mut AppWorld) -> Result<()> {
let content = world
.clipboard
.get("edit_content")
.cloned()
.ok_or(anyhow!("Can't find content in clipboard"))?;
world.find_text(content).await?;
Ok(())
}
#[then("I don't see old content")]
pub async fn dont_see_old_content_posted(world: &mut AppWorld) -> Result<()> {
let content = world
.clipboard
.get("content")
.cloned()
.ok_or(anyhow!("Can't find content in clipboard"))?;
if world.find_text(content).await.is_ok() {
return Err(anyhow!("But I do see old content..."));
}
Ok(())
}
#[given("I click show post list")]
#[when("I click show post list")]
pub async fn i_click_show_post_list(world: &mut AppWorld) -> Result<()> {
world.click(ids::POST_SHOW_LIST_BUTTON_ID).await?;
Ok(())
}
#[given("I clear cookies")]
pub async fn i_clear_cookies(world: &mut AppWorld) -> Result<()> {
let cookies = world
.page
.get_cookies()
.await?
.into_iter()
.map(|cookie| {
DeleteCookiesParams::from_cookie(&CookieParam {
name: cookie.name,
value: cookie.value,
url: None, // Since there's no direct field for URL, it's set as None
domain: Some(cookie.domain),
path: Some(cookie.path),
secure: Some(cookie.secure),
http_only: Some(cookie.http_only),
same_site: cookie.same_site,
// Assuming you have a way to convert f64 expires to TimeSinceEpoch
expires: None,
priority: Some(cookie.priority),
same_party: Some(cookie.same_party),
source_scheme: Some(cookie.source_scheme),
source_port: Some(cookie.source_port),
partition_key: cookie.partition_key,
// Note: `partition_key_opaque` is omitted since it doesn't have a direct mapping
})
})
.collect();
world.page.delete_cookies(cookies).await?;
Ok(())
}
#[given("I click recover email")]
pub async fn click_recover_email(world: &mut AppWorld) -> Result<()> {
world.click(ids::RECOVER_EMAIL_BUTTON_ID).await?;
wait().await;
Ok(())
}
#[given("I submit valid recovery email")]
pub async fn submit_valid_recovery_email(world: &mut AppWorld) -> Result<()> {
let email = world
.clipboard
.get("email")
.cloned()
.ok_or(anyhow!("Expecting email in clipboard if recovering email."))?;
world
.set_field(ids::EMAIL_INPUT_ID, &email)
.await
.expect("set email field");
world.submit().await?;
world.errors().await?;
Ok(())
}
#[given("I check my email for recovery link and code")]
pub async fn check_email_for_recovery_link_and_code(world: &mut AppWorld) -> Result<()> {
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
// we've stored the email with the id
// so we get the id with our email from our clipboard
let email = world
.clipboard
.get("email")
.ok_or(anyhow!("email not found in clipboard"))?;
let id = EMAIL_ID_MAP
.read()
.await
.get(email)
.ok_or(anyhow!("{email} not found in EMAIL_ID_MAP"))?
.clone();
// then we use the id to get the message from mailcrab
let body = reqwest::get(format!("http://127.0.0.1:1080/api/message/{}/body", id))
.await
.unwrap()
.text()
.await
.unwrap();
let code = super::extract_code(&body)?;
world.clipboard.insert("recovery_code", code);
Ok(())
}
#[when("I copy the code onto the recovery link page")]
pub async fn copy_code_onto_recovery_page(world: &mut AppWorld) -> Result<()> {
// we should figure out how to be on the right page, will this just work?
let code = world
.clipboard
.get("recovery_code")
.ok_or(anyhow!("link not found in clipboard"))?
.clone();
world
.set_field(ids::VERFICATION_CODE_ID, code)
.await
.expect(&format!("Can't find {}", ids::VERFICATION_CODE_ID));
world.submit().await?;
wait().await;
Ok(())
}
#[then("I am on the settings page")]
pub async fn im_on_settings_page(world: &mut AppWorld) -> Result<()> {
wait().await;
world.url_contains("/settings").await?;
Ok(())
}
#[given("I enter recovery credentials")]
#[when("I enter recovery credentials")]
pub async fn i_enter_a_new_recovery_password(world: &mut AppWorld) -> Result<()> {
let email = world
.clipboard
.get("email")
.cloned()
.ok_or(anyhow!("Can't find credentials in clipboard"))?;
world
.set_field(ids::EMAIL_INPUT_ID, &email)
.await
.expect("set email field");
world
.set_field(ids::PASSWORD_INPUT_ID, ids::RECOVERY_PASSWORD)
.await
.expect("set password field");
let code = world
.clipboard
.get("recovery_code")
.ok_or(anyhow!("link not found in clipboard"))?
.clone();
world
.set_field(ids::VERFICATION_CODE_ID, code)
.await
.expect(&format!("Can't find {}", ids::VERFICATION_CODE_ID));
world.submit().await?;
wait().await;
Ok(())
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/ory-kratos/frontend/src/lib.rs | projects/ory-kratos/frontend/src/lib.rs | use app::*;
use leptos::*;
use wasm_bindgen::prelude::wasm_bindgen;
#[wasm_bindgen]
pub fn hydrate() {
// initializes logging using the `log` crate
// _ = console_log::init_with_level(tracing::Level::Debug);
console_error_panic_hook::set_once();
leptos::mount_to_body(App);
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/ory-kratos/server/src/fileserv.rs | projects/ory-kratos/server/src/fileserv.rs | use app::App;
use axum::response::Response as AxumResponse;
use axum::{
body::Body,
extract::State,
http::{Request, Response, StatusCode, Uri},
response::IntoResponse,
};
use leptos::*;
use tower::ServiceExt;
use tower_http::services::ServeDir;
pub async fn file_and_error_handler(
uri: Uri,
State(options): State<LeptosOptions>,
req: Request<Body>,
) -> AxumResponse {
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 handler =
leptos_axum::render_app_to_stream(options.to_owned(), move || view! { <App/> });
handler(req).await.into_response()
}
}
async fn get_static_file(uri: Uri, root: &str) -> Result<Response<Body>, (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(Body::new)),
Err(err) => Err((
StatusCode::INTERNAL_SERVER_ERROR,
format!("Something went wrong: {err}"),
)),
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/ory-kratos/server/src/extract_session.rs | projects/ory-kratos/server/src/extract_session.rs | use axum::{async_trait, extract::FromRequestParts, RequestPartsExt};
use axum_extra::extract::CookieJar;
use http::request::Parts;
use ory_kratos_client::models::session::Session;
pub struct ExtractSession(pub Session);
#[async_trait]
impl<S> FromRequestParts<S> for ExtractSession
where
S: Send + Sync,
{
type Rejection = String;
#[tracing::instrument(err(Debug),skip_all)]
async fn from_request_parts(parts:&mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
let cookie_jar = parts
.extract::<CookieJar>()
.await
.unwrap();
let csrf_cookie = cookie_jar
.iter()
.filter(|cookie| cookie.name().contains("csrf_token"))
.next()
.ok_or(
"Expecting a csrf_token cookie to already be set if fetching a pre-existing flow".to_string()
)?;
let session_cookie = cookie_jar
.get("ory_kratos_session")
.ok_or("Ory Kratos Session cookie does not exist.".to_string())?;
let client = reqwest::ClientBuilder::new()
.redirect(reqwest::redirect::Policy::none())
.build()
.unwrap();
let resp = client
.get("http://127.0.0.1:4433/sessions/whoami")
.header("accept","application/json")
.header(
"cookie",
format!("{}={}", csrf_cookie.name(), csrf_cookie.value()),
)
.header(
"cookie",
format!("{}={}",session_cookie.name(),session_cookie.value())
)
.send()
.await
.map_err(|err|format!("Error sending resp to whoami err:{:#?}",err).to_string())?;
let session = resp.json::<Session>().await
.map_err(|err|format!("Error getting json from body err:{:#?}",err).to_string())?;
Ok(Self(session))
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/ory-kratos/server/src/main.rs | projects/ory-kratos/server/src/main.rs | use app::*;
use axum::Router;
use axum_server::tls_rustls::RustlsConfig;
use fileserv::file_and_error_handler;
use leptos::*;
use leptos_axum::{generate_route_list, LeptosRoutes};
use std::path::PathBuf;
use tracing_subscriber::EnvFilter;
pub mod fileserv;
#[tokio::main]
async fn main() {
tracing_subscriber::fmt()
.with_env_filter(EnvFilter::new("debug,tower_http=trace,rustls=error,cookie_store=error,reqwest=error,sqlx=error,hyper=error,h2=error"))
.pretty()
.init();
// we get a new db every restart.
_ = std::fs::remove_file("./app.db");
_ = std::fs::remove_file("./app.db-shm");
_ = std::fs::remove_file("./app.db-wal");
std::process::Command::new("sqlx")
.args(["db", "create", "--database-url", "sqlite:app.db"])
.status()
.expect("sqlx to exist on user machine");
std::process::Command::new("sqlx")
.args(["migrate", "run", "--database-url", "sqlite:app.db"])
.status()
.expect("sqlite3 to exist on user machine");
let pool = sqlx::SqlitePool::connect("sqlite:app.db").await.unwrap();
let config =
RustlsConfig::from_pem_file(PathBuf::from("./cert.pem"), PathBuf::from("./key.pem"))
.await
.unwrap();
// Setting get_configuration(None) means we'll be using cargo-leptos's env values
// For deployment these variables are:
// <https://github.com/leptos-rs/start-axum#executing-a-server-on-a-remote-machine-without-the-toolchain>
// Alternately a file can be specified such as Some("Cargo.toml")
// The file would need to be included with the executable when moved to deployment
let conf = get_configuration(None).unwrap();
let leptos_options = conf.leptos_options;
let addr = leptos_options.site_addr;
let routes = generate_route_list(App);
// build our application with a route
let app = Router::new()
.leptos_routes(&leptos_options, routes, App)
.fallback(file_and_error_handler)
.layer(axum::Extension(pool))
.layer(tower_http::trace::TraceLayer::new_for_http())
.with_state(leptos_options);
// run our app with hyper
// `axum::Server` is a re-export of `hyper::Server`
// axum_server::bind_rustl is a wrapper around that
// in real use case we'd want to also run a server that redirects http requests with https to the https server
println!("listening on https://{}", &addr);
axum_server::bind_rustls(addr, config)
.serve(app.into_make_service())
.await
.unwrap();
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/ory-kratos/ids/src/lib.rs | projects/ory-kratos/ids/src/lib.rs | pub static REGISTER_BUTTON_ID: &'static str = "register_button_id";
pub static REGISTRATION_FORM_ID: &'static str = "registration_form_id";
pub static EMAIL_INPUT_ID: &'static str = "email_input_id";
pub static PASSWORD_INPUT_ID: &'static str = "password_input_id";
pub static VERIFY_EMAIL_DIV_ID: &'static str = "verify_email_div_id";
pub static VERIFICATION_FORM_ID: &'static str = "verification_form_id";
pub static LOGIN_FORM_ID: &'static str = "login_form_id";
pub static REGISTER_ROUTE: &'static str = "/register";
pub static VERIFICATION_ROUTE: &'static str = "/verification";
pub static LOGIN_ROUTE: &'static str = "/login";
pub static KRATOS_ERROR_ROUTE: &'static str = "/kratos_error";
pub static RECOVERY_ROUTE: &'static str = "/recovery";
pub static SETTINGS_ROUTE: &'static str = "/settings";
pub static ERROR_ERROR_ID: &'static str = "error_template_id";
pub static ERROR_COOKIES_ID: &'static str = "error_cookies_id";
pub static VERFICATION_CODE_ID: &'static str = "verification_code_id";
pub static KRATOS_FORM_SUBMIT_ID: &'static str = "kratos_form_submit_id";
pub static LOGOUT_BUTTON_ID: &'static str = "logout_button_id";
pub static LOGIN_BUTTON_ID: &'static str = "login_button_id";
/// This function is for use in kratos_html, it takes the name of the input node and it
/// matches it according to what we've specified in the kratos schema file. If we change the schema.
/// I.e use a phone instead of an email, the identifier id will change and break tests that expect an email.
/// i.e use oidc instead of password, as auth method... that will break tests too.
/// Which is good.
pub fn match_name_to_id(name: String) -> &'static str {
match name.as_str() {
"traits.email" => EMAIL_INPUT_ID,
"identifier" => EMAIL_INPUT_ID,
"email" => EMAIL_INPUT_ID,
"password" => PASSWORD_INPUT_ID,
"code" => VERFICATION_CODE_ID,
"totp_code" => VERFICATION_CODE_ID,
_ => "",
}
}
pub static POST_POST_TEXT_AREA_ID: &'static str = "post_post_text_area_id";
pub static POST_POST_SUBMIT_ID: &'static str = "post_post_submit_id";
pub static POST_ADD_EDITOR_BUTTON_ID: &'static str = "post_add_editor_button_id";
pub static POST_ADD_EDITOR_INPUT_ID: &'static str = "add_editor_input_id";
pub static POST_ADD_EDITOR_SUBMIT_ID: &'static str = "post_add_editor_submit_id";
pub static POST_DELETE_ID: &'static str = "post_delete_id";
pub static POST_EDIT_TEXT_AREA_ID: &'static str = "post_edit_text_area_id";
pub static POST_EDIT_SUBMIT_ID: &'static str = "post_edit_submit_id";
pub static POST_SHOW_LIST_BUTTON_ID: &'static str = "post_show_list_button_id";
pub static CLEAR_COOKIES_BUTTON_ID: &'static str = "clear_cookies_button_id";
pub static RECOVERY_FORM_ID: &'static str = "recovery_form_id";
pub static RECOVER_EMAIL_BUTTON_ID: &'static str = "recover_email_button_id";
pub static RECOVERY_PASSWORD: &'static str = "RECOVERY_SuPeRsAfEpAsSwOrD1234!";
pub static PASSWORD: &'static str = "SuPeRsAfEpAsSwOrD1234!";
pub static SETTINGS_FORM_ID: &'static str = "settings_form_id";
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/sitemap_axum/src/app.rs | projects/sitemap_axum/src/app.rs | use crate::error_template::{AppError, ErrorTemplate};
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/sitemap-axum.css"/>
// sets the document title
<Title text="Welcome to Leptos"/>
// content for this welcome page
<Router fallback=|| {
let mut outside_errors = Errors::default();
outside_errors.insert_with_default_key(AppError::NotFound);
view! {
<ErrorTemplate outside_errors/>
}
.into_view()
}>
<main>
<Routes>
<Route path="" view=HomePage/>
</Routes>
</main>
</Router>
}
}
/// Renders the home page of your application.
#[component]
fn HomePage() -> impl IntoView {
view! {
<h1>"Welcome to Leptos!"</h1>
// Typically, you won't route to these files manually - a crawler of sorts will take care of that
<a href="http://localhost:3000/sitemap-index.xml">"Generate dynamic sitemap"</a>
<a style="padding-left: 1em;" href="http://localhost:3000/sitemap-static.xml">"Go to static sitemap"</a>
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/sitemap_axum/src/fileserv.rs | projects/sitemap_axum/src/fileserv.rs | use crate::app::App;
use axum::{
body::Body,
extract::State,
http::{Request, Response, StatusCode, Uri},
response::{IntoResponse, Response as AxumResponse},
};
use leptos::*;
use tower::ServiceExt;
use tower_http::services::ServeDir;
pub async fn file_and_error_handler(
uri: Uri,
State(options): State<LeptosOptions>,
req: Request<Body>,
) -> AxumResponse {
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 handler =
leptos_axum::render_app_to_stream(options.to_owned(), App);
handler(req).await.into_response()
}
}
async fn get_static_file(
uri: Uri,
root: &str,
) -> Result<Response<Body>, (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.into_response()),
Err(err) => Err((
StatusCode::INTERNAL_SERVER_ERROR,
format!("Something went wrong: {err}"),
)),
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/sitemap_axum/src/lib.rs | projects/sitemap_axum/src/lib.rs | pub mod app;
pub mod error_template;
#[cfg(feature = "ssr")]
pub mod fileserv;
#[cfg(feature = "ssr")]
pub mod sitemap;
#[cfg(feature = "hydrate")]
#[wasm_bindgen::prelude::wasm_bindgen]
pub fn hydrate() {
use crate::app::*;
console_error_panic_hook::set_once();
leptos::mount_to_body(App);
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/sitemap_axum/src/error_template.rs | projects/sitemap_axum/src/error_template.rs | use http::status::StatusCode;
use leptos::*;
use thiserror::Error;
#[derive(Clone, Debug, Error)]
pub enum AppError {
#[error("Not Found")]
NotFound,
}
impl AppError {
pub fn status_code(&self) -> StatusCode {
match self {
AppError::NotFound => StatusCode::NOT_FOUND,
}
}
}
// A basic function to display errors served by the error boundaries.
// Feel free to do more complicated things here than just displaying the error.
#[component]
pub fn ErrorTemplate(
#[prop(optional)] outside_errors: Option<Errors>,
#[prop(optional)] errors: Option<RwSignal<Errors>>,
) -> impl IntoView {
let errors = match outside_errors {
Some(e) => create_rw_signal(e),
None => match errors {
Some(e) => e,
None => panic!("No Errors found and we expected errors!"),
},
};
// Get Errors from Signal
let errors = errors.get_untracked();
// 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(feature = "ssr")]
{
use leptos_axum::ResponseOptions;
let response = use_context::<ResponseOptions>();
if let Some(response) = response {
response.set_status(errors[0].status_code());
}
}
view! {
<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
children=move |error| {
let error_string = error.1.to_string();
let error_code= error.1.status_code();
view! {
<h2>{error_code.to_string()}</h2>
<p>"Error: " {error_string}</p>
}
}
/>
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/sitemap_axum/src/main.rs | projects/sitemap_axum/src/main.rs | #[cfg(feature = "ssr")]
#[tokio::main]
async fn main() {
use axum::{routing::get, Router};
use leptos::*;
use leptos_axum::{generate_route_list, LeptosRoutes};
use sitemap_axum::{
app::*, fileserv::file_and_error_handler, sitemap::generate_sitemap,
};
use tower_http::services::ServeFile;
// Setting get_configuration(None) means we'll be using cargo-leptos's env values
// For deployment these variables are:
// <https://github.com/leptos-rs/start-axum#executing-a-server-on-a-remote-machine-without-the-toolchain>
// Alternately a file can be specified such as Some("Cargo.toml")
// The file would need to be included with the executable when moved to deployment
let conf = get_configuration(None).unwrap();
let leptos_options = conf.leptos_options;
let addr = leptos_options.site_addr;
let routes = generate_route_list(App);
// Build our application with a route
let app = Router::new()
// We can use Axum to mount a route that serves a sitemap file that we can generate with dynamic data
.route("/sitemap-index.xml", get(generate_sitemap))
// Using tower's serve file service, we can also serve a static sitemap file for relatively small sites too
.route_service(
"/sitemap-static.xml",
ServeFile::new("sitemap-static.xml"),
)
.leptos_routes(&leptos_options, routes, App)
.fallback(file_and_error_handler)
.with_state(leptos_options);
let listener = tokio::net::TcpListener::bind(&addr).await.unwrap();
logging::log!("listening on http://{}", &addr);
axum::serve(listener, app.into_make_service())
.await
.unwrap();
}
#[cfg(not(feature = "ssr"))]
pub fn main() {
// no client-side main function
// unless we want this to work with e.g., Trunk for a purely client-side app
// see lib.rs for hydration function instead
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/sitemap_axum/src/sitemap.rs | projects/sitemap_axum/src/sitemap.rs | use axum::{
body::Body,
response::{IntoResponse, Response},
};
use sqlx::{PgPool, Pool, Postgres};
use std::{
env::{self, current_dir},
fs::File,
io::{BufWriter, Read},
path::Path,
};
use time::{format_description, PrimitiveDateTime};
use xml::{writer::XmlEvent, EmitterConfig, EventWriter};
#[derive(Debug)]
struct Post {
slug: String,
updated_at: PrimitiveDateTime,
}
/// Generates a sitemap based on data stored in a database containing slugs that we can use to build URLs to the posts themselves.
pub async fn generate_sitemap() -> impl IntoResponse {
dotenvy::dotenv().ok();
// Depending on your preference, we can dynamically servce the sitemap file for each,
// or generate the file once on the first visit (probably from a bot) and write it to disk
// so we can simply serve the created file instead of having to query the database every time
let sitemap_path = format!(
"{}/sitemap-index.xml",
¤t_dir().unwrap().to_str().unwrap()
);
let path = Path::new(&sitemap_path);
// If the doesn't exist, we've probably deployed a fresh version of our Leptos site somewhere so we'll generate it on first request
if !path.exists() {
let pool = PgPool::connect(
&env::var("DATABASE_URL").expect("database URL to exist"),
)
.await
.expect("to be able to connect to pool");
create_sitemap_file(path, pool).await.ok();
}
// Once the file has been written, grab the contents of it and write it out as an XML file in the response
let mut file = File::open(sitemap_path).unwrap();
let mut contents = vec![];
file.read_to_end(&mut contents).ok();
let body = Body::from(contents);
Response::builder()
.header("Content-Type", "application/xml")
// Cache control can be helpful for cases where your site might be deployed occassionally and the original
// sitemap that was generated can be cached with a header
.header("Cache-Control", "max-age=86400")
.body(body)
.unwrap()
}
async fn create_sitemap_file(
path: &Path,
pool: Pool<Postgres>,
) -> anyhow::Result<()> {
let file = File::create(path).expect("sitemap file to be created");
let file = BufWriter::new(file);
let mut writer = EmitterConfig::new()
.perform_indent(true)
.create_writer(file);
writer
.write(
XmlEvent::start_element("urlset")
.attr("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9")
.attr("xmlns:xhtml", "http://www.w3.org/1999/xhtml")
.attr(
"xmlns:image",
"http://www.google.com/schemas/sitemap-image/1.1",
)
.attr(
"xmlns:video",
"http://www.google.com/schemas/sitemap-video/1.1",
)
.attr(
"xmlns:news",
"http://www.google.com/schemas/sitemap-news/0.9",
),
)
.expect("xml header to be written");
// We could also pull this from configuration or an environment variable
let app_url = "https://mywebsite.com";
// First, read all the blog entries so we can get the slug for building,
// URLs and the updated date to determine the change frequency
sqlx::query_as!(
Post,
r#"
SELECT slug,
updated_at
FROM posts
ORDER BY updated_at DESC
"#
)
.fetch_all(&pool)
.await
.expect("")
.into_iter()
.try_for_each(|p| write_post_entry(p, app_url, &mut writer))?;
// Next, write the static pages and close the XML stream
write_static_page_entry(app_url, &mut writer)?;
writer.write(XmlEvent::end_element())?;
Ok(())
}
fn write_post_entry(
post: Post,
app_url: &str,
writer: &mut EventWriter<BufWriter<File>>,
) -> anyhow::Result<()> {
let format = format_description::parse(
"[year]-[month]-[day]T[hour]:[minute]:[second]Z",
)?;
let parsed_date = post.updated_at.format(&format)?;
let route = format!("{}/blog/{}", app_url, post.slug);
writer.write(XmlEvent::start_element("url"))?;
writer.write(XmlEvent::start_element("loc"))?;
writer.write(XmlEvent::characters(&route))?;
writer.write(XmlEvent::end_element())?;
writer.write(XmlEvent::start_element("lastmod"))?;
writer.write(XmlEvent::characters(&parsed_date))?;
writer.write(XmlEvent::end_element())?;
writer.write(XmlEvent::start_element("changefreq"))?;
writer.write(XmlEvent::characters("yearly"))?;
writer.write(XmlEvent::end_element())?;
writer.write(XmlEvent::start_element("priority"))?;
writer.write(XmlEvent::characters("0.5"))?;
writer.write(XmlEvent::end_element())?;
writer.write(XmlEvent::end_element())?;
Ok(())
}
fn write_static_page_entry(
route: &str,
writer: &mut EventWriter<BufWriter<File>>,
) -> anyhow::Result<()> {
write_entry(route, "weekly", "0.8", writer)?;
Ok(())
}
fn write_entry(
route: &str,
change_frequency: &str,
priority: &str,
writer: &mut EventWriter<BufWriter<File>>,
) -> anyhow::Result<()> {
writer.write(XmlEvent::start_element("url"))?;
writer.write(XmlEvent::start_element("loc"))?;
writer.write(XmlEvent::characters(route))?;
writer.write(XmlEvent::end_element())?;
writer.write(XmlEvent::start_element("changefreq"))?;
writer.write(XmlEvent::characters(change_frequency))?;
writer.write(XmlEvent::end_element())?;
writer.write(XmlEvent::start_element("priority"))?;
writer.write(XmlEvent::characters(priority))?;
writer.write(XmlEvent::end_element())?;
writer.write(XmlEvent::end_element())?;
Ok(())
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/counter_dwarf_debug/src/lib.rs | projects/counter_dwarf_debug/src/lib.rs | use leptos::*;
/// A simple counter component.
///
/// You can use doc comments like this to document your component.
#[component]
pub fn SimpleCounter(
/// The starting value for the counter
initial_value: i32,
/// The change that should be applied each time the button is clicked.
step: i32,
) -> impl IntoView {
let (value, set_value) = create_signal(initial_value);
view! {
<div>
<button on:click=move |_| set_value.set(0)>"Clear"</button>
<button on:click=move |_| set_value.update(|value| *value -= step)>"-1"</button>
<span>"Value: " {value} "!"</span>
<button on:click=move |_| {
// Test Panic
//panic!("Test Panic");
// In order to breakpoint the below, the code needs to be on it's own line
set_value.update(|value| *value += step)
}
>"+1"</button>
</div>
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/counter_dwarf_debug/src/main.rs | projects/counter_dwarf_debug/src/main.rs | use counter_dwarf_debug::SimpleCounter;
use leptos::*;
pub fn main() {
_ = console_log::init_with_level(log::Level::Debug);
console_error_panic_hook::set_once();
mount_to_body(|| {
view! {
<SimpleCounter
initial_value=0
step=1
/>
}
})
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/session_auth_axum/src/errors.rs | projects/session_auth_axum/src/errors.rs | 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
}
}
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/session_auth_axum/src/lib.rs | projects/session_auth_axum/src/lib.rs | pub mod auth;
pub mod error_template;
pub mod errors;
#[cfg(feature = "ssr")]
pub mod state;
pub mod todo;
#[cfg(feature = "hydrate")]
#[wasm_bindgen::prelude::wasm_bindgen]
pub fn hydrate() {
use crate::todo::*;
_ = console_log::init_with_level(log::Level::Debug);
console_error_panic_hook::set_once();
leptos::mount::hydrate_body(TodoApp);
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/session_auth_axum/src/state.rs | projects/session_auth_axum/src/state.rs | use axum::extract::FromRef;
use leptos::prelude::LeptosOptions;
use leptos_axum::AxumRouteListing;
use sqlx::SqlitePool;
/// This takes advantage of Axum's SubStates feature by deriving FromRef. This is the only way to have more than one
/// item in Axum's State. Leptos requires you to have leptosOptions in your State struct for the leptos route handlers
#[derive(FromRef, Debug, Clone)]
pub struct AppState {
pub leptos_options: LeptosOptions,
pub pool: SqlitePool,
pub routes: Vec<AxumRouteListing>,
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/session_auth_axum/src/todo.rs | projects/session_auth_axum/src/todo.rs | use crate::{auth::*, error_template::ErrorTemplate};
use leptos::prelude::*;
use leptos_meta::*;
use leptos_router::{components::*, path};
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Todo {
id: u32,
user: Option<User>,
title: String,
created_at: String,
completed: bool,
}
#[cfg(feature = "ssr")]
pub mod ssr {
use super::Todo;
use crate::{
auth::{ssr::AuthSession, User},
state::AppState,
};
use leptos::prelude::*;
use sqlx::SqlitePool;
pub fn pool() -> Result<SqlitePool, ServerFnError> {
with_context::<AppState, _>(|state| state.pool.clone())
.ok_or_else(|| ServerFnError::ServerError("Pool missing.".into()))
}
pub async fn auth() -> Result<AuthSession, ServerFnError> {
let auth = leptos_axum::extract().await?;
Ok(auth)
}
#[derive(sqlx::FromRow, Clone)]
pub struct SqlTodo {
id: u32,
user_id: i64,
title: String,
created_at: String,
completed: bool,
}
impl SqlTodo {
pub async fn into_todo(self, pool: &SqlitePool) -> Todo {
Todo {
id: self.id,
user: User::get(self.user_id, pool).await,
title: self.title,
created_at: self.created_at,
completed: self.completed,
}
}
}
}
#[server(GetTodos, "/api")]
pub async fn get_todos() -> Result<Vec<Todo>, ServerFnError> {
use self::ssr::{pool, SqlTodo};
use futures::future::join_all;
let pool = pool()?;
Ok(join_all(
sqlx::query_as::<_, SqlTodo>("SELECT * FROM todos")
.fetch_all(&pool)
.await?
.iter()
.map(|todo: &SqlTodo| todo.clone().into_todo(&pool)),
)
.await)
}
#[server(AddTodo, "/api")]
pub async fn add_todo(title: String) -> Result<(), ServerFnError> {
use self::ssr::*;
let user = get_user().await?;
let pool = pool()?;
let id = match user {
Some(user) => user.id,
None => -1,
};
// fake API delay
std::thread::sleep(std::time::Duration::from_millis(1250));
Ok(sqlx::query(
"INSERT INTO todos (title, user_id, completed) VALUES (?, ?, false)",
)
.bind(title)
.bind(id)
.execute(&pool)
.await
.map(|_| ())?)
}
// The struct name and path prefix arguments are optional.
#[server]
pub async fn delete_todo(id: u16) -> Result<(), ServerFnError> {
use self::ssr::*;
let pool = pool()?;
Ok(sqlx::query("DELETE FROM todos WHERE id = $1")
.bind(id)
.execute(&pool)
.await
.map(|_| ())?)
}
pub fn shell(options: LeptosOptions) -> impl IntoView {
view! {
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<AutoReload options=options.clone() />
<HydrationScripts options/>
<link rel="stylesheet" id="leptos" href="/pkg/session_auth_axum.css"/>
<link rel="shortcut icon" type="image/ico" href="/favicon.ico"/>
<MetaTags/>
</head>
<body>
<TodoApp/>
</body>
</html>
}
}
#[component]
pub fn TodoApp() -> impl IntoView {
let login = ServerAction::<Login>::new();
let logout = ServerAction::<Logout>::new();
let signup = ServerAction::<Signup>::new();
let user = Resource::new(
move || {
(
login.version().get(),
signup.version().get(),
logout.version().get(),
)
},
move |_| get_user(),
);
provide_meta_context();
view! {
<Router>
<header>
<A href="/">
<h1>"My Tasks"</h1>
</A>
<Transition fallback=move || {
view! { <span>"Loading..."</span> }
}>
{move || {
user.get()
.map(|user| match user {
Err(e) => {
view! {
<A href="/signup">"Signup"</A>
", "
<A href="/login">"Login"</A>
", "
<span>{format!("Login error: {e}")}</span>
}
.into_any()
}
Ok(None) => {
view! {
<A href="/signup">"Signup"</A>
", "
<A href="/login">"Login"</A>
", "
<span>"Logged out."</span>
}
.into_any()
}
Ok(Some(user)) => {
view! {
<A href="/settings">"Settings"</A>
", "
<span>
{format!("Logged in as: {} ({})", user.username, user.id)}
</span>
}
.into_any()
}
})
}}
</Transition>
</header>
<hr/>
<main>
<FlatRoutes fallback=|| "Not found.">
// Route
<Route path=path!("") view=Todos/>
<Route path=path!("signup") view=move || view! { <Signup action=signup/> }/>
<Route path=path!("login") view=move || view! { <Login action=login/> }/>
<ProtectedRoute
path=path!("settings")
condition=move || user.get().map(|r| r.ok().flatten().is_some())
redirect_path=|| "/"
view=move || {
view! {
<h1>"Settings"</h1>
<Logout action=logout/>
}
}
/>
</FlatRoutes>
</main>
</Router>
}
}
#[component]
pub fn Todos() -> impl IntoView {
let add_todo = ServerMultiAction::<AddTodo>::new();
let delete_todo = ServerAction::<DeleteTodo>::new();
let submissions = add_todo.submissions();
// list of todos is loaded from the server in reaction to changes
let todos = Resource::new(
move || (add_todo.version().get(), delete_todo.version().get()),
move |_| get_todos(),
);
view! {
<div>
<MultiActionForm action=add_todo>
<label>"Add a Todo" <input type="text" name="title"/></label>
<input type="submit" value="Add"/>
</MultiActionForm>
<Transition fallback=move || view! { <p>"Loading..."</p> }>
<ErrorBoundary fallback=|errors| {
view! { <ErrorTemplate errors=errors/> }
}>
{move || {
let existing_todos = {
move || {
todos
.get()
.map(move |todos| match todos {
Err(e) => {
view! {
<pre class="error">"Server Error: " {e.to_string()}</pre>
}
.into_any()
}
Ok(todos) => {
if todos.is_empty() {
view! { <p>"No tasks were found."</p> }.into_any()
} else {
todos
.into_iter()
.map(move |todo| {
view! {
<li>
{todo.title} ": Created at " {todo.created_at} " by "
{todo.user.unwrap_or_default().username}
<ActionForm action=delete_todo>
<input type="hidden" name="id" value=todo.id/>
<input type="submit" value="X"/>
</ActionForm>
</li>
}
})
.collect_view()
.into_any()
}
}
})
.unwrap_or(().into_any())
}
};
let pending_todos = move || {
submissions
.get()
.into_iter()
.filter(|submission| submission.pending().get())
.map(|submission| {
view! {
<li class="pending">
{move || submission.input().get().map(|data| data.title)}
</li>
}
})
.collect_view()
};
view! { <ul>{existing_todos} {pending_todos}</ul> }
}}
</ErrorBoundary>
</Transition>
</div>
}
}
#[component]
pub fn Login(action: ServerAction<Login>) -> impl IntoView {
view! {
<ActionForm action=action>
<h1>"Log In"</h1>
<label>
"User ID:"
<input
type="text"
placeholder="User ID"
maxlength="32"
name="username"
class="auth-input"
/>
</label>
<br/>
<label>
"Password:"
<input type="password" placeholder="Password" name="password" class="auth-input"/>
</label>
<br/>
<label>
<input type="checkbox" name="remember" class="auth-input"/>
"Remember me?"
</label>
<br/>
<button type="submit" class="button">
"Log In"
</button>
</ActionForm>
}
}
#[component]
pub fn Signup(action: ServerAction<Signup>) -> impl IntoView {
view! {
<ActionForm action=action>
<h1>"Sign Up"</h1>
<label>
"User ID:"
<input
type="text"
placeholder="User ID"
maxlength="32"
name="username"
class="auth-input"
/>
</label>
<br/>
<label>
"Password:"
<input type="password" placeholder="Password" name="password" class="auth-input"/>
</label>
<br/>
<label>
"Confirm Password:"
<input
type="password"
placeholder="Password again"
name="password_confirmation"
class="auth-input"
/>
</label>
<br/>
<label>
"Remember me?" <input type="checkbox" name="remember" class="auth-input"/>
</label>
<br/>
<button type="submit" class="button">
"Sign Up"
</button>
</ActionForm>
}
}
#[component]
pub fn Logout(action: ServerAction<Logout>) -> impl IntoView {
view! {
<div id="loginbox">
<ActionForm action=action>
<button type="submit" class="button">
"Log Out"
</button>
</ActionForm>
</div>
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/session_auth_axum/src/auth.rs | projects/session_auth_axum/src/auth.rs | use leptos::prelude::*;
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct User {
pub id: i64,
pub username: String,
pub permissions: HashSet<String>,
}
// Explicitly is not Serialize/Deserialize!
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct UserPasshash(String);
impl Default for User {
fn default() -> Self {
let permissions = HashSet::new();
Self {
id: -1,
username: "Guest".into(),
permissions,
}
}
}
#[cfg(feature = "ssr")]
pub mod ssr {
pub use super::{User, UserPasshash};
pub use axum_session_auth::{Authentication, HasPermission};
use axum_session_sqlx::SessionSqlitePool;
pub use sqlx::SqlitePool;
pub use std::collections::HashSet;
pub type AuthSession = axum_session_auth::AuthSession<
User,
i64,
SessionSqlitePool,
SqlitePool,
>;
pub use crate::todo::ssr::{auth, pool};
pub use async_trait::async_trait;
pub use bcrypt::{hash, verify, DEFAULT_COST};
impl User {
pub async fn get_with_passhash(
id: i64,
pool: &SqlitePool,
) -> Option<(Self, UserPasshash)> {
let sqluser = sqlx::query_as::<_, SqlUser>(
"SELECT * FROM users WHERE id = ?",
)
.bind(id)
.fetch_one(pool)
.await
.ok()?;
//lets just get all the tokens the user can use, we will only use the full permissions if modifying them.
let sql_user_perms = sqlx::query_as::<_, SqlPermissionTokens>(
"SELECT token FROM user_permissions WHERE user_id = ?;",
)
.bind(id)
.fetch_all(pool)
.await
.ok()?;
Some(sqluser.into_user(Some(sql_user_perms)))
}
pub async fn get(id: i64, pool: &SqlitePool) -> Option<Self> {
User::get_with_passhash(id, pool)
.await
.map(|(user, _)| user)
}
pub async fn get_from_username_with_passhash(
name: String,
pool: &SqlitePool,
) -> Option<(Self, UserPasshash)> {
let sqluser = sqlx::query_as::<_, SqlUser>(
"SELECT * FROM users WHERE username = ?",
)
.bind(name)
.fetch_one(pool)
.await
.ok()?;
//lets just get all the tokens the user can use, we will only use the full permissions if modifying them.
let sql_user_perms = sqlx::query_as::<_, SqlPermissionTokens>(
"SELECT token FROM user_permissions WHERE user_id = ?;",
)
.bind(sqluser.id)
.fetch_all(pool)
.await
.ok()?;
Some(sqluser.into_user(Some(sql_user_perms)))
}
pub async fn get_from_username(
name: String,
pool: &SqlitePool,
) -> Option<Self> {
User::get_from_username_with_passhash(name, pool)
.await
.map(|(user, _)| user)
}
}
#[derive(sqlx::FromRow, Clone)]
pub struct SqlPermissionTokens {
pub token: String,
}
#[async_trait]
impl Authentication<User, i64, SqlitePool> for User {
async fn load_user(
userid: i64,
pool: Option<&SqlitePool>,
) -> Result<User, anyhow::Error> {
let pool = pool.unwrap();
User::get(userid, pool)
.await
.ok_or_else(|| anyhow::anyhow!("Cannot get user"))
}
fn is_authenticated(&self) -> bool {
true
}
fn is_active(&self) -> bool {
true
}
fn is_anonymous(&self) -> bool {
false
}
}
#[async_trait]
impl HasPermission<SqlitePool> for User {
async fn has(&self, perm: &str, _pool: &Option<&SqlitePool>) -> bool {
self.permissions.contains(perm)
}
}
#[derive(sqlx::FromRow, Clone)]
pub struct SqlUser {
pub id: i64,
pub username: String,
pub password: String,
}
impl SqlUser {
pub fn into_user(
self,
sql_user_perms: Option<Vec<SqlPermissionTokens>>,
) -> (User, UserPasshash) {
(
User {
id: self.id,
username: self.username,
permissions: if let Some(user_perms) = sql_user_perms {
user_perms
.into_iter()
.map(|x| x.token)
.collect::<HashSet<String>>()
} else {
HashSet::<String>::new()
},
},
UserPasshash(self.password),
)
}
}
}
#[server]
pub async fn foo() -> Result<String, ServerFnError> {
Ok(String::from("Bar!"))
}
#[server]
pub async fn get_user() -> Result<Option<User>, ServerFnError> {
use crate::todo::ssr::auth;
let auth = auth().await?;
Ok(auth.current_user)
}
#[server(Login, "/api")]
pub async fn login(
username: String,
password: String,
remember: Option<String>,
) -> Result<(), ServerFnError> {
use self::ssr::*;
let pool = pool()?;
let auth = auth().await?;
let (user, UserPasshash(expected_passhash)) =
User::get_from_username_with_passhash(username, &pool)
.await
.ok_or_else(|| ServerFnError::new("User does not exist."))?;
match verify(password, &expected_passhash)? {
true => {
auth.login_user(user.id);
auth.remember_user(remember.is_some());
leptos_axum::redirect("/");
Ok(())
}
false => Err(ServerFnError::ServerError(
"Password does not match.".to_string(),
)),
}
}
#[server(Signup, "/api")]
pub async fn signup(
username: String,
password: String,
password_confirmation: String,
remember: Option<String>,
) -> Result<(), ServerFnError> {
use self::ssr::*;
let pool = pool()?;
let auth = auth().await?;
if password != password_confirmation {
return Err(ServerFnError::ServerError(
"Passwords did not match.".to_string(),
));
}
let password_hashed = hash(password, DEFAULT_COST).unwrap();
sqlx::query("INSERT INTO users (username, password) VALUES (?,?)")
.bind(username.clone())
.bind(password_hashed)
.execute(&pool)
.await?;
let user =
User::get_from_username(username, &pool)
.await
.ok_or_else(|| {
ServerFnError::new("Signup failed: User does not exist.")
})?;
auth.login_user(user.id);
auth.remember_user(remember.is_some());
leptos_axum::redirect("/");
Ok(())
}
#[server(Logout, "/api")]
pub async fn logout() -> Result<(), ServerFnError> {
use self::ssr::*;
let auth = auth().await?;
auth.logout_user();
leptos_axum::redirect("/");
Ok(())
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/session_auth_axum/src/error_template.rs | projects/session_auth_axum/src/error_template.rs | use crate::errors::TodoAppError;
use leptos::prelude::*;
#[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(
#[prop(optional)] outside_errors: Option<Errors>,
#[prop(optional)] errors: Option<ArcRwSignal<Errors>>,
) -> impl IntoView {
let errors = match outside_errors {
Some(e) => ArcRwSignal::new(e),
None => match errors {
Some(e) => e,
None => panic!("No Errors found and we expected errors!"),
},
};
// Get Errors from Signal
// Downcast lets us take a type that implements `std::error::Error`
let errors: Vec<TodoAppError> = errors
.get()
.into_iter()
.filter_map(|(_, v)| v.downcast_ref::<TodoAppError>().cloned())
.collect();
// Only the response code for the first error is actually sent from the server
// this may be customized by the specific application
#[cfg(feature = "ssr")]
{
let response = use_context::<ResponseOptions>();
if let Some(response) = response {
response.set_status(errors[0].status_code());
}
}
view! {
<h1>"Errors"</h1>
<For
// a function that returns the items we're iterating over; a signal is fine
each=move || { errors.clone().into_iter().enumerate() }
// a unique key for each item as a reference
key=|(index, _error)| *index
// renders each item to a view
children=move |error| {
let error_string = error.1.to_string();
let error_code = error.1.status_code();
view! {
<h2>{error_code.to_string()}</h2>
<p>"Error: " {error_string}</p>
}
}
/>
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/session_auth_axum/src/main.rs | projects/session_auth_axum/src/main.rs | use axum::Router;
use axum_session::{SessionConfig, SessionLayer, SessionStore};
use axum_session_auth::{AuthConfig, AuthSessionLayer};
use axum_session_sqlx::SessionSqlitePool;
use leptos::{config::get_configuration, logging::log};
use leptos_axum::{generate_route_list, LeptosRoutes};
use session_auth_axum::{auth::User, state::AppState, todo::*};
use sqlx::{sqlite::SqlitePoolOptions, SqlitePool};
#[tokio::main]
async fn main() {
simple_logger::init_with_level(log::Level::Info)
.expect("couldn't initialize logging");
let pool = SqlitePoolOptions::new()
.connect("sqlite:Todos.db")
.await
.expect("Could not make pool.");
// Auth section
let session_config =
SessionConfig::default().with_table_name("axum_sessions");
let auth_config = AuthConfig::<i64>::default();
let session_store = SessionStore::<SessionSqlitePool>::new(
Some(SessionSqlitePool::from(pool.clone())),
session_config,
)
.await
.unwrap();
if let Err(e) = sqlx::migrate!().run(&pool).await {
eprintln!("{e:?}");
}
// Setting this to None means we'll be using cargo-leptos and its env vars
let conf = get_configuration(None).unwrap();
let leptos_options = conf.leptos_options;
let addr = leptos_options.site_addr;
let routes = generate_route_list(TodoApp);
let app_state = AppState {
leptos_options,
pool: pool.clone(),
routes: routes.clone(),
};
// build our application with a route
let app = Router::new()
.leptos_routes(&app_state, routes, {
let options = app_state.leptos_options.clone();
move || shell(options.clone())
})
.fallback(leptos_axum::file_and_error_handler::<AppState, _>(shell))
.layer(
AuthSessionLayer::<User, i64, SessionSqlitePool, SqlitePool>::new(
Some(pool.clone()),
)
.with_config(auth_config),
)
.layer(SessionLayer::new(session_store))
.with_state(app_state);
// run our app with hyper
// `axum::Server` is a re-export of `hyper::Server`
log!("listening on http://{}", &addr);
let listener = tokio::net::TcpListener::bind(&addr).await.unwrap();
axum::serve(listener, app.into_make_service())
.await
.unwrap();
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/tauri-from-scratch/src-orig/src/app.rs | projects/tauri-from-scratch/src-orig/src/app.rs | use leptos::prelude::*;
#[cfg(feature = "ssr")]
pub fn shell(options: LeptosOptions) -> impl IntoView {
use leptos_meta::MetaTags;
view! {
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<AutoReload options=options.clone() />
<HydrationScripts options/>
<MetaTags/>
</head>
<body>
<App/>
</body>
</html>
}
}
#[server(endpoint = "hello_world")]
pub async fn hello_world_server() -> Result<String, ServerFnError> {
Ok("Hey.".to_string())
}
#[component]
pub fn App() -> impl IntoView {
let action = ServerAction::<HelloWorldServer>::new();
let vals = RwSignal::new(String::new());
Effect::new(move |_| {
if let Some(resp) = action.value().get() {
match resp {
Ok(val) => vals.set(val),
Err(err) => vals.set(format!("{err:?}")),
}
}
});
view! {
<button
on:click=move |_| {
action.dispatch(HelloWorldServer{});
}
>"Hello world."</button>
<br/><br/>
<span>"Server says: "</span>
{move || vals.get()}
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/tauri-from-scratch/src-orig/src/lib.rs | projects/tauri-from-scratch/src-orig/src/lib.rs | pub mod app;
#[cfg(feature = "ssr")]
pub mod fallback;
#[cfg(feature = "hydrate")]
#[wasm_bindgen::prelude::wasm_bindgen]
pub fn hydrate() {
console_error_panic_hook::set_once();
leptos::mount::hydrate_body(app::App);
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/tauri-from-scratch/src-orig/src/main.rs | projects/tauri-from-scratch/src-orig/src/main.rs | #[cfg(feature = "ssr")]
#[tokio::main]
async fn main() {
use axum::{
body::Body,
extract::{Request, State},
response::IntoResponse,
routing::get,
Router,
};
use leptos::logging::log;
use leptos::prelude::*;
use leptos_axum::{generate_route_list, LeptosRoutes};
use leptos_tauri_from_scratch::{
app::{shell, App},
fallback::file_and_error_handler,
};
use tower_http::cors::CorsLayer;
let conf = get_configuration(None).unwrap();
let addr = conf.leptos_options.site_addr;
let leptos_options = conf.leptos_options;
// Generate the list of routes in your Leptos App
let routes = generate_route_list(App);
#[derive(Clone, Debug, axum_macros::FromRef)]
pub struct ServerState {
pub options: LeptosOptions,
pub routes: Vec<leptos_axum::AxumRouteListing>,
}
let state = ServerState {
options: leptos_options,
routes: routes.clone(),
};
pub async fn server_fn_handler(
State(state): State<ServerState>,
request: Request<Body>,
) -> impl IntoResponse {
leptos_axum::handle_server_fns_with_context(
move || {
provide_context(state.clone());
},
request,
)
.await
.into_response()
}
let cors = CorsLayer::new()
.allow_methods([axum::http::Method::GET, axum::http::Method::POST])
.allow_origin(
"tauri://localhost"
.parse::<axum::http::HeaderValue>()
.unwrap(),
)
.allow_headers(vec![axum::http::header::CONTENT_TYPE]);
pub async fn leptos_routes_handler(
State(state): State<ServerState>,
req: Request<Body>,
) -> axum::response::Response {
let leptos_options = state.options.clone();
let handler = leptos_axum::render_route_with_context(
state.routes.clone(),
move || {
provide_context("...");
},
move || shell(leptos_options.clone()),
);
handler(axum::extract::State(state), req)
.await
.into_response()
}
let app = Router::new()
.route(
"/api/{*fn_name}",
get(server_fn_handler).post(server_fn_handler),
)
.layer(cors)
.leptos_routes_with_handler(routes, get(leptos_routes_handler))
.fallback(file_and_error_handler)
.with_state(state);
// run our app with hyper
// `axum::Server` is a re-export of `hyper::Server`
log!("listening on http://{}", &addr);
let listener = tokio::net::TcpListener::bind(&addr).await.unwrap();
axum::serve(listener, app.into_make_service())
.await
.unwrap();
}
#[cfg(feature = "csr")]
pub fn main() {
server_fn::client::set_server_url("http://127.0.0.1:3000");
leptos::mount::mount_to_body(leptos_tauri_from_scratch::app::App);
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/tauri-from-scratch/src-orig/src/fallback.rs | projects/tauri-from-scratch/src-orig/src/fallback.rs | use axum::{
body::Body,
extract::State,
http::{Request, Response, StatusCode, Uri},
response::{IntoResponse, Response as AxumResponse},
};
use leptos::{prelude::LeptosOptions, view};
use tower::ServiceExt;
use tower_http::services::ServeDir;
pub async fn file_and_error_handler(
uri: Uri,
State(options): State<LeptosOptions>,
req: Request<Body>,
) -> AxumResponse {
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 handler = leptos_axum::render_app_to_stream(move || view! {404});
handler(req).await.into_response()
}
}
async fn get_static_file(
uri: Uri,
root: &str,
) -> Result<Response<Body>, (StatusCode, String)> {
let req = Request::builder()
.uri(uri.clone())
.body(Body::empty())
.unwrap();
match ServeDir::new(root).oneshot(req).await {
Ok(res) => Ok(res.into_response()),
Err(err) => Err((
StatusCode::INTERNAL_SERVER_ERROR,
format!("Something went wrong: {err}"),
)),
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/tauri-from-scratch/src-tauri/build.rs | projects/tauri-from-scratch/src-tauri/build.rs | fn main() {
tauri_build::build();
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/tauri-from-scratch/src-tauri/src/lib.rs | projects/tauri-from-scratch/src-tauri/src/lib.rs | use tauri::Manager;
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
tauri::Builder::default()
.plugin(tauri_plugin_http::init())
.setup(|app| {
{
let window = app.get_webview_window("main").unwrap();
window.open_devtools();
}
Ok(())
})
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/tauri-from-scratch/src-tauri/src/main.rs | projects/tauri-from-scratch/src-tauri/src/main.rs | // Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
fn main() {
app_lib::run();
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/bevy3d_ui/src/main.rs | projects/bevy3d_ui/src/main.rs | mod demos;
mod routes;
use leptos::prelude::*;
use routes::RootPage;
pub fn main() {
// Bevy will output a lot of debug info to the console when this is enabled.
//_ = console_log::init_with_level(log::Level::Debug);
console_error_panic_hook::set_once();
mount_to_body(|| view! { <RootPage/> })
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/bevy3d_ui/src/demos/mod.rs | projects/bevy3d_ui/src/demos/mod.rs | pub mod bevydemo1;
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/bevy3d_ui/src/demos/bevydemo1/state.rs | projects/bevy3d_ui/src/demos/bevydemo1/state.rs | use bevy::ecs::system::Resource;
use std::sync::{Arc, Mutex};
pub type Shared<T> = Arc<Mutex<T>>;
/// Shared Resource used for Bevy
#[derive(Resource)]
pub struct SharedResource(pub Shared<SharedState>);
/// Shared State
pub struct SharedState {
pub name: String,
}
impl SharedState {
/// Get a new shared state
pub fn new() -> Arc<Mutex<SharedState>> {
let state = SharedState {
name: "This can be used for shared state".to_string(),
};
let shared = Arc::new(Mutex::new(state));
shared
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/bevy3d_ui/src/demos/bevydemo1/scene.rs | projects/bevy3d_ui/src/demos/bevydemo1/scene.rs | use super::eventqueue::events::{
ClientInEvents, CounterEvtData, EventProcessor, PluginOutEvents,
};
use super::eventqueue::plugin::DuplexEventsPlugin;
use super::state::{Shared, SharedResource, SharedState};
use bevy::prelude::*;
/// Represents the Cube in the scene
#[derive(Component, Copy, Clone)]
pub struct Cube;
/// Represents the 3D Scene
#[derive(Clone)]
pub struct Scene {
is_setup: bool,
canvas_id: String,
evt_plugin: DuplexEventsPlugin,
shared_state: Shared<SharedState>,
processor: EventProcessor<ClientInEvents, PluginOutEvents>,
}
impl Scene {
/// Create a new instance
pub fn new(canvas_id: String) -> Scene {
let plugin = DuplexEventsPlugin::new();
Scene {
is_setup: false,
canvas_id,
evt_plugin: plugin.clone(),
shared_state: SharedState::new(),
processor: plugin.get_processor(),
}
}
/// Get the shared state
pub fn get_state(&self) -> Shared<SharedState> {
self.shared_state.clone()
}
/// Get the event processor
pub fn get_processor(
&self,
) -> EventProcessor<ClientInEvents, PluginOutEvents> {
self.processor.clone()
}
/// Setup and attach the bevy instance to the html canvas element
pub fn setup(&mut self) {
if self.is_setup {
return;
};
App::new()
.add_plugins(DefaultPlugins.set(WindowPlugin {
primary_window: Some(Window {
canvas: Some(self.canvas_id.clone()),
..default()
}),
..default()
}))
.add_plugins(self.evt_plugin.clone())
.insert_resource(SharedResource(self.shared_state.clone()))
.add_systems(Startup, setup_scene)
.add_systems(Update, handle_bevy_event)
.run();
self.is_setup = true;
}
}
/// Setup the scene
fn setup_scene(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
resource: Res<SharedResource>,
) {
let name = resource.0.lock().unwrap().name.clone();
// circular base
commands.spawn((
Mesh3d(meshes.add(Circle::new(4.0))),
MeshMaterial3d(materials.add(Color::WHITE)),
Transform::from_rotation(Quat::from_rotation_x(
-std::f32::consts::FRAC_PI_2,
)),
));
// cube
commands.spawn((
Mesh3d(meshes.add(Cuboid::new(1.0, 1.0, 1.0))),
MeshMaterial3d(materials.add(Color::srgb_u8(124, 144, 255))),
Transform::from_xyz(0.0, 0.5, 0.0),
Cube,
));
// light
commands.spawn((
PointLight {
shadows_enabled: true,
..default()
},
Transform::from_xyz(4.0, 8.0, 4.0),
));
// camera
commands.spawn((
Camera3d::default(),
Transform::from_xyz(-2.5, 4.5, 9.0).looking_at(Vec3::ZERO, Vec3::Y),
));
commands.spawn((Text::new(name), TextFont::default()));
}
/// Move the Cube on event
fn handle_bevy_event(
mut counter_event_reader: EventReader<CounterEvtData>,
mut cube_query: Query<&mut Transform, With<Cube>>,
) {
let mut cube_transform = cube_query.get_single_mut().expect("no cube :(");
for _ev in counter_event_reader.read() {
cube_transform.translation += Vec3::new(0.0, _ev.value, 0.0);
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/bevy3d_ui/src/demos/bevydemo1/mod.rs | projects/bevy3d_ui/src/demos/bevydemo1/mod.rs | pub mod eventqueue;
pub mod scene;
pub mod state;
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/bevy3d_ui/src/demos/bevydemo1/eventqueue/mod.rs | projects/bevy3d_ui/src/demos/bevydemo1/eventqueue/mod.rs | pub mod events;
pub mod plugin;
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/bevy3d_ui/src/demos/bevydemo1/eventqueue/events.rs | projects/bevy3d_ui/src/demos/bevydemo1/eventqueue/events.rs | use bevy::prelude::*;
/// Event Processor
#[derive(Resource)]
pub struct EventProcessor<TSender, TReceiver> {
pub sender: crossbeam_channel::Sender<TSender>,
pub receiver: crossbeam_channel::Receiver<TReceiver>,
}
impl<TSender, TReceiver> Clone for EventProcessor<TSender, TReceiver> {
fn clone(&self) -> Self {
Self {
sender: self.sender.clone(),
receiver: self.receiver.clone(),
}
}
}
/// Events sent from the client to bevy
#[derive(Debug)]
pub enum ClientInEvents {
/// Update the 3d model position from the client
CounterEvt(CounterEvtData),
}
/// Events sent out from bevy to the client
#[derive(Debug)]
pub enum PluginOutEvents {
/// TODO Feed back to the client an event from bevy
Click,
}
/// Input event to update the bevy view from the client
#[derive(Clone, Debug, Event)]
pub struct CounterEvtData {
/// Amount to move on the Y Axis
pub value: f32,
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/bevy3d_ui/src/demos/bevydemo1/eventqueue/plugin.rs | projects/bevy3d_ui/src/demos/bevydemo1/eventqueue/plugin.rs | use super::events::*;
use bevy::prelude::*;
/// Events plugin for bevy
#[derive(Clone)]
pub struct DuplexEventsPlugin {
/// Client processor for sending ClientInEvents, receiving PluginOutEvents
client_processor: EventProcessor<ClientInEvents, PluginOutEvents>,
/// Internal processor for sending PluginOutEvents, receiving ClientInEvents
plugin_processor: EventProcessor<PluginOutEvents, ClientInEvents>,
}
impl DuplexEventsPlugin {
/// Create a new instance
pub fn new() -> DuplexEventsPlugin {
// For sending messages from bevy to the client
let (bevy_sender, client_receiver) = crossbeam_channel::bounded(50);
// For sending message from the client to bevy
let (client_sender, bevy_receiver) = crossbeam_channel::bounded(50);
DuplexEventsPlugin {
client_processor: EventProcessor {
sender: client_sender,
receiver: client_receiver,
},
plugin_processor: EventProcessor {
sender: bevy_sender,
receiver: bevy_receiver,
},
}
}
/// Get the client event processor
pub fn get_processor(
&self,
) -> EventProcessor<ClientInEvents, PluginOutEvents> {
self.client_processor.clone()
}
}
/// Build the bevy plugin and attach
impl Plugin for DuplexEventsPlugin {
fn build(&self, app: &mut App) {
app.insert_resource(self.plugin_processor.clone())
.init_resource::<Events<CounterEvtData>>()
.add_systems(PreUpdate, input_events_system);
}
}
/// Send the event to bevy using EventWriter
fn input_events_system(
int_processor: Res<EventProcessor<PluginOutEvents, ClientInEvents>>,
mut counter_event_writer: EventWriter<CounterEvtData>,
) {
for input_event in int_processor.receiver.try_iter() {
match input_event {
ClientInEvents::CounterEvt(event) => {
// Send event through Bevy's event system
counter_event_writer.send(event);
}
}
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/bevy3d_ui/src/routes/demo1.rs | projects/bevy3d_ui/src/routes/demo1.rs | use crate::demos::bevydemo1::eventqueue::events::{
ClientInEvents, CounterEvtData,
};
use crate::demos::bevydemo1::scene::Scene;
use leptos::prelude::*;
/// 3d view component
#[component]
pub fn Demo1() -> impl IntoView {
// Setup a Counter
let initial_value: i32 = 0;
let step: i32 = 1;
let (value, set_value) = signal(initial_value);
// Setup a bevy 3d scene
let scene = Scene::new("#bevy".to_string());
let sender = scene.get_processor().sender;
let (sender_sig, _set_sender_sig) = signal(sender);
let (scene_sig, _set_scene_sig) = signal(scene);
// We need to add the 3D view onto the canvas post render.
Effect::new(move |_| {
request_animation_frame(move || {
scene_sig.get_untracked().setup();
});
});
view! {
<div>
<button on:click=move |_| set_value.set(0)>"Clear"</button>
<button on:click=move |_| {
set_value.update(|value| *value -= step);
let newpos = (step as f32) / 10.0;
sender_sig
.get()
.send(ClientInEvents::CounterEvt(CounterEvtData { value: -newpos }))
.expect("could not send event");
}>"-1"</button>
<span>"Value: " {value} "!"</span>
<button on:click=move |_| {
set_value.update(|value| *value += step);
let newpos = step as f32 / 10.0;
sender_sig
.get()
.send(ClientInEvents::CounterEvt(CounterEvtData { value: newpos }))
.expect("could not send event");
}>"+1"</button>
</div>
<canvas id="bevy" width="800" height="600"></canvas>
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/projects/bevy3d_ui/src/routes/mod.rs | projects/bevy3d_ui/src/routes/mod.rs | pub mod demo1;
use demo1::Demo1;
use leptos::prelude::*;
use leptos_meta::Meta;
use leptos_meta::Title;
use leptos_meta::{provide_meta_context, MetaTags, Stylesheet};
use leptos_router::components::*;
use leptos_router::StaticSegment;
#[component]
pub fn RootPage() -> impl IntoView {
provide_meta_context();
view! {
<Meta name="charset" content="UTF-8"/>
<Meta name="description" content="Leptonic CSR template"/>
<Meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<Meta name="theme-color" content="#e66956"/>
<Title text="Leptos Bevy3D Example"/>
<Stylesheet href="https://fonts.googleapis.com/css?family=Roboto&display=swap"/>
<MetaTags/>
<Router>
<Routes fallback=move || "Not found.">
<Route path=StaticSegment("") view=Demo1 />
</Routes>
</Router>
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/either_of/src/lib.rs | either_of/src/lib.rs | #![cfg_attr(feature = "no_std", no_std)]
#![forbid(unsafe_code)]
//! Utilities for working with enumerated types that contain one of `2..n` other types.
use core::{
cmp::Ordering,
fmt::Display,
future::Future,
iter::{Product, Sum},
pin::Pin,
task::{Context, Poll},
};
use paste::paste;
use pin_project_lite::pin_project;
#[cfg(not(feature = "no_std"))]
use std::error::Error; // TODO: replace with core::error::Error once MSRV is >= 1.81.0
macro_rules! tuples {
($name:ident + $fut_name:ident + $fut_proj:ident {
$($ty:ident => ($($rest_variant:ident),*) + <$($mapped_ty:ident),+>),+$(,)?
}) => {
tuples!($name + $fut_name + $fut_proj {
$($ty($ty) => ($($rest_variant),*) + <$($mapped_ty),+>),+
});
};
($name:ident + $fut_name:ident + $fut_proj:ident {
$($variant:ident($ty:ident) => ($($rest_variant:ident),*) + <$($mapped_ty:ident),+>),+$(,)?
}) => {
#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
pub enum $name<$($ty),+> {
$($variant ($ty),)+
}
impl<$($ty),+> $name<$($ty),+> {
paste! {
#[allow(clippy::too_many_arguments)]
pub fn map<$([<F $ty>]),+, $([<$ty 1>]),+>(self, $([<$variant:lower>]: [<F $ty>]),+) -> $name<$([<$ty 1>]),+>
where
$([<F $ty>]: FnOnce($ty) -> [<$ty 1>],)+
{
match self {
$($name::$variant(inner) => $name::$variant([<$variant:lower>](inner)),)+
}
}
$(
pub fn [<map_ $variant:lower>]<Fun, [<$ty 1>]>(self, f: Fun) -> $name<$($mapped_ty),+>
where
Fun: FnOnce($ty) -> [<$ty 1>],
{
match self {
$name::$variant(inner) => $name::$variant(f(inner)),
$($name::$rest_variant(inner) => $name::$rest_variant(inner),)*
}
}
pub fn [<inspect_ $variant:lower>]<Fun, [<$ty 1>]>(self, f: Fun) -> Self
where
Fun: FnOnce(&$ty),
{
if let $name::$variant(inner) = &self {
f(inner);
}
self
}
pub fn [<is_ $variant:lower>](&self) -> bool {
matches!(self, $name::$variant(_))
}
pub fn [<as_ $variant:lower>](&self) -> Option<&$ty> {
match self {
$name::$variant(inner) => Some(inner),
_ => None,
}
}
pub fn [<as_ $variant:lower _mut>](&mut self) -> Option<&mut $ty> {
match self {
$name::$variant(inner) => Some(inner),
_ => None,
}
}
pub fn [<unwrap_ $variant:lower>](self) -> $ty {
match self {
$name::$variant(inner) => inner,
_ => panic!(concat!(
"called `unwrap_", stringify!([<$variant:lower>]), "()` on a non-`", stringify!($variant), "` variant of `", stringify!($name), "`"
)),
}
}
pub fn [<into_ $variant:lower>](self) -> Result<$ty, Self> {
match self {
$name::$variant(inner) => Ok(inner),
_ => Err(self),
}
}
)+
}
}
impl<$($ty),+> Display for $name<$($ty),+>
where
$($ty: Display,)+
{
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
$($name::$variant(this) => this.fmt(f),)+
}
}
}
#[cfg(not(feature = "no_std"))]
impl<$($ty),+> Error for $name<$($ty),+>
where
$($ty: Error,)+
{
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
$($name::$variant(this) => this.source(),)+
}
}
}
impl<Item, $($ty),+> Iterator for $name<$($ty),+>
where
$($ty: Iterator<Item = Item>,)+
{
type Item = Item;
fn next(&mut self) -> Option<Self::Item> {
match self {
$($name::$variant(i) => i.next(),)+
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
match self {
$($name::$variant(i) => i.size_hint(),)+
}
}
fn count(self) -> usize
where
Self: Sized,
{
match self {
$($name::$variant(i) => i.count(),)+
}
}
fn last(self) -> Option<Self::Item>
where
Self: Sized,
{
match self {
$($name::$variant(i) => i.last(),)+
}
}
fn nth(&mut self, n: usize) -> Option<Self::Item> {
match self {
$($name::$variant(i) => i.nth(n),)+
}
}
fn for_each<Fun>(self, f: Fun)
where
Self: Sized,
Fun: FnMut(Self::Item),
{
match self {
$($name::$variant(i) => i.for_each(f),)+
}
}
fn collect<Col: FromIterator<Self::Item>>(self) -> Col
where
Self: Sized,
{
match self {
$($name::$variant(i) => i.collect(),)+
}
}
fn partition<Col, Fun>(self, f: Fun) -> (Col, Col)
where
Self: Sized,
Col: Default + Extend<Self::Item>,
Fun: FnMut(&Self::Item) -> bool,
{
match self {
$($name::$variant(i) => i.partition(f),)+
}
}
fn fold<Acc, Fun>(self, init: Acc, f: Fun) -> Acc
where
Self: Sized,
Fun: FnMut(Acc, Self::Item) -> Acc,
{
match self {
$($name::$variant(i) => i.fold(init, f),)+
}
}
fn reduce<Fun>(self, f: Fun) -> Option<Self::Item>
where
Self: Sized,
Fun: FnMut(Self::Item, Self::Item) -> Self::Item,
{
match self {
$($name::$variant(i) => i.reduce(f),)+
}
}
fn all<Fun>(&mut self, f: Fun) -> bool
where
Self: Sized,
Fun: FnMut(Self::Item) -> bool,
{
match self {
$($name::$variant(i) => i.all(f),)+
}
}
fn any<Fun>(&mut self, f: Fun) -> bool
where
Self: Sized,
Fun: FnMut(Self::Item) -> bool,
{
match self {
$($name::$variant(i) => i.any(f),)+
}
}
fn find<Pre>(&mut self, predicate: Pre) -> Option<Self::Item>
where
Self: Sized,
Pre: FnMut(&Self::Item) -> bool,
{
match self {
$($name::$variant(i) => i.find(predicate),)+
}
}
fn find_map<Out, Fun>(&mut self, f: Fun) -> Option<Out>
where
Self: Sized,
Fun: FnMut(Self::Item) -> Option<Out>,
{
match self {
$($name::$variant(i) => i.find_map(f),)+
}
}
fn position<Pre>(&mut self, predicate: Pre) -> Option<usize>
where
Self: Sized,
Pre: FnMut(Self::Item) -> bool,
{
match self {
$($name::$variant(i) => i.position(predicate),)+
}
}
fn max(self) -> Option<Self::Item>
where
Self: Sized,
Self::Item: Ord,
{
match self {
$($name::$variant(i) => i.max(),)+
}
}
fn min(self) -> Option<Self::Item>
where
Self: Sized,
Self::Item: Ord,
{
match self {
$($name::$variant(i) => i.min(),)+
}
}
fn max_by_key<Key: Ord, Fun>(self, f: Fun) -> Option<Self::Item>
where
Self: Sized,
Fun: FnMut(&Self::Item) -> Key,
{
match self {
$($name::$variant(i) => i.max_by_key(f),)+
}
}
fn max_by<Cmp>(self, compare: Cmp) -> Option<Self::Item>
where
Self: Sized,
Cmp: FnMut(&Self::Item, &Self::Item) -> Ordering,
{
match self {
$($name::$variant(i) => i.max_by(compare),)+
}
}
fn min_by_key<Key: Ord, Fun>(self, f: Fun) -> Option<Self::Item>
where
Self: Sized,
Fun: FnMut(&Self::Item) -> Key,
{
match self {
$($name::$variant(i) => i.min_by_key(f),)+
}
}
fn min_by<Cmp>(self, compare: Cmp) -> Option<Self::Item>
where
Self: Sized,
Cmp: FnMut(&Self::Item, &Self::Item) -> Ordering,
{
match self {
$($name::$variant(i) => i.min_by(compare),)+
}
}
fn sum<Out>(self) -> Out
where
Self: Sized,
Out: Sum<Self::Item>,
{
match self {
$($name::$variant(i) => i.sum(),)+
}
}
fn product<Out>(self) -> Out
where
Self: Sized,
Out: Product<Self::Item>,
{
match self {
$($name::$variant(i) => i.product(),)+
}
}
fn cmp<Other>(self, other: Other) -> Ordering
where
Other: IntoIterator<Item = Self::Item>,
Self::Item: Ord,
Self: Sized,
{
match self {
$($name::$variant(i) => i.cmp(other),)+
}
}
fn partial_cmp<Other>(self, other: Other) -> Option<Ordering>
where
Other: IntoIterator,
Self::Item: PartialOrd<Other::Item>,
Self: Sized,
{
match self {
$($name::$variant(i) => i.partial_cmp(other),)+
}
}
// TODO: uncomment once MSRV is >= 1.82.0
// fn is_sorted(self) -> bool
// where
// Self: Sized,
// Self::Item: PartialOrd,
// {
// match self {
// $($name::$variant(i) => i.is_sorted(),)+
// }
// }
//
// fn is_sorted_by<Cmp>(self, compare: Cmp) -> bool
// where
// Self: Sized,
// Cmp: FnMut(&Self::Item, &Self::Item) -> bool,
// {
// match self {
// $($name::$variant(i) => i.is_sorted_by(compare),)+
// }
// }
//
// fn is_sorted_by_key<Fun, Key>(self, f: Fun) -> bool
// where
// Self: Sized,
// Fun: FnMut(Self::Item) -> Key,
// Key: PartialOrd,
// {
// match self {
// $($name::$variant(i) => i.is_sorted_by_key(f),)+
// }
// }
}
impl<Item, $($ty),+> ExactSizeIterator for $name<$($ty),+>
where
$($ty: ExactSizeIterator<Item = Item>,)+
{
fn len(&self) -> usize {
match self {
$($name::$variant(i) => i.len(),)+
}
}
}
impl<Item, $($ty),+> DoubleEndedIterator for $name<$($ty),+>
where
$($ty: DoubleEndedIterator<Item = Item>,)+
{
fn next_back(&mut self) -> Option<Self::Item> {
match self {
$($name::$variant(i) => i.next_back(),)+
}
}
fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
match self {
$($name::$variant(i) => i.nth_back(n),)+
}
}
fn rfind<Pre>(&mut self, predicate: Pre) -> Option<Self::Item>
where
Pre: FnMut(&Self::Item) -> bool,
{
match self {
$($name::$variant(i) => i.rfind(predicate),)+
}
}
}
pin_project! {
#[project = $fut_proj]
pub enum $fut_name<$($ty),+> {
$($variant { #[pin] inner: $ty },)+
}
}
impl<$($ty),+> Future for $fut_name<$($ty),+>
where
$($ty: Future,)+
{
type Output = $name<$($ty::Output),+>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.project();
match this {
$($fut_proj::$variant { inner } => match inner.poll(cx) {
Poll::Pending => Poll::Pending,
Poll::Ready(inner) => Poll::Ready($name::$variant(inner)),
},)+
}
}
}
}
}
tuples!(Either + EitherFuture + EitherFutureProj {
Left(A) => (Right) + <A1, B>,
Right(B) => (Left) + <A, B1>,
});
impl<A, B> Either<A, B> {
pub fn swap(self) -> Either<B, A> {
match self {
Either::Left(a) => Either::Right(a),
Either::Right(b) => Either::Left(b),
}
}
}
impl<A, B> From<Result<A, B>> for Either<A, B> {
fn from(value: Result<A, B>) -> Self {
match value {
Ok(left) => Either::Left(left),
Err(right) => Either::Right(right),
}
}
}
pub trait EitherOr {
type Left;
type Right;
fn either_or<FA, A, FB, B>(self, a: FA, b: FB) -> Either<A, B>
where
FA: FnOnce(Self::Left) -> A,
FB: FnOnce(Self::Right) -> B;
}
impl EitherOr for bool {
type Left = ();
type Right = ();
fn either_or<FA, A, FB, B>(self, a: FA, b: FB) -> Either<A, B>
where
FA: FnOnce(Self::Left) -> A,
FB: FnOnce(Self::Right) -> B,
{
if self {
Either::Left(a(()))
} else {
Either::Right(b(()))
}
}
}
impl<T> EitherOr for Option<T> {
type Left = T;
type Right = ();
fn either_or<FA, A, FB, B>(self, a: FA, b: FB) -> Either<A, B>
where
FA: FnOnce(Self::Left) -> A,
FB: FnOnce(Self::Right) -> B,
{
match self {
Some(t) => Either::Left(a(t)),
None => Either::Right(b(())),
}
}
}
impl<T, E> EitherOr for Result<T, E> {
type Left = T;
type Right = E;
fn either_or<FA, A, FB, B>(self, a: FA, b: FB) -> Either<A, B>
where
FA: FnOnce(Self::Left) -> A,
FB: FnOnce(Self::Right) -> B,
{
match self {
Ok(t) => Either::Left(a(t)),
Err(err) => Either::Right(b(err)),
}
}
}
impl<A, B> EitherOr for Either<A, B> {
type Left = A;
type Right = B;
#[inline]
fn either_or<FA, A1, FB, B1>(self, a: FA, b: FB) -> Either<A1, B1>
where
FA: FnOnce(<Self as EitherOr>::Left) -> A1,
FB: FnOnce(<Self as EitherOr>::Right) -> B1,
{
self.map(a, b)
}
}
#[test]
fn test_either_or() {
let right = false.either_or(|_| 'a', |_| 12);
assert!(matches!(right, Either::Right(12)));
let left = true.either_or(|_| 'a', |_| 12);
assert!(matches!(left, Either::Left('a')));
let left = Some(12).either_or(|a| a, |_| 'a');
assert!(matches!(left, Either::Left(12)));
let right = None.either_or(|a: i32| a, |_| 'a');
assert!(matches!(right, Either::Right('a')));
let result: Result<_, ()> = Ok(1.2f32);
let left = result.either_or(|a| a * 2f32, |b| b);
assert!(matches!(left, Either::Left(2.4f32)));
let result: Result<i32, _> = Err("12");
let right = result.either_or(|a| a, |b| b.chars().next());
assert!(matches!(right, Either::Right(Some('1'))));
let either = Either::<i32, char>::Left(12);
let left = either.either_or(|a| a, |b| b);
assert!(matches!(left, Either::Left(12)));
let either = Either::<i32, char>::Right('a');
let right = either.either_or(|a| a, |b| b);
assert!(matches!(right, Either::Right('a')));
}
tuples!(EitherOf3 + EitherOf3Future + EitherOf3FutureProj {
A => (B, C) + <A1, B, C>,
B => (A, C) + <A, B1, C>,
C => (A, B) + <A, B, C1>,
});
tuples!(EitherOf4 + EitherOf4Future + EitherOf4FutureProj {
A => (B, C, D) + <A1, B, C, D>,
B => (A, C, D) + <A, B1, C, D>,
C => (A, B, D) + <A, B, C1, D>,
D => (A, B, C) + <A, B, C, D1>,
});
tuples!(EitherOf5 + EitherOf5Future + EitherOf5FutureProj {
A => (B, C, D, E) + <A1, B, C, D, E>,
B => (A, C, D, E) + <A, B1, C, D, E>,
C => (A, B, D, E) + <A, B, C1, D, E>,
D => (A, B, C, E) + <A, B, C, D1, E>,
E => (A, B, C, D) + <A, B, C, D, E1>,
});
tuples!(EitherOf6 + EitherOf6Future + EitherOf6FutureProj {
A => (B, C, D, E, F) + <A1, B, C, D, E, F>,
B => (A, C, D, E, F) + <A, B1, C, D, E, F>,
C => (A, B, D, E, F) + <A, B, C1, D, E, F>,
D => (A, B, C, E, F) + <A, B, C, D1, E, F>,
E => (A, B, C, D, F) + <A, B, C, D, E1, F>,
F => (A, B, C, D, E) + <A, B, C, D, E, F1>,
});
tuples!(EitherOf7 + EitherOf7Future + EitherOf7FutureProj {
A => (B, C, D, E, F, G) + <A1, B, C, D, E, F, G>,
B => (A, C, D, E, F, G) + <A, B1, C, D, E, F, G>,
C => (A, B, D, E, F, G) + <A, B, C1, D, E, F, G>,
D => (A, B, C, E, F, G) + <A, B, C, D1, E, F, G>,
E => (A, B, C, D, F, G) + <A, B, C, D, E1, F, G>,
F => (A, B, C, D, E, G) + <A, B, C, D, E, F1, G>,
G => (A, B, C, D, E, F) + <A, B, C, D, E, F, G1>,
});
tuples!(EitherOf8 + EitherOf8Future + EitherOf8FutureProj {
A => (B, C, D, E, F, G, H) + <A1, B, C, D, E, F, G, H>,
B => (A, C, D, E, F, G, H) + <A, B1, C, D, E, F, G, H>,
C => (A, B, D, E, F, G, H) + <A, B, C1, D, E, F, G, H>,
D => (A, B, C, E, F, G, H) + <A, B, C, D1, E, F, G, H>,
E => (A, B, C, D, F, G, H) + <A, B, C, D, E1, F, G, H>,
F => (A, B, C, D, E, G, H) + <A, B, C, D, E, F1, G, H>,
G => (A, B, C, D, E, F, H) + <A, B, C, D, E, F, G1, H>,
H => (A, B, C, D, E, F, G) + <A, B, C, D, E, F, G, H1>,
});
tuples!(EitherOf9 + EitherOf9Future + EitherOf9FutureProj {
A => (B, C, D, E, F, G, H, I) + <A1, B, C, D, E, F, G, H, I>,
B => (A, C, D, E, F, G, H, I) + <A, B1, C, D, E, F, G, H, I>,
C => (A, B, D, E, F, G, H, I) + <A, B, C1, D, E, F, G, H, I>,
D => (A, B, C, E, F, G, H, I) + <A, B, C, D1, E, F, G, H, I>,
E => (A, B, C, D, F, G, H, I) + <A, B, C, D, E1, F, G, H, I>,
F => (A, B, C, D, E, G, H, I) + <A, B, C, D, E, F1, G, H, I>,
G => (A, B, C, D, E, F, H, I) + <A, B, C, D, E, F, G1, H, I>,
H => (A, B, C, D, E, F, G, I) + <A, B, C, D, E, F, G, H1, I>,
I => (A, B, C, D, E, F, G, H) + <A, B, C, D, E, F, G, H, I1>,
});
tuples!(EitherOf10 + EitherOf10Future + EitherOf10FutureProj {
A => (B, C, D, E, F, G, H, I, J) + <A1, B, C, D, E, F, G, H, I, J>,
B => (A, C, D, E, F, G, H, I, J) + <A, B1, C, D, E, F, G, H, I, J>,
C => (A, B, D, E, F, G, H, I, J) + <A, B, C1, D, E, F, G, H, I, J>,
D => (A, B, C, E, F, G, H, I, J) + <A, B, C, D1, E, F, G, H, I, J>,
E => (A, B, C, D, F, G, H, I, J) + <A, B, C, D, E1, F, G, H, I, J>,
F => (A, B, C, D, E, G, H, I, J) + <A, B, C, D, E, F1, G, H, I, J>,
G => (A, B, C, D, E, F, H, I, J) + <A, B, C, D, E, F, G1, H, I, J>,
H => (A, B, C, D, E, F, G, I, J) + <A, B, C, D, E, F, G, H1, I, J>,
I => (A, B, C, D, E, F, G, H, J) + <A, B, C, D, E, F, G, H, I1, J>,
J => (A, B, C, D, E, F, G, H, I) + <A, B, C, D, E, F, G, H, I, J1>,
});
tuples!(EitherOf11 + EitherOf11Future + EitherOf11FutureProj {
A => (B, C, D, E, F, G, H, I, J, K) + <A1, B, C, D, E, F, G, H, I, J, K>,
B => (A, C, D, E, F, G, H, I, J, K) + <A, B1, C, D, E, F, G, H, I, J, K>,
C => (A, B, D, E, F, G, H, I, J, K) + <A, B, C1, D, E, F, G, H, I, J, K>,
D => (A, B, C, E, F, G, H, I, J, K) + <A, B, C, D1, E, F, G, H, I, J, K>,
E => (A, B, C, D, F, G, H, I, J, K) + <A, B, C, D, E1, F, G, H, I, J, K>,
F => (A, B, C, D, E, G, H, I, J, K) + <A, B, C, D, E, F1, G, H, I, J, K>,
G => (A, B, C, D, E, F, H, I, J, K) + <A, B, C, D, E, F, G1, H, I, J, K>,
H => (A, B, C, D, E, F, G, I, J, K) + <A, B, C, D, E, F, G, H1, I, J, K>,
I => (A, B, C, D, E, F, G, H, J, K) + <A, B, C, D, E, F, G, H, I1, J, K>,
J => (A, B, C, D, E, F, G, H, I, K) + <A, B, C, D, E, F, G, H, I, J1, K>,
K => (A, B, C, D, E, F, G, H, I, J) + <A, B, C, D, E, F, G, H, I, J, K1>,
});
tuples!(EitherOf12 + EitherOf12Future + EitherOf12FutureProj {
A => (B, C, D, E, F, G, H, I, J, K, L) + <A1, B, C, D, E, F, G, H, I, J, K, L>,
B => (A, C, D, E, F, G, H, I, J, K, L) + <A, B1, C, D, E, F, G, H, I, J, K, L>,
C => (A, B, D, E, F, G, H, I, J, K, L) + <A, B, C1, D, E, F, G, H, I, J, K, L>,
D => (A, B, C, E, F, G, H, I, J, K, L) + <A, B, C, D1, E, F, G, H, I, J, K, L>,
E => (A, B, C, D, F, G, H, I, J, K, L) + <A, B, C, D, E1, F, G, H, I, J, K, L>,
F => (A, B, C, D, E, G, H, I, J, K, L) + <A, B, C, D, E, F1, G, H, I, J, K, L>,
G => (A, B, C, D, E, F, H, I, J, K, L) + <A, B, C, D, E, F, G1, H, I, J, K, L>,
H => (A, B, C, D, E, F, G, I, J, K, L) + <A, B, C, D, E, F, G, H1, I, J, K, L>,
I => (A, B, C, D, E, F, G, H, J, K, L) + <A, B, C, D, E, F, G, H, I1, J, K, L>,
J => (A, B, C, D, E, F, G, H, I, K, L) + <A, B, C, D, E, F, G, H, I, J1, K, L>,
K => (A, B, C, D, E, F, G, H, I, J, L) + <A, B, C, D, E, F, G, H, I, J, K1, L>,
L => (A, B, C, D, E, F, G, H, I, J, K) + <A, B, C, D, E, F, G, H, I, J, K, L1>,
});
tuples!(EitherOf13 + EitherOf13Future + EitherOf13FutureProj {
A => (B, C, D, E, F, G, H, I, J, K, L, M) + <A1, B, C, D, E, F, G, H, I, J, K, L, M>,
B => (A, C, D, E, F, G, H, I, J, K, L, M) + <A, B1, C, D, E, F, G, H, I, J, K, L, M>,
C => (A, B, D, E, F, G, H, I, J, K, L, M) + <A, B, C1, D, E, F, G, H, I, J, K, L, M>,
D => (A, B, C, E, F, G, H, I, J, K, L, M) + <A, B, C, D1, E, F, G, H, I, J, K, L, M>,
E => (A, B, C, D, F, G, H, I, J, K, L, M) + <A, B, C, D, E1, F, G, H, I, J, K, L, M>,
F => (A, B, C, D, E, G, H, I, J, K, L, M) + <A, B, C, D, E, F1, G, H, I, J, K, L, M>,
G => (A, B, C, D, E, F, H, I, J, K, L, M) + <A, B, C, D, E, F, G1, H, I, J, K, L, M>,
H => (A, B, C, D, E, F, G, I, J, K, L, M) + <A, B, C, D, E, F, G, H1, I, J, K, L, M>,
I => (A, B, C, D, E, F, G, H, J, K, L, M) + <A, B, C, D, E, F, G, H, I1, J, K, L, M>,
J => (A, B, C, D, E, F, G, H, I, K, L, M) + <A, B, C, D, E, F, G, H, I, J1, K, L, M>,
K => (A, B, C, D, E, F, G, H, I, J, L, M) + <A, B, C, D, E, F, G, H, I, J, K1, L, M>,
L => (A, B, C, D, E, F, G, H, I, J, K, M) + <A, B, C, D, E, F, G, H, I, J, K, L1, M>,
M => (A, B, C, D, E, F, G, H, I, J, K, L) + <A, B, C, D, E, F, G, H, I, J, K, L, M1>,
});
tuples!(EitherOf14 + EitherOf14Future + EitherOf14FutureProj {
A => (B, C, D, E, F, G, H, I, J, K, L, M, N) + <A1, B, C, D, E, F, G, H, I, J, K, L, M, N>,
B => (A, C, D, E, F, G, H, I, J, K, L, M, N) + <A, B1, C, D, E, F, G, H, I, J, K, L, M, N>,
C => (A, B, D, E, F, G, H, I, J, K, L, M, N) + <A, B, C1, D, E, F, G, H, I, J, K, L, M, N>,
D => (A, B, C, E, F, G, H, I, J, K, L, M, N) + <A, B, C, D1, E, F, G, H, I, J, K, L, M, N>,
E => (A, B, C, D, F, G, H, I, J, K, L, M, N) + <A, B, C, D, E1, F, G, H, I, J, K, L, M, N>,
F => (A, B, C, D, E, G, H, I, J, K, L, M, N) + <A, B, C, D, E, F1, G, H, I, J, K, L, M, N>,
G => (A, B, C, D, E, F, H, I, J, K, L, M, N) + <A, B, C, D, E, F, G1, H, I, J, K, L, M, N>,
H => (A, B, C, D, E, F, G, I, J, K, L, M, N) + <A, B, C, D, E, F, G, H1, I, J, K, L, M, N>,
I => (A, B, C, D, E, F, G, H, J, K, L, M, N) + <A, B, C, D, E, F, G, H, I1, J, K, L, M, N>,
J => (A, B, C, D, E, F, G, H, I, K, L, M, N) + <A, B, C, D, E, F, G, H, I, J1, K, L, M, N>,
K => (A, B, C, D, E, F, G, H, I, J, L, M, N) + <A, B, C, D, E, F, G, H, I, J, K1, L, M, N>,
L => (A, B, C, D, E, F, G, H, I, J, K, M, N) + <A, B, C, D, E, F, G, H, I, J, K, L1, M, N>,
M => (A, B, C, D, E, F, G, H, I, J, K, L, N) + <A, B, C, D, E, F, G, H, I, J, K, L, M1, N>,
N => (A, B, C, D, E, F, G, H, I, J, K, L, M) + <A, B, C, D, E, F, G, H, I, J, K, L, M, N1>,
});
tuples!(EitherOf15 + EitherOf15Future + EitherOf15FutureProj {
A => (B, C, D, E, F, G, H, I, J, K, L, M, N, O) + <A1, B, C, D, E, F, G, H, I, J, K, L, M, N, O>,
B => (A, C, D, E, F, G, H, I, J, K, L, M, N, O) + <A, B1, C, D, E, F, G, H, I, J, K, L, M, N, O>,
C => (A, B, D, E, F, G, H, I, J, K, L, M, N, O) + <A, B, C1, D, E, F, G, H, I, J, K, L, M, N, O>,
D => (A, B, C, E, F, G, H, I, J, K, L, M, N, O) + <A, B, C, D1, E, F, G, H, I, J, K, L, M, N, O>,
E => (A, B, C, D, F, G, H, I, J, K, L, M, N, O) + <A, B, C, D, E1, F, G, H, I, J, K, L, M, N, O>,
F => (A, B, C, D, E, G, H, I, J, K, L, M, N, O) + <A, B, C, D, E, F1, G, H, I, J, K, L, M, N, O>,
G => (A, B, C, D, E, F, H, I, J, K, L, M, N, O) + <A, B, C, D, E, F, G1, H, I, J, K, L, M, N, O>,
H => (A, B, C, D, E, F, G, I, J, K, L, M, N, O) + <A, B, C, D, E, F, G, H1, I, J, K, L, M, N, O>,
I => (A, B, C, D, E, F, G, H, J, K, L, M, N, O) + <A, B, C, D, E, F, G, H, I1, J, K, L, M, N, O>,
J => (A, B, C, D, E, F, G, H, I, K, L, M, N, O) + <A, B, C, D, E, F, G, H, I, J1, K, L, M, N, O>,
K => (A, B, C, D, E, F, G, H, I, J, L, M, N, O) + <A, B, C, D, E, F, G, H, I, J, K1, L, M, N, O>,
L => (A, B, C, D, E, F, G, H, I, J, K, M, N, O) + <A, B, C, D, E, F, G, H, I, J, K, L1, M, N, O>,
M => (A, B, C, D, E, F, G, H, I, J, K, L, N, O) + <A, B, C, D, E, F, G, H, I, J, K, L, M1, N, O>,
N => (A, B, C, D, E, F, G, H, I, J, K, L, M, O) + <A, B, C, D, E, F, G, H, I, J, K, L, M, N1, O>,
O => (A, B, C, D, E, F, G, H, I, J, K, L, M, N) + <A, B, C, D, E, F, G, H, I, J, K, L, M, N, O1>,
});
tuples!(EitherOf16 + EitherOf16Future + EitherOf16FutureProj {
A => (B, C, D, E, F, G, H, I, J, K, L, M, N, O, P) + <A1, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P>,
B => (A, C, D, E, F, G, H, I, J, K, L, M, N, O, P) + <A, B1, C, D, E, F, G, H, I, J, K, L, M, N, O, P>,
C => (A, B, D, E, F, G, H, I, J, K, L, M, N, O, P) + <A, B, C1, D, E, F, G, H, I, J, K, L, M, N, O, P>,
D => (A, B, C, E, F, G, H, I, J, K, L, M, N, O, P) + <A, B, C, D1, E, F, G, H, I, J, K, L, M, N, O, P>,
E => (A, B, C, D, F, G, H, I, J, K, L, M, N, O, P) + <A, B, C, D, E1, F, G, H, I, J, K, L, M, N, O, P>,
F => (A, B, C, D, E, G, H, I, J, K, L, M, N, O, P) + <A, B, C, D, E, F1, G, H, I, J, K, L, M, N, O, P>,
G => (A, B, C, D, E, F, H, I, J, K, L, M, N, O, P) + <A, B, C, D, E, F, G1, H, I, J, K, L, M, N, O, P>,
H => (A, B, C, D, E, F, G, I, J, K, L, M, N, O, P) + <A, B, C, D, E, F, G, H1, I, J, K, L, M, N, O, P>,
I => (A, B, C, D, E, F, G, H, J, K, L, M, N, O, P) + <A, B, C, D, E, F, G, H, I1, J, K, L, M, N, O, P>,
J => (A, B, C, D, E, F, G, H, I, K, L, M, N, O, P) + <A, B, C, D, E, F, G, H, I, J1, K, L, M, N, O, P>,
K => (A, B, C, D, E, F, G, H, I, J, L, M, N, O, P) + <A, B, C, D, E, F, G, H, I, J, K1, L, M, N, O, P>,
L => (A, B, C, D, E, F, G, H, I, J, K, M, N, O, P) + <A, B, C, D, E, F, G, H, I, J, K, L1, M, N, O, P>,
M => (A, B, C, D, E, F, G, H, I, J, K, L, N, O, P) + <A, B, C, D, E, F, G, H, I, J, K, L, M1, N, O, P>,
N => (A, B, C, D, E, F, G, H, I, J, K, L, M, O, P) + <A, B, C, D, E, F, G, H, I, J, K, L, M, N1, O, P>,
O => (A, B, C, D, E, F, G, H, I, J, K, L, M, N, P) + <A, B, C, D, E, F, G, H, I, J, K, L, M, N, O1, P>,
P => (A, B, C, D, E, F, G, H, I, J, K, L, M, N, O) + <A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P1>,
});
/// Matches over the first expression and returns an either ([`Either`], [`EitherOf3`], ... [`EitherOf8`])
/// composed of the values returned by the match arms.
///
/// The pattern syntax is exactly the same as found in a match arm.
///
/// # Examples
///
/// ```
/// # use either_of::*;
/// let either2 = either!(Some("hello"),
/// Some(s) => s.len(),
/// None => 0.0,
/// );
/// assert!(matches!(either2, Either::<usize, f64>::Left(5)));
///
/// let either3 = either!(Some("admin"),
/// Some("admin") => "hello admin",
/// Some(_) => 'x',
/// _ => 0,
/// );
/// assert!(matches!(either3, EitherOf3::<&str, char, i32>::A("hello admin")));
/// ```
#[macro_export]
macro_rules! either {
($match:expr, $left_pattern:pat => $left_expression:expr, $right_pattern:pat => $right_expression:expr$(,)?) => {
match $match {
$left_pattern => $crate::Either::Left($left_expression),
$right_pattern => $crate::Either::Right($right_expression),
}
};
($match:expr, $a_pattern:pat => $a_expression:expr, $b_pattern:pat => $b_expression:expr, $c_pattern:pat => $c_expression:expr$(,)?) => {
match $match {
$a_pattern => $crate::EitherOf3::A($a_expression),
$b_pattern => $crate::EitherOf3::B($b_expression),
$c_pattern => $crate::EitherOf3::C($c_expression),
}
};
($match:expr, $a_pattern:pat => $a_expression:expr, $b_pattern:pat => $b_expression:expr, $c_pattern:pat => $c_expression:expr, $d_pattern:pat => $d_expression:expr$(,)?) => {
match $match {
$a_pattern => $crate::EitherOf4::A($a_expression),
$b_pattern => $crate::EitherOf4::B($b_expression),
$c_pattern => $crate::EitherOf4::C($c_expression),
$d_pattern => $crate::EitherOf4::D($d_expression),
}
};
($match:expr, $a_pattern:pat => $a_expression:expr, $b_pattern:pat => $b_expression:expr, $c_pattern:pat => $c_expression:expr, $d_pattern:pat => $d_expression:expr, $e_pattern:pat => $e_expression:expr$(,)?) => {
match $match {
$a_pattern => $crate::EitherOf5::A($a_expression),
$b_pattern => $crate::EitherOf5::B($b_expression),
$c_pattern => $crate::EitherOf5::C($c_expression),
$d_pattern => $crate::EitherOf5::D($d_expression),
$e_pattern => $crate::EitherOf5::E($e_expression),
}
};
($match:expr, $a_pattern:pat => $a_expression:expr, $b_pattern:pat => $b_expression:expr, $c_pattern:pat => $c_expression:expr, $d_pattern:pat => $d_expression:expr, $e_pattern:pat => $e_expression:expr, $f_pattern:pat => $f_expression:expr$(,)?) => {
match $match {
$a_pattern => $crate::EitherOf6::A($a_expression),
$b_pattern => $crate::EitherOf6::B($b_expression),
$c_pattern => $crate::EitherOf6::C($c_expression),
$d_pattern => $crate::EitherOf6::D($d_expression),
$e_pattern => $crate::EitherOf6::E($e_expression),
$f_pattern => $crate::EitherOf6::F($f_expression),
}
};
($match:expr, $a_pattern:pat => $a_expression:expr, $b_pattern:pat => $b_expression:expr, $c_pattern:pat => $c_expression:expr, $d_pattern:pat => $d_expression:expr, $e_pattern:pat => $e_expression:expr, $f_pattern:pat => $f_expression:expr, $g_pattern:pat => $g_expression:expr$(,)?) => {
match $match {
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | true |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/or_poisoned/src/lib.rs | or_poisoned/src/lib.rs | //! Provides a simple trait that unwraps the locks provide by [`std::sync::RwLock`].
//!
//! In every case, this is the same as calling `.expect("lock poisoned")`. However, it
//! does not use `.unwrap()` or `.expect()`, which makes it easier to distinguish from
//! other forms of unwrapping when reading code.
//!
//! ```rust
//! use or_poisoned::OrPoisoned;
//! use std::sync::RwLock;
//!
//! let lock = RwLock::new(String::from("Hello!"));
//!
//! let read = lock.read().or_poisoned();
//! // this is identical to
//! let read = lock.read().unwrap();
//! ```
#![forbid(unsafe_code)]
#![deny(missing_docs)]
use std::sync::{
LockResult, MutexGuard, PoisonError, RwLockReadGuard, RwLockWriteGuard,
};
/// Unwraps a lock.
pub trait OrPoisoned {
/// The inner guard type.
type Inner;
/// Unwraps the lock.
///
/// ## Panics
///
/// Will panic if the lock is poisoned.
fn or_poisoned(self) -> Self::Inner;
}
impl<'a, T: ?Sized> OrPoisoned
for Result<RwLockReadGuard<'a, T>, PoisonError<RwLockReadGuard<'a, T>>>
{
type Inner = RwLockReadGuard<'a, T>;
fn or_poisoned(self) -> Self::Inner {
self.expect("lock poisoned")
}
}
impl<'a, T: ?Sized> OrPoisoned
for Result<RwLockWriteGuard<'a, T>, PoisonError<RwLockWriteGuard<'a, T>>>
{
type Inner = RwLockWriteGuard<'a, T>;
fn or_poisoned(self) -> Self::Inner {
self.expect("lock poisoned")
}
}
impl<'a, T: ?Sized> OrPoisoned for LockResult<MutexGuard<'a, T>> {
type Inner = MutexGuard<'a, T>;
fn or_poisoned(self) -> Self::Inner {
self.expect("lock poisoned")
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/next_tuple/src/lib.rs | next_tuple/src/lib.rs | //! Defines a trait that allows you to extend a tuple, by returning
//! a new tuple with an element of an arbitrary type added.
#![no_std]
#![allow(non_snake_case)]
#![forbid(unsafe_code)]
#![deny(missing_docs)]
/// Allows extending a tuple, or creating a new tuple, by adding the next value.
pub trait NextTuple {
/// The type that will be returned by adding another value of type `Next` to the end of the current type.
type Output<Next>;
/// Adds the next value and returns the result.
fn next_tuple<Next>(self, next: Next) -> Self::Output<Next>;
}
macro_rules! impl_tuple_builder {
($($ty:ident),*) => {
impl<$($ty),*> NextTuple for ($($ty,)*) {
type Output<Next> = ($($ty,)* Next);
fn next_tuple<Next>(self, next: Next) -> Self::Output<Next> {
let ($($ty,)*) = self;
($($ty,)* next)
}
}
};
}
impl NextTuple for () {
type Output<Next> = (Next,);
fn next_tuple<Next>(self, next: Next) -> Self::Output<Next> {
(next,)
}
}
impl_tuple_builder!(A);
impl_tuple_builder!(A, B);
impl_tuple_builder!(A, B, C);
impl_tuple_builder!(A, B, C, D);
impl_tuple_builder!(A, B, C, D, E);
impl_tuple_builder!(A, B, C, D, E, F);
impl_tuple_builder!(A, B, C, D, E, F, G);
impl_tuple_builder!(A, B, C, D, E, F, G, H);
impl_tuple_builder!(A, B, C, D, E, F, G, H, I);
impl_tuple_builder!(A, B, C, D, E, F, G, H, I, J);
impl_tuple_builder!(A, B, C, D, E, F, G, H, I, J, K);
impl_tuple_builder!(A, B, C, D, E, F, G, H, I, J, K, L);
impl_tuple_builder!(A, B, C, D, E, F, G, H, I, J, K, L, M);
impl_tuple_builder!(A, B, C, D, E, F, G, H, I, J, K, L, M, N);
impl_tuple_builder!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O);
impl_tuple_builder!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P);
impl_tuple_builder!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q);
impl_tuple_builder!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R);
impl_tuple_builder!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S);
impl_tuple_builder!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T);
impl_tuple_builder!(
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U
);
impl_tuple_builder!(
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V
);
impl_tuple_builder!(
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W
);
impl_tuple_builder!(
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X
);
impl_tuple_builder!(
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y
);
impl_tuple_builder!(
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y,
Z
);
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.