27 Commits

Author SHA1 Message Date
ed0c107a80 Worked with @jkassman on match adding code
All checks were successful
Build Crate / build (push) Successful in 3m19s
2024-09-03 00:39:43 -04:00
f319f41835 Merge branch 'ft/integrate-daisy-ui'
Some checks failed
Build Crate / build (push) Failing after 1m50s
2024-08-31 03:12:38 -04:00
3e2163dbf3 Add themes, update layout, fix pages
Some checks failed
Build Crate / build (push) Failing after 1m53s
2024-08-31 03:12:28 -04:00
659037ec00 Moved pending username to new global state
Some checks failed
Build Crate / build (push) Failing after 1m45s
2024-08-30 03:38:02 -04:00
8be43c95d4 Merge branch 'main' into ft/integrate-daisy-ui
Some checks failed
Build Crate / build (push) Failing after 1m43s
2024-08-30 02:38:30 -04:00
72bac10714 Fix margins for submit buttons
Some checks failed
Build Crate / build (push) Failing after 1m43s
2024-08-30 02:38:23 -04:00
ec2edd1d2a Merge branch 'ft/integrate-daisy-ui'
Some checks failed
Build Crate / build (push) Failing after 1m48s
2024-08-30 02:16:31 -04:00
a288a35225 Updated remaining modals to daisyui
Some checks failed
Build Crate / build (push) Failing after 1m47s
Made username carry over between modals too
2024-08-30 02:16:15 -04:00
d82a5e2c65 Updated alert to daisyui
Some checks failed
Build Crate / build (push) Failing after 1m44s
2024-08-30 01:25:42 -04:00
97420b84c8 Changed login to be daisyui
Some checks failed
Build Crate / build (push) Failing after 1m44s
2024-08-30 01:10:24 -04:00
82648cfbae Add initial daisy ui
Some checks failed
Build Crate / build (push) Failing after 1m45s
2024-08-29 23:29:28 -04:00
4cb809f20f Merge branch 'ft/add-generic-components'
Some checks failed
Build Crate / build (push) Failing after 1m42s
2024-08-29 23:15:35 -04:00
abbece5f53 Add static components, change error design
Some checks failed
Build Crate / build (push) Failing after 1m45s
2024-08-29 23:15:22 -04:00
510158f381 Fix error component, add to all pages
Some checks failed
Build Crate / build (push) Failing after 1m48s
2024-08-29 22:43:55 -04:00
d523373b8e WIP components
Some checks failed
Build Crate / build (push) Failing after 1m2s
2024-08-29 21:23:39 -04:00
d25fb283cc Mode templates to folders
Some checks failed
Build Crate / build (push) Failing after 1m46s
2024-08-29 16:28:05 -04:00
988d0f9807 Fix login error
All checks were successful
Build Crate / build (push) Successful in 1m46s
2024-08-29 01:43:14 -04:00
2409cd1f52 Merge branch 'fix/login-error'
All checks were successful
Build Crate / build (push) Successful in 1m42s
2024-08-29 00:41:46 -04:00
8714f65a0f Remove reset after login error
All checks were successful
Build Crate / build (push) Successful in 16m5s
2024-08-29 00:37:24 -04:00
893a9b5a06 Merge branch 'ft/add-error-handling'
All checks were successful
Build Crate / build (push) Successful in 1m56s
2024-08-29 00:18:59 -04:00
d6e62b98aa Fix more clippy warnings
All checks were successful
Build Crate / build (push) Successful in 1m45s
2024-08-28 23:54:56 -04:00
aca0b83dd4 Implement login form error, more clippy fixes
All checks were successful
Build Crate / build (push) Successful in 1m47s
2024-08-28 23:45:10 -04:00
9a42ed5b80 Fix forget password
All checks were successful
Build Crate / build (push) Successful in 1m46s
2024-08-28 23:14:27 -04:00
ed780c9585 Fix more clippy issues, implement forgot password
All checks were successful
Build Crate / build (push) Successful in 1m48s
2024-08-28 23:03:52 -04:00
1faaf65aad Clean up imports
All checks were successful
Build Crate / build (push) Successful in 1m47s
2024-08-28 21:55:23 -04:00
df0d7d6c0d Add registration errors
All checks were successful
Build Crate / build (push) Successful in 1m48s
2024-08-28 17:29:51 -04:00
56ea1f12c7 Merge branch 'ft/add-db-and-auth'
All checks were successful
Build Crate / build (push) Successful in 1m45s
2024-08-28 16:54:39 -04:00
43 changed files with 933 additions and 468 deletions

View File

@@ -40,6 +40,8 @@ jobs:
run: npm install -g sass run: npm install -g sass
- name: Install tailwindcss via npm - name: Install tailwindcss via npm
run: npm install -D tailwindcss run: npm install -D tailwindcss
- name: Install daisy ui via npm
run: npm i -D daisyui@latest
- name: Compile css - name: Compile css
run: npm run build run: npm run build
# TODO -> Remove wasm-opt-version once perseus is updated # TODO -> Remove wasm-opt-version once perseus is updated

View File

@@ -16,11 +16,17 @@ Run `curl --proto '=https' --tlsv1.3 https://sh.rustup.rs -sSf | sh`
https://nodejs.org/en https://nodejs.org/en
(todo look into:) (todo look into:)
https://pnpm.io/ https://pnpm.io/
`npm i -D daisyui@latest`
### Unix based systems: ### Unix based systems:
`sudo apt install nodejs` `sudo apt install nodejs`
`sudo apt install npm` `sudo apt install npm`
`npm i -D daisyui@latest`
For easy UI see:
https://daisyui.com/components/button/
## 3. Install Perseus, for real-time updates while developing ## 3. Install Perseus, for real-time updates while developing
@@ -36,7 +42,7 @@ https://pnpm.io/
`cargo install sea-orm-cli@1.0.0-rc.5` `cargo install sea-orm-cli@1.0.0-rc.5`
## 5. Install tailwindcss, for styling ## 6. Install tailwindcss, for styling
`npm install -D tailwindcss` `npm install -D tailwindcss`

View File

@@ -11,6 +11,7 @@
"author": "", "author": "",
"license": "ISC", "license": "ISC",
"devDependencies": { "devDependencies": {
"daisyui": "^4.12.10",
"tailwindcss": "^3.4.10" "tailwindcss": "^3.4.10"
} }
} }

View File

@@ -4,14 +4,26 @@ use serde::{Deserialize, Serialize};
use sycamore::prelude::*; use sycamore::prelude::*;
use web_sys::Event; use web_sys::Event;
use crate::{
components::{
static_components::close_button::CloseButtonSvg, sub_components::error_block::ErrorBlock,
},
global_state::AppStateRx,
};
cfg_if::cfg_if! { cfg_if::cfg_if! {
if #[cfg(client)] { if #[cfg(client)] {
use crate::{ use crate::{
state_enums::{ OpenState}, state_enums::{ OpenState},
templates::{get_api_path}, templates::get_api_path,
global_state::{self, AppStateRx}, endpoints::FORGOT_PASSWORD,
models::{
auth::ForgotPasswordRequest,
generic::GenericResponse,
},
}; };
use reqwest::StatusCode; use reqwest::StatusCode;
} }
} }
@@ -25,6 +37,7 @@ lazy_static! {
struct ForgotPasswordFormState { struct ForgotPasswordFormState {
username: String, username: String,
how_to_reach: String, how_to_reach: String,
error: String,
} }
impl ForgotPasswordFormStateRx { impl ForgotPasswordFormStateRx {
@@ -32,6 +45,7 @@ impl ForgotPasswordFormStateRx {
fn reset(&self) { fn reset(&self) {
self.username.set(String::new()); self.username.set(String::new());
self.how_to_reach.set(String::new()); self.how_to_reach.set(String::new());
self.error.set(String::new());
} }
} }
@@ -44,12 +58,18 @@ fn forgot_password_form_capsule<G: Html>(
state: &ForgotPasswordFormStateRx, state: &ForgotPasswordFormStateRx,
_props: ForgotPasswordFormProps, _props: ForgotPasswordFormProps,
) -> View<G> { ) -> View<G> {
// If there's a tentative username, set it
let global_state = Reactor::<G>::from_cx(cx).get_global_state::<AppStateRx>(cx);
state
.username
.set((*global_state.auth.pending_username.get()).clone());
global_state.auth.pending_username.set(String::new());
let close_modal = move |_event: Event| { let close_modal = move |_event: Event| {
#[cfg(client)] #[cfg(client)]
{ {
spawn_local_scoped(cx, async move { spawn_local_scoped(cx, async move {
let global_state = Reactor::<G>::from_cx(cx).get_global_state::<AppStateRx>(cx); let global_state = Reactor::<G>::from_cx(cx).get_global_state::<AppStateRx>(cx);
// Close modal // Close modal
state.reset(); state.reset();
global_state global_state
@@ -63,6 +83,26 @@ fn forgot_password_form_capsule<G: Html>(
#[cfg(client)] #[cfg(client)]
{ {
spawn_local_scoped(cx, async move { spawn_local_scoped(cx, async move {
let request = ForgotPasswordRequest {
username: state.username.get().as_ref().clone(),
contact_info: state.how_to_reach.get().as_ref().clone(),
};
// // @todo clean up error handling
let client = reqwest::Client::new();
let response = client
.post(get_api_path(FORGOT_PASSWORD).as_str())
.json(&request)
.send()
.await
.unwrap();
let status = response.status();
let response_data = response.json::<GenericResponse>().await.unwrap();
if status != StatusCode::OK {
state.error.set(response_data.status);
return;
}
let global_state = Reactor::<G>::from_cx(cx).get_global_state::<AppStateRx>(cx); let global_state = Reactor::<G>::from_cx(cx).get_global_state::<AppStateRx>(cx);
// Close modal // Close modal
@@ -76,27 +116,26 @@ fn forgot_password_form_capsule<G: Html>(
}; };
view! { cx, view! { cx,
div (class="overflow-x-hidden overflow-y-auto fixed h-modal md:h-full top-4 left-0 right-0 md:inset-0 z-50 justify-center items-center"){ dialog (class="modal-open modal modal-bottom sm:modal-middle animate-none") {
div (class="relative md:mx-auto w-full md:w-1/2 lg:w-1/3 z-0 my-10") { div (class="modal-box"){
div (class="bg-white rounded-lg shadow relative dark:bg-gray-700"){ // Header row - title and close button
div (class="flex justify-end p-2"){ h3 (class="text-lg font-bold mb-4 text-center"){"Forgot Password"}
button (on:click = close_modal, class="text-gray-400 bg-transparent hover:bg-gray-200 hover:text-gray-900 rounded-lg text-sm p-1.5 ml-auto inline-flex items-center dark:hover:bg-gray-800 dark:hover:text-white"){ button (on:click = close_modal, class = "btn btn-circle right-2 top-2 absolute") { CloseButtonSvg {} }
"Back"
}
}
div (class="space-y-6 px-6 lg:px-8 pb-4 sm:pb-6 xl:pb-8") {
h3 (class="text-xl font-medium text-gray-900 dark:text-white"){"Forgot Password"}
div {
label (class="text-sm font-medium text-gray-900 block mb-2 dark:text-gray-300") {"Username"}
input (bind:value = state.username, class="bg-gray-50 border border-gray-300 text-gray-900 sm:text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-600 dark:border-gray-500 dark:placeholder-gray-400 dark:text-white") {}
}
div {
label (class="text-sm font-medium text-gray-900 block mb-2 dark:text-gray-300"){"Contact Info"}
input (bind:value = state.how_to_reach, class="bg-gray-50 border border-gray-300 text-gray-900 sm:text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-600 dark:border-gray-500 dark:placeholder-gray-400 dark:text-white"){}
}
button (on:click = handle_submit, class="w-full text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800"){"Submit"} // Add component for handling error messages
} ErrorBlock(error = state.error.clone())
// Username field
div (class = "label") { span (class = "label-text") { "Username" } }
input (bind:value = state.username, class = "input input-bordered w-full")
// Password field
div (class = "label") { span (class = "label-text") { "Contact Info" } }
input (bind:value = state.how_to_reach, class = "input input-bordered w-full")
// Submit button
div (class = "flex justify-center mt-6") {
button (on:click = handle_submit, class="btn"){"Submit"}
} }
} }
} }
@@ -113,7 +152,8 @@ pub fn get_capsule<G: Html>() -> Capsule<G, ForgotPasswordFormProps> {
#[engine_only_fn] #[engine_only_fn]
async fn get_build_state(_info: StateGeneratorInfo<()>) -> ForgotPasswordFormState { async fn get_build_state(_info: StateGeneratorInfo<()>) -> ForgotPasswordFormState {
ForgotPasswordFormState { ForgotPasswordFormState {
username: "".to_owned(), username: String::new(),
how_to_reach: "".to_owned(), how_to_reach: String::new(),
error: String::new(),
} }
} }

View File

@@ -4,15 +4,21 @@ use serde::{Deserialize, Serialize};
use sycamore::prelude::*; use sycamore::prelude::*;
use web_sys::Event; use web_sys::Event;
use crate::{
components::{
static_components::close_button::CloseButtonSvg, sub_components::error_block::ErrorBlock,
},
global_state::AppStateRx,
};
cfg_if::cfg_if! { cfg_if::cfg_if! {
if #[cfg(client)] { if #[cfg(client)] {
use crate::{ use crate::{
models::auth::{LoginInfo, LoginResponse},
endpoints::LOGIN, endpoints::LOGIN,
state_enums::{LoginState, OpenState}, models::auth::{LoginInfo, LoginResponse, WebAuthInfo},
templates::{get_api_path}, models::generic::GenericResponse,
global_state::{self, AppStateRx}, state_enums::{OpenState},
models::auth::WebAuthInfo, templates::get_api_path,
}; };
use reqwest::StatusCode; use reqwest::StatusCode;
} }
@@ -28,6 +34,7 @@ struct LoginFormState {
username: String, username: String,
password: String, password: String,
remember_me: bool, remember_me: bool,
error: String,
} }
impl LoginFormStateRx { impl LoginFormStateRx {
@@ -36,6 +43,7 @@ impl LoginFormStateRx {
self.username.set(String::new()); self.username.set(String::new());
self.password.set(String::new()); self.password.set(String::new());
self.remember_me.set(false); self.remember_me.set(false);
self.error.set(String::new());
} }
} }
@@ -50,11 +58,19 @@ fn login_form_capsule<G: Html>(
state: &LoginFormStateRx, state: &LoginFormStateRx,
props: LoginFormProps, props: LoginFormProps,
) -> View<G> { ) -> View<G> {
// If there's a tentative username, set it
let global_state = Reactor::<G>::from_cx(cx).get_global_state::<AppStateRx>(cx);
state
.username
.set((*global_state.auth.pending_username.get()).clone());
global_state.auth.pending_username.set(String::new());
let close_modal = move |_event: Event| { let close_modal = move |_event: Event| {
#[cfg(client)] #[cfg(client)]
{ {
spawn_local_scoped(cx, async move { spawn_local_scoped(cx, async move {
let global_state = Reactor::<G>::from_cx(cx).get_global_state::<AppStateRx>(cx); let global_state = Reactor::<G>::from_cx(cx).get_global_state::<AppStateRx>(cx);
state.reset();
global_state.modals_open.login.set(OpenState::Closed) global_state.modals_open.login.set(OpenState::Closed)
}); });
} }
@@ -65,23 +81,19 @@ fn login_form_capsule<G: Html>(
{ {
spawn_local_scoped(cx, async move { spawn_local_scoped(cx, async move {
let global_state = Reactor::<G>::from_cx(cx).get_global_state::<AppStateRx>(cx); let global_state = Reactor::<G>::from_cx(cx).get_global_state::<AppStateRx>(cx);
// Update tentative username
global_state
.auth
.pending_username
.set((*state.username.get()).clone());
// Open new modal
global_state global_state
.modals_open .modals_open
.forgot_password .forgot_password
.set(OpenState::Open); .set(OpenState::Open);
// Close modal
state.reset();
global_state.modals_open.login.set(OpenState::Closed);
});
}
};
let handle_register = move |_event: Event| {
#[cfg(client)]
{
spawn_local_scoped(cx, async move {
let global_state = Reactor::<G>::from_cx(cx).get_global_state::<AppStateRx>(cx);
global_state.modals_open.register.set(OpenState::Open);
// Close modal // Close modal
state.reset(); state.reset();
global_state.modals_open.login.set(OpenState::Closed); global_state.modals_open.login.set(OpenState::Closed);
@@ -93,7 +105,7 @@ fn login_form_capsule<G: Html>(
#[cfg(client)] #[cfg(client)]
{ {
spawn_local_scoped(cx, async move { spawn_local_scoped(cx, async move {
let remember_me = state.remember_me.get().as_ref().clone(); let remember_me = *state.remember_me.get().as_ref();
let username = state.username.get().as_ref().clone(); let username = state.username.get().as_ref().clone();
let login_info = LoginInfo { let login_info = LoginInfo {
username: username.clone(), username: username.clone(),
@@ -113,8 +125,8 @@ fn login_form_capsule<G: Html>(
let global_state = Reactor::<G>::from_cx(cx).get_global_state::<AppStateRx>(cx); let global_state = Reactor::<G>::from_cx(cx).get_global_state::<AppStateRx>(cx);
if response.status() != StatusCode::OK { if response.status() != StatusCode::OK {
// todo update to some type of alert let response = response.json::<GenericResponse>().await.unwrap();
state.username.set(response.status().to_string()); state.error.set(response.status.to_string());
return; return;
} }
@@ -136,45 +148,44 @@ fn login_form_capsule<G: Html>(
}; };
view! { cx, view! { cx,
div (class="overflow-x-hidden overflow-y-auto fixed h-modal md:h-full top-4 left-0 right-0 md:inset-0 z-50 justify-center items-center"){ dialog (class="modal-open modal modal-bottom sm:modal-middle") {
div (class="relative md:mx-auto w-full md:w-1/2 lg:w-1/3 z-0 my-10") { div (class="modal-box"){
div (class="bg-white rounded-lg shadow relative dark:bg-gray-700"){ // Header row - title and close button
div (class="flex justify-end p-2"){ h3 (class="text-lg font-bold mb-4 text-center"){"Sign in"}
button (on:click = close_modal, class="text-gray-400 bg-transparent hover:bg-gray-200 hover:text-gray-900 rounded-lg text-sm p-1.5 ml-auto inline-flex items-center dark:hover:bg-gray-800 dark:hover:text-white"){ button (on:click = close_modal, class = "btn btn-circle right-2 top-2 absolute") { CloseButtonSvg {} }
"Back"
} // Add component for handling error messages
} ErrorBlock(error = state.error.clone())
div (class="space-y-6 px-6 lg:px-8 pb-4 sm:pb-6 xl:pb-8") {
h3 (class="text-xl font-medium text-gray-900 dark:text-white"){"Sign in"} // Username field
div { div (class = "label") { span (class = "label-text") { "Username" } }
label (class="text-sm font-medium text-gray-900 block mb-2 dark:text-gray-300") {"Username"} input (bind:value = state.username, class = "input input-bordered w-full")
input (bind:value = state.username, class="bg-gray-50 border border-gray-300 text-gray-900 sm:text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-600 dark:border-gray-500 dark:placeholder-gray-400 dark:text-white") {}
} // Password field
div { div (class = "label") { span (class = "label-text") { "Password" } }
label (class="text-sm font-medium text-gray-900 block mb-2 dark:text-gray-300"){"Password"} input (bind:value = state.password, type = "password", class = "input input-bordered w-full")
input (bind:value = state.password, type = "password", class="bg-gray-50 border border-gray-300 text-gray-900 sm:text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-600 dark:border-gray-500 dark:placeholder-gray-400 dark:text-white"){}
} // Remember me button and forget password button
div (class="flex justify-between"){ div (class="flex justify-between items-center mt-1"){
// Remember me button
(match props.remember_me { (match props.remember_me {
true => { view!{ cx, true => { view!{ cx,
div (class="flex items-start"){ div (class = "flex items-start form-control") {
div (class="flex items-center h-5"){ label (class = "label cursor-pointer") {
input (bind:checked = state.remember_me, type = "checkbox", class="w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600") {} span (class = "label-text mr-4") { "Remember me" }
} input (bind:checked = state.remember_me, type = "checkbox", class = "checkbox")
div (class="text-sm ml-3"){
label (class="font-medium text-gray-900 dark:text-gray-300"){"Remember me"}
} }
} }
}}, }},
false => view!{cx, }, false => view!{cx, },
}) })
button (on:click = handle_forgot_password, class="text-sm text-blue-700 hover:underline dark:text-blue-500"){"Lost Password?"} // Forget password button
} button (on:click = handle_forgot_password, class="flex link link-primary"){"Lost Password?"}
button (on:click = handle_log_in, class="w-full text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800"){"Log in"}
div (class="text-sm font-medium text-gray-500 dark:text-gray-300"){
button (on:click = handle_register, class="text-blue-700 hover:underline dark:text-blue-500"){"Create account"}
}
} }
// Log in button
div (class = "flex justify-center") {
button (on:click = handle_log_in, class="btn"){"Log in"}
} }
} }
} }
@@ -191,8 +202,9 @@ pub fn get_capsule<G: Html>() -> Capsule<G, LoginFormProps> {
#[engine_only_fn] #[engine_only_fn]
async fn get_build_state(_info: StateGeneratorInfo<()>) -> LoginFormState { async fn get_build_state(_info: StateGeneratorInfo<()>) -> LoginFormState {
LoginFormState { LoginFormState {
username: "".to_owned(), username: String::new(),
password: "".to_owned(), password: String::new(),
remember_me: false, remember_me: false,
error: String::new(),
} }
} }

View File

@@ -4,15 +4,21 @@ use serde::{Deserialize, Serialize};
use sycamore::prelude::*; use sycamore::prelude::*;
use web_sys::Event; use web_sys::Event;
use crate::components::{
static_components::close_button::CloseButtonSvg, sub_components::error_block::ErrorBlock,
};
cfg_if::cfg_if! { cfg_if::cfg_if! {
if #[cfg(client)] { if #[cfg(client)] {
use crate::{ use crate::{
models::auth::{RegisterRequest}, models::auth::{RegisterRequest},
endpoints::REGISTER, endpoints::REGISTER,
state_enums::{LoginState, OpenState}, state_enums::OpenState,
templates::{get_api_path}, templates::get_api_path,
global_state::{self, AppStateRx}, global_state::AppStateRx,
models::auth::WebAuthInfo, models::{
generic::GenericResponse
},
}; };
use reqwest::StatusCode; use reqwest::StatusCode;
} }
@@ -30,6 +36,7 @@ struct RegisterFormState {
nickname: String, nickname: String,
registration_code: String, registration_code: String,
email: String, email: String,
error: String,
} }
impl RegisterFormStateRx { impl RegisterFormStateRx {
@@ -40,6 +47,7 @@ impl RegisterFormStateRx {
self.nickname.set(String::new()); self.nickname.set(String::new());
self.registration_code.set(String::new()); self.registration_code.set(String::new());
self.email.set(String::new()); self.email.set(String::new());
self.error.set(String::new());
} }
} }
@@ -90,16 +98,22 @@ fn register_form_capsule<G: Html>(
.unwrap(); .unwrap();
let global_state = Reactor::<G>::from_cx(cx).get_global_state::<AppStateRx>(cx); let global_state = Reactor::<G>::from_cx(cx).get_global_state::<AppStateRx>(cx);
let status = response.status();
if response.status() != StatusCode::OK { let response_data = response.json::<GenericResponse>().await.unwrap();
if status != StatusCode::OK {
// todo update to some type of alert // todo update to some type of alert
state.username.set(response.status().to_string()); state.error.set(response_data.status);
return; return;
} }
// Update tentative username
global_state
.auth
.pending_username
.set((*state.username.get()).clone());
// Open login modal // Open login modal
global_state.modals_open.login.set(OpenState::Open); global_state.modals_open.login.set(OpenState::Open);
state.reset();
// Close modal // Close modal
state.reset(); state.reset();
@@ -109,53 +123,48 @@ fn register_form_capsule<G: Html>(
}; };
view! { cx, view! { cx,
div (class="overflow-x-hidden overflow-y-auto fixed h-modal md:h-full top-4 left-0 right-0 md:inset-0 z-50 justify-center items-center"){ dialog (class="modal-open modal modal-bottom sm:modal-middle"){
div (class="relative md:mx-auto w-full md:w-1/2 lg:w-1/3 z-0 my-10") { div (class="modal-box") {
div (class="bg-white rounded-lg shadow relative dark:bg-gray-700"){ // Header row - title and close button
div (class="flex justify-end p-2"){ h3 (class="text-lg font-bold mb-4 text-center"){"Register"}
button (on:click = close_modal, class="text-gray-400 bg-transparent hover:bg-gray-200 hover:text-gray-900 rounded-lg text-sm p-1.5 ml-auto inline-flex items-center dark:hover:bg-gray-800 dark:hover:text-white"){ button (on:click = close_modal, class = "btn btn-circle right-2 top-2 absolute") { CloseButtonSvg {} }
"Back"
} // Add component for handling error messages
} ErrorBlock(error = state.error.clone())
div (class="space-y-6 px-6 lg:px-8 pb-4 sm:pb-6 xl:pb-8") {
h3 (class="text-xl font-medium text-gray-900 dark:text-white"){"Register"} // Username field
div { div (class = "label") { span (class = "label-text") { "Username" } }
label (class="text-sm font-medium text-gray-900 block mb-2 dark:text-gray-300") {"Username"} input (bind:value = state.username, class = "input input-bordered w-full")
input (bind:value = state.username, class="bg-gray-50 border border-gray-300 text-gray-900 sm:text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-600 dark:border-gray-500 dark:placeholder-gray-400 dark:text-white") {}
} // Password field
div { div (class = "label") { span (class = "label-text") { "Password" } }
label (class="text-sm font-medium text-gray-900 block mb-2 dark:text-gray-300"){"Password"} input (bind:value = state.password, type = "password", class = "input input-bordered w-full")
input (bind:value = state.password, type = "password", class="bg-gray-50 border border-gray-300 text-gray-900 sm:text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-600 dark:border-gray-500 dark:placeholder-gray-400 dark:text-white"){}
}
(match props.registration_code { (match props.registration_code {
true => { view! {cx, true => { view! {cx,
div { div (class = "label") { span (class = "label-text") { "Registration Code" } }
label (class="text-sm font-medium text-gray-900 block mb-2 dark:text-gray-300"){"Registration code"} input (bind:value = state.registration_code, class = "input input-bordered w-full")
input (bind:value = state.registration_code, class="bg-gray-50 border border-gray-300 text-gray-900 sm:text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-600 dark:border-gray-500 dark:placeholder-gray-400 dark:text-white"){}
}
}}, }},
false => {view!{cx,}}, false => {view!{cx,}},
}) })
(match props.nickname { (match props.nickname {
true => { view! {cx, true => { view! {cx,
div { div (class = "label") { span (class = "label-text") { "Nickname (Optional)" } }
label (class="text-sm font-medium text-gray-900 block mb-2 dark:text-gray-300"){"Nickname (optional)"} input (bind:value = state.nickname, class = "input input-bordered w-full")
input (bind:value = state.nickname, class="bg-gray-50 border border-gray-300 text-gray-900 sm:text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-600 dark:border-gray-500 dark:placeholder-gray-400 dark:text-white"){}
}
}}, }},
false => {view!{cx,}}, false => {view!{cx,}},
}) })
(match props.email { (match props.email {
true => { view! {cx, true => { view! {cx,
div { div (class = "label") { span (class = "label-text") { "Email (Optional)" } }
label (class="text-sm font-medium text-gray-900 block mb-2 dark:text-gray-300"){"Email (optional)"} input (bind:value = state.email, class = "input input-bordered w-full")
input (bind:value = state.email, class="bg-gray-50 border border-gray-300 text-gray-900 sm:text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-600 dark:border-gray-500 dark:placeholder-gray-400 dark:text-white"){}
}
}}, }},
false => {view!{cx,}}, false => {view!{cx,}},
}) })
button (on:click = handle_register, class="w-full text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800"){"Register"}
} // Register button
div (class = "flex justify-center mt-6") {
button (on:click = handle_register, class="btn"){"Register"}
} }
} }
} }
@@ -174,6 +183,7 @@ async fn get_build_state(_info: StateGeneratorInfo<()>) -> RegisterFormState {
RegisterFormState { RegisterFormState {
username: String::new(), username: String::new(),
password: String::new(), password: String::new(),
error: String::new(),
nickname: String::new(), nickname: String::new(),
registration_code: String::new(), registration_code: String::new(),
email: String::new(), email: String::new(),

View File

@@ -1,29 +1,98 @@
use std::sync::Arc;
use perseus::prelude::*; use perseus::prelude::*;
use sycamore::prelude::*; use sycamore::prelude::*;
use web_sys::Event; use web_sys::Event;
use crate::{ use crate::{
capsules::{ components::static_components::menu_button::MenuButtonSvg,
forgot_password_form::{ForgotPasswordFormProps, FORGOT_PASSWORD_FORM},
login_form::{LoginFormProps, LOGIN_FORM},
},
endpoints::LOGIN,
global_state::AppStateRx, global_state::AppStateRx,
models::auth::LoginInfo, state_enums::{ContentState, LoginState},
state_enums::{GameState, LoginState, OpenState},
}; };
cfg_if::cfg_if! {
if #[cfg(client)] {
use crate::{
state_enums::OpenState,
};
}
}
#[derive(Prop)] #[derive(Prop)]
pub struct HeaderProps<'a> { pub struct HeaderProps {
pub game: GameState, pub content_state: ContentState,
pub title: &'a str, }
// TODO update to have user preferences
#[component]
fn LinkList<G: Html>(cx: Scope) -> View<G> {
// Get global state to get style info
let global_state = Reactor::<G>::from_cx(cx).get_global_state::<AppStateRx>(cx);
view! { cx,
li {
a (href = "pool") {
label (class = "swap") {
input (
type="radio",
name = "theme-dropdown",
class = "theme-controller",
value = (*global_state.style.theme.pool.get()),
) {}
p (class = (
if *global_state.style.theme.current.get() == *global_state.style.theme.pool.get(){
"font-bold"
}
else {
""
}
)){ "Pool" }
}
}
}
li {
a (href = "table_tennis") {
label (class = "swap") {
input (
type="radio",
name = "theme-dropdown",
class = "theme-controller",
value = (*global_state.style.theme.table_tennis.get()),
) {}
p (class = (
if *global_state.style.theme.current.get() == *global_state.style.theme.table_tennis.get(){
"font-bold"
}
else {
""
}
)){ "Table Tennis" }
}
}
}
li {
a (href = "pickleball") {
label (class = "swap") {
input (
type="radio",
name = "theme-dropdown",
class = "theme-controller",
value = (*global_state.style.theme.pickleball.get()),
) {}
p (class = (
if *global_state.style.theme.current.get() == *global_state.style.theme.pickleball.get(){
"font-bold"
}
else {
""
}
)){ "Pickleball" }
}
}
}
}
} }
#[component] #[component]
pub fn Header<'a, G: Html>(cx: Scope<'a>, HeaderProps { game, title }: HeaderProps<'a>) -> View<G> { pub fn Header<G: Html>(cx: Scope, props: HeaderProps) -> View<G> {
// Get global state to get authentication info
let global_state = Reactor::<G>::from_cx(cx).get_global_state::<AppStateRx>(cx); let global_state = Reactor::<G>::from_cx(cx).get_global_state::<AppStateRx>(cx);
let handle_log_in = move |_event: Event| { let handle_log_in = move |_event: Event| {
@@ -57,50 +126,46 @@ pub fn Header<'a, G: Html>(cx: Scope<'a>, HeaderProps { game, title }: HeaderPro
}; };
view! { cx, view! { cx,
header { header (class="navbar bg-base-100") {
div (class = "flex items-center justify-between w-full md:text-center h-20") { // Navigation
div(class = "flex-1") {} div (class="navbar-start") {
div (class="dropdown") {
div (tabindex="0", role="button", class="btn btn-ghost lg:hidden") { MenuButtonSvg {} }
ul (tabindex = "0", class = "menu menu-sm dropdown-content bg-base-100 rounded-box z-[1] mt-3 w-52 p-2 shadow" ) {
LinkList {}
}
}
ul (class="menu menu-horizontal px-1 hidden lg:flex") {
LinkList {}
}
}
// Title // Title
div(class = "text-gray-700 text-2xl font-semibold py-2") { div (class="navbar-center lg:flex") {
"Pool Elo - Season 1" (props.content_state.to_string())
} }
// User buttons
// Login / register or user buttons div (class="navbar-end") {
div(class = "flex-1 py-2") {( (match *global_state.auth.state.get() {
match *global_state.auth.state.get() { LoginState::Authenticated => { view! { cx,
LoginState::NotAuthenticated => { button(on:click = handle_log_out, class = "btn btn-primary mr-2") {
view! { cx,
button(on:click = handle_register, class = "text-gray-900 bg-white border border-gray-300 focus:outline-none hover:bg-gray-100 focus:ring-4 focus:ring-gray-100 font-medium rounded-lg text-sm px-5 py-2.5 me-2 mb-2 dark:bg-gray-800 dark:text-white dark:border-gray-600 dark:hover:bg-gray-700 dark:hover:border-gray-600 dark:focus:ring-gray-700") {
"Register"
}
button(on:click = handle_log_in, class = "text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 me-2 mb-2 dark:bg-blue-600 dark:hover:bg-blue-700 focus:outline-none dark:focus:ring-blue-800") {
"Log in"
}
}
}
LoginState::Authenticated => {
view! { cx,
div {
"Hello "
(global_state.auth.username.get().as_ref().clone().unwrap_or("".to_owned()))
}
button(on:click = handle_log_out, class = "text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 me-2 mb-2 dark:bg-blue-600 dark:hover:bg-blue-700 focus:outline-none dark:focus:ring-blue-800") {
"Log out" "Log out"
} }
} },
LoginState::NotAuthenticated => { view! { cx,
button(on:click = handle_register, class = "btn btn-primary mr-2") {
"Register"
} }
button(on:click = handle_log_in, class = "btn btn-secondary mr-2") {
"Log in"
} }
// Will only appear for a few seconds } },
LoginState::Unknown => { LoginState::Unknown => { view! { cx,
view! { cx,
div (class = "px-5 py-2.5 me-2 mb-2") { div (class = "px-5 py-2.5 me-2 mb-2") {
"Loading..." "Loading..."
} }
} } },
},
}) })
} }
} }
} }
} }
}

View File

@@ -4,18 +4,16 @@ use crate::{
login_form::{LoginFormProps, LOGIN_FORM}, login_form::{LoginFormProps, LOGIN_FORM},
register_form::{RegisterFormProps, REGISTER_FORM}, register_form::{RegisterFormProps, REGISTER_FORM},
}, },
components::header::{Header, HeaderProps}, components::header::Header,
global_state::AppStateRx, global_state::AppStateRx,
state_enums::{GameState, LoginState, OpenState}, state_enums::{ContentState, OpenState},
}; };
use perseus::prelude::*; use perseus::prelude::*;
use sycamore::prelude::*; use sycamore::prelude::*;
use web_sys::Event;
#[derive(Prop)] #[derive(Prop)]
pub struct LayoutProps<'a, G: Html> { pub struct LayoutProps<'a, G: Html> {
pub game: GameState, pub content_state: ContentState,
pub title: &'a str,
pub children: Children<'a, G>, pub children: Children<'a, G>,
} }
@@ -25,22 +23,38 @@ pub struct LayoutProps<'a, G: Html> {
pub fn Layout<'a, G: Html>( pub fn Layout<'a, G: Html>(
cx: Scope<'a>, cx: Scope<'a>,
LayoutProps { LayoutProps {
game, content_state,
title,
children, children,
}: LayoutProps<'a, G>, }: LayoutProps<'a, G>,
) -> View<G> { ) -> View<G> {
let children = children.call(cx);
let global_state = Reactor::<G>::from_cx(cx).get_global_state::<AppStateRx>(cx); let global_state = Reactor::<G>::from_cx(cx).get_global_state::<AppStateRx>(cx);
// Set the theme
global_state.style.theme.current.set(match content_state {
ContentState::None => (*global_state.style.theme.default.get()).clone(),
ContentState::Pool => (*global_state.style.theme.pool.get()).clone(),
ContentState::Pickleball => (*global_state.style.theme.pickleball.get()).clone(),
ContentState::TableTennis => (*global_state.style.theme.table_tennis.get()).clone(),
});
#[cfg(client)]
let _ = web_sys::window()
.unwrap()
.document()
.unwrap()
.document_element()
.unwrap()
.set_attribute("data-theme", &global_state.style.theme.current.get());
let children = children.call(cx);
// Check if the client is authenticated or not // Check if the client is authenticated or not
#[cfg(client)] #[cfg(client)]
global_state.auth.detect_state(); global_state.auth.detect_state();
let content_state_header = content_state.clone();
view! { cx, view! { cx,
// Main page header, including login functionality // Main page header, including login functionality
Header(game = game, title = title) Header(content_state = content_state_header)
// Modals // Modals
section(class = "flex-2") { section(class = "flex-2") {
@@ -89,24 +103,25 @@ pub fn Layout<'a, G: Html>(
} }
main(style = "my-8") { main(style = "my-8") {
(match content_state {
ContentState::None => view!{ cx, },
ContentState::Pool => view!{ cx,
// Body header // Body header
div {
div (class = "container mx-auto px-6 py-3") { div (class = "container mx-auto px-6 py-3") {
nav (class = "sm:flex sm:justify-center sm:items-center mt-4 hidden") { nav (class = "sm:flex sm:justify-center sm:items-center mt-4 hidden") {
div (class = "flex flex-col sm:flex-row"){ div (class = "flex flex-col sm:flex-row"){
a(href = "add-game-form", a(href = "pool/add-game-form",
class = "mt-3 text-gray-600 hover:underline sm:mx-3 sm:mt-0" class = "mt-3 text-gray-600 hover:underline sm:mx-3 sm:mt-0"
) { "Add game result" } ) { "Add game result" }
a(href = "one-v-one-board", a(href = "pool/one-v-one-board",
class = "mt-3 text-gray-600 hover:underline sm:mx-3 sm:mt-0" class = "mt-3 text-gray-600 hover:underline sm:mx-3 sm:mt-0"
) { "1v1 Leaderboard" } ) { "1v1 Leaderboard" }
a(href = "overall-board", a(href = "pool/overall-board",
class = "mt-3 text-gray-600 hover:underline sm:mx-3 sm:mt-0" class = "mt-3 text-gray-600 hover:underline sm:mx-3 sm:mt-0"
) { "Overall Leaderboard" } ) { "Overall Leaderboard" }
} }
} }
} }
}
// Content body // Content body
div(class = "container mx-auto px-6") { div(class = "container mx-auto px-6") {
div(class = "md:flex mt-8 md:-mx-4") { div(class = "md:flex mt-8 md:-mx-4") {
@@ -115,6 +130,10 @@ pub fn Layout<'a, G: Html>(
} }
} }
} }
},
ContentState::Pickleball => view!{ cx, },
ContentState::TableTennis => view!{ cx, },
})
} }
} }
} }

View File

@@ -1,2 +1,4 @@
mod header; mod header;
pub mod layout; pub mod layout;
pub mod static_components;
pub mod sub_components;

View File

@@ -0,0 +1,21 @@
use perseus::prelude::*;
use sycamore::prelude::*;
#[component]
pub fn CloseButtonSvg<G: Html>(cx: Scope) -> View<G> {
view! { cx,
svg (
xmlns = "http://www.w3.org/2000/svg",
class = "h-6 w-6 stroke-primary",
fill = "none",
viewBox = "0 0 24 24",
) {
path (
stroke-linecap = "round",
stroke-linejoin = "round",
stroke-width = "2",
d = "M6 18L18 6M6 6l12 12"
){}
}
}
}

View File

@@ -0,0 +1,22 @@
use perseus::prelude::*;
use sycamore::prelude::*;
#[component]
pub fn ErrorSvg<G: Html>(cx: Scope) -> View<G> {
view! { cx,
svg (
xmlns="http://www.w3.org/2000/svg",
class="h-6 w-6 shrink-0 stroke-current",
fill="none",
viewBox="0 0 24 24",
)
{
path (
stroke-linecap="round",
stroke-linejoin="round",
stroke-width="2",
d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z",
){}
}
}
}

View File

@@ -0,0 +1,20 @@
use perseus::prelude::*;
use sycamore::prelude::*;
#[component]
pub fn MenuButtonSvg<G: Html>(cx: Scope) -> View<G> {
view! { cx,
svg (
xmlns="http://www.w3.org/2000/svg",
class="h-5 w-5",
fill="none",
viewBox="0 0 24 24",
stroke="currentColor"){
path (
stroke-linecap="round",
stroke-linejoin="round",
stroke-width="2",
d="M4 6h16M4 12h8m-8 6h16") {}
}
}
}

View File

@@ -0,0 +1,3 @@
pub mod close_button;
pub mod indicator;
pub mod menu_button;

View File

@@ -0,0 +1,25 @@
use perseus::prelude::*;
use sycamore::prelude::*;
use crate::components::static_components::indicator::ErrorSvg;
#[component(inline_props)]
pub fn ErrorBlock<'a, G: Html>(cx: Scope<'a>, error: RcSignal<String>) -> View<G> {
let error = create_ref(cx, error);
let is_empty = create_selector(cx, || error.get().is_empty());
view! { cx,
(match !(*is_empty.get()) {
true => { view!{cx,
div (role="alert", class="alert alert-error") {
// Error icon
ErrorSvg {}
// Error text
span {(*error.get())}
}
}},
false => {view!{cx,}},
})
}
}

View File

@@ -0,0 +1 @@
pub mod error_block;

View File

@@ -1,4 +1,7 @@
pub const REGISTER: &str = "/api/register"; pub const REGISTER: &str = "/api/register";
pub const LOGIN: &str = "/api/login"; pub const LOGIN: &str = "/api/login";
pub const ADD_MATCH: &str = "/api/add-match";
// TODO -> remove once it's used
#[cfg(engine)]
pub const LOGIN_TEST: &str = "/api/login-test"; pub const LOGIN_TEST: &str = "/api/login-test";
pub const FORGOT_PASSWORD: &str = "/api/forgot-password"; pub const FORGOT_PASSWORD: &str = "/api/forgot-password";

View File

@@ -4,16 +4,10 @@ use perseus::{prelude::*, state::GlobalStateCreator};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::{ use crate::{
models::auth::{Claims, WebAuthInfo}, models::auth::WebAuthInfo,
state_enums::{LoginState, OpenState}, state_enums::{LoginState, OpenState},
}; };
cfg_if::cfg_if! {
if #[cfg(engine)] {
}
}
#[derive(Serialize, Deserialize, ReactiveState, Clone)] #[derive(Serialize, Deserialize, ReactiveState, Clone)]
#[rx(alias = "AppStateRx")] #[rx(alias = "AppStateRx")]
pub struct AppState { pub struct AppState {
@@ -21,18 +15,78 @@ pub struct AppState {
pub auth: AuthData, pub auth: AuthData,
#[rx(nested)] #[rx(nested)]
pub modals_open: ModalOpenData, pub modals_open: ModalOpenData,
#[rx(nested)]
pub style: StyleData,
} }
#[derive(Serialize, Deserialize, ReactiveState, Clone)] #[derive(Serialize, Deserialize, ReactiveState, Clone)]
#[rx(alias = "AuthDataRx")] #[rx(alias = "AuthDataRx")]
pub struct AuthData { pub struct AuthData {
pub state: LoginState, pub state: LoginState,
pub pending_username: String,
pub username: Option<String>, pub username: Option<String>,
pub remember_me: Option<bool>, pub remember_me: Option<bool>,
pub auth_info: Option<WebAuthInfo>, pub auth_info: Option<WebAuthInfo>,
} }
#[derive(Serialize, Deserialize, ReactiveState, Clone)]
#[rx(alias = "ModalOpenDataRx")]
pub struct ModalOpenData {
pub login: OpenState,
pub register: OpenState,
pub forgot_password: OpenState,
}
#[derive(Serialize, Deserialize, ReactiveState, Clone)]
#[rx(alias = "StyleDataRx")]
pub struct StyleData {
#[rx(nested)]
pub theme: ThemeData,
}
#[derive(Serialize, Deserialize, ReactiveState, Clone)]
#[rx(alias = "ThemeDataRx")]
pub struct ThemeData {
pub current: String,
pub pool: String,
pub pickleball: String,
pub table_tennis: String,
pub default: String,
}
pub fn get_global_state_creator() -> GlobalStateCreator {
GlobalStateCreator::new().build_state_fn(get_build_state)
}
#[engine_only_fn]
pub async fn get_build_state() -> AppState {
AppState {
auth: AuthData {
state: LoginState::Unknown,
pending_username: String::new(),
username: None,
remember_me: None,
auth_info: None,
},
modals_open: ModalOpenData {
login: OpenState::Closed,
register: OpenState::Closed,
forgot_password: OpenState::Closed,
},
style: StyleData {
theme: ThemeData {
current: "light".to_owned(),
pool: "autumn".to_owned(),
pickleball: "lemonade".to_owned(),
table_tennis: "nord".to_owned(),
default: "light".to_owned(),
},
},
}
}
impl AuthDataRx { impl AuthDataRx {
#[cfg(client)]
pub fn handle_log_in(&self, auth_info: WebAuthInfo) { pub fn handle_log_in(&self, auth_info: WebAuthInfo) {
// Save new token to persistent storage // Save new token to persistent storage
if auth_info.remember_me { if auth_info.remember_me {
@@ -52,11 +106,11 @@ impl AuthDataRx {
// Save token to session storage // Save token to session storage
self.username.set(Some(auth_info.username.clone())); self.username.set(Some(auth_info.username.clone()));
self.remember_me.set(Some(auth_info.remember_me.clone())); self.remember_me.set(Some(auth_info.remember_me));
self.auth_info.set(Some(auth_info)); self.auth_info.set(Some(auth_info));
self.state.set(LoginState::Authenticated); self.state.set(LoginState::Authenticated);
} }
#[cfg(client)]
pub fn handle_log_out(&self) { pub fn handle_log_out(&self) {
// Delete persistent storage // Delete persistent storage
// TODO -> handle error if local storage is not readable in browser // TODO -> handle error if local storage is not readable in browser
@@ -77,35 +131,6 @@ impl AuthDataRx {
} }
} }
#[derive(Serialize, Deserialize, ReactiveState, Clone)]
#[rx(alias = "ModalOpenDataRx")]
pub struct ModalOpenData {
pub login: OpenState,
pub register: OpenState,
pub forgot_password: OpenState,
}
pub fn get_global_state_creator() -> GlobalStateCreator {
GlobalStateCreator::new().build_state_fn(get_build_state)
}
#[engine_only_fn]
pub async fn get_build_state() -> AppState {
AppState {
auth: AuthData {
state: LoginState::Unknown,
username: None,
remember_me: None,
auth_info: None,
},
modals_open: ModalOpenData {
login: OpenState::Closed,
register: OpenState::Closed,
forgot_password: OpenState::Closed,
},
}
}
// Client only code to check if they're authenticated // Client only code to check if they're authenticated
#[cfg(client)] #[cfg(client)]
impl AuthDataRx { impl AuthDataRx {

View File

@@ -71,16 +71,19 @@ pub fn main<G: Html>() -> PerseusApp<G> {
PerseusApp::new() PerseusApp::new()
.global_state_creator(crate::global_state::get_global_state_creator()) .global_state_creator(crate::global_state::get_global_state_creator())
.template(crate::templates::index::get_template()) .template(crate::templates::index::get_template())
.template(crate::templates::add_game_form::get_template()) .template(crate::templates::pickleball::index::get_template())
.template(crate::templates::one_v_one_board::get_template()) .template(crate::templates::pool::index::get_template())
.template(crate::templates::overall_board::get_template()) .template(crate::templates::pool::add_game_form::get_template())
.template(crate::templates::pool::one_v_one_board::get_template())
.template(crate::templates::pool::overall_board::get_template())
.template(crate::templates::table_tennis::index::get_template())
.capsule_ref(&*crate::capsules::login_form::LOGIN_FORM) .capsule_ref(&*crate::capsules::login_form::LOGIN_FORM)
.capsule_ref(&*crate::capsules::forgot_password_form::FORGOT_PASSWORD_FORM) .capsule_ref(&*crate::capsules::forgot_password_form::FORGOT_PASSWORD_FORM)
.capsule_ref(&*crate::capsules::register_form::REGISTER_FORM) .capsule_ref(&*crate::capsules::register_form::REGISTER_FORM)
.error_views(crate::error_views::get_error_views()) .error_views(crate::error_views::get_error_views())
.index_view(|cx| { .index_view(|cx| {
view! { cx, view! { cx,
html (class = "flex w-full h-full"){ html (class = "flex w-full h-full", data-theme = "light"){
head { head {
meta(charset = "UTF-8") meta(charset = "UTF-8")
meta(name = "viewport", content = "width=device-width, initial-scale=1.0") meta(name = "viewport", content = "width=device-width, initial-scale=1.0")

10
src/models/game_result.rs Normal file
View File

@@ -0,0 +1,10 @@
use serde::{Deserialize, Serialize};
use crate::entity::sea_orm_active_enums::GameType;
#[derive(Serialize, Deserialize, Clone)]
pub struct GameResult {
pub winner: String,
pub loser: String,
pub game_type: GameType,
}

View File

@@ -6,11 +6,13 @@ pub struct GenericResponse {
} }
impl GenericResponse { impl GenericResponse {
#[cfg(engine)]
pub fn ok() -> Self { pub fn ok() -> Self {
GenericResponse { GenericResponse {
status: String::new(), status: String::new(),
} }
} }
#[cfg(engine)]
pub fn err(msg: &str) -> Self { pub fn err(msg: &str) -> Self {
GenericResponse { GenericResponse {
status: msg.to_string(), status: msg.to_string(),

View File

@@ -1,2 +1,3 @@
pub mod auth; pub mod auth;
pub mod game_result;
pub mod generic; pub mod generic;

View File

@@ -1,13 +1,40 @@
use crate::{models::auth::ForgotPasswordRequest, server::server_state::ServerState}; use crate::{
entity::{prelude::*, user},
models::{auth::ForgotPasswordRequest, generic::GenericResponse},
server::server_state::ServerState,
};
use axum::{ use axum::{
extract::{Json, State}, extract::{Json, State},
http::{HeaderMap, StatusCode}, http::StatusCode,
}; };
use sea_orm::DatabaseConnection; use sea_orm::{ActiveModelTrait, ColumnTrait, EntityTrait, IntoActiveModel, QueryFilter, Set};
pub async fn post_forgot_password( pub async fn post_forgot_password(
State(state): State<ServerState>, State(state): State<ServerState>,
Json(password_request): Json<ForgotPasswordRequest>, Json(password_request): Json<ForgotPasswordRequest>,
) -> StatusCode { ) -> (StatusCode, Json<GenericResponse>) {
StatusCode::OK // Get user
let existing_user: Option<user::Model> = User::find()
.filter(user::Column::Username.eq(password_request.username))
.one(&state.db_conn)
.await
.unwrap();
match existing_user {
Some(user) => {
let mut user = user.into_active_model();
user.forgot_password_request = Set(Some(password_request.contact_info));
let user = user.update(&state.db_conn).await;
match user {
Ok(_) => (StatusCode::OK, Json(GenericResponse::ok())),
Err(_) => (
StatusCode::BAD_REQUEST,
Json(GenericResponse::err("Database error")),
),
}
}
None => (
StatusCode::BAD_REQUEST,
Json(GenericResponse::err("Username doesn't exist")),
),
}
} }

View File

@@ -1,30 +1,27 @@
use crate::entity::prelude::*;
use crate::models::auth::{Claims, LoginInfo, LoginResponse};
use crate::{ use crate::{
entity::user::{self, Entity}, entity::{
models::auth::RegisterRequest, prelude::*,
user::{self},
},
models::{
auth::{Claims, LoginInfo, LoginResponse},
generic::GenericResponse,
},
server::server_state::ServerState, server::server_state::ServerState,
}; };
use argon2::password_hash::rand_core::OsRng; use argon2::{Argon2, PasswordHash, PasswordVerifier};
use argon2::password_hash::SaltString;
use argon2::Argon2;
use argon2::PasswordHash;
use argon2::PasswordHasher;
use argon2::PasswordVerifier;
use axum::{ use axum::{
extract::{Json, State}, extract::{Json, State},
http::{HeaderMap, StatusCode}, http::{HeaderMap, StatusCode},
}; };
use futures::sink::Fanout;
use sea_orm::ColumnTrait;
use sea_orm::EntityTrait;
use sea_orm::InsertResult;
use sea_orm::QueryFilter;
use sea_orm::Set;
use jsonwebtoken::{decode, encode, DecodingKey, EncodingKey, Header, Validation}; use jsonwebtoken::{decode, encode, DecodingKey, EncodingKey, Header, Validation};
use sea_orm::{ColumnTrait, EntityTrait, QueryFilter};
pub async fn credentials_are_correct(username: &str, password: &str, state: &ServerState) -> bool { pub async fn credentials_are_correct(
username: &str,
password: &str,
state: &ServerState,
) -> Result<(), String> {
// Get user // Get user
let existing_user: Option<user::Model> = User::find() let existing_user: Option<user::Model> = User::find()
.filter(user::Column::Username.eq(username)) .filter(user::Column::Username.eq(username))
@@ -35,28 +32,35 @@ pub async fn credentials_are_correct(username: &str, password: &str, state: &Ser
Some(user) => user.password_hash_and_salt, Some(user) => user.password_hash_and_salt,
None => { None => {
// @todo make dummy password hash // @todo make dummy password hash
return false; return Err("Username doesn't exist".to_owned());
} }
}; };
return Argon2::default() match Argon2::default().verify_password(
.verify_password(
password.as_bytes(), password.as_bytes(),
&PasswordHash::new(hash_to_check.as_str()).unwrap(), &PasswordHash::new(hash_to_check.as_str()).unwrap(),
) ) {
.is_ok(); Ok(_) => Ok(()),
Err(_) => Err("Invalid credentials".to_owned()),
}
} }
pub async fn post_login_user( pub async fn post_login_user(
State(state): State<ServerState>, State(state): State<ServerState>,
Json(login_info): Json<LoginInfo>, Json(login_info): Json<LoginInfo>,
) -> Result<Json<LoginResponse>, StatusCode> { ) -> (
StatusCode,
Result<Json<LoginResponse>, Json<GenericResponse>>,
) {
let user_authenticated = let user_authenticated =
credentials_are_correct(&login_info.username, &login_info.password, &state); credentials_are_correct(&login_info.username, &login_info.password, &state);
match user_authenticated.await { match user_authenticated.await {
false => Err(StatusCode::UNAUTHORIZED), Err(why) => (
true => { StatusCode::UNAUTHORIZED,
Err(Json(GenericResponse::err(why.as_str()))),
),
Ok(_) => {
let expires = match login_info.remember_me { let expires = match login_info.remember_me {
true => chrono::Utc::now() + chrono::Duration::days(365), true => chrono::Utc::now() + chrono::Duration::days(365),
false => chrono::Utc::now() + chrono::Duration::days(1), false => chrono::Utc::now() + chrono::Duration::days(1),
@@ -73,17 +77,21 @@ pub async fn post_login_user(
&EncodingKey::from_secret("secret".as_ref()), &EncodingKey::from_secret("secret".as_ref()),
) { ) {
Ok(token) => token, Ok(token) => token,
Err(_) => return Err(StatusCode::INTERNAL_SERVER_ERROR), Err(_) => {
return (
StatusCode::INTERNAL_SERVER_ERROR,
Err(Json(GenericResponse::err("Failed to get token"))),
)
}
}; };
let resp = LoginResponse { token, expires }; (StatusCode::OK, Ok(Json(LoginResponse { token, expires })))
Ok(Json(resp))
} }
} }
} }
pub async fn post_test_login( pub async fn post_test_login(
State(state): State<ServerState>, State(_): State<ServerState>,
header_map: HeaderMap, header_map: HeaderMap,
) -> Result<Json<String>, StatusCode> { ) -> Result<Json<String>, StatusCode> {
if let Some(auth_header) = header_map.get("Authorization") { if let Some(auth_header) = header_map.get("Authorization") {
@@ -91,13 +99,14 @@ pub async fn post_test_login(
if auth_header_str.starts_with("Bearer ") { if auth_header_str.starts_with("Bearer ") {
let token = auth_header_str.trim_start_matches("Bearer ").to_string(); let token = auth_header_str.trim_start_matches("Bearer ").to_string();
// @todo change secret // @todo change secret
match decode::<Claims>( if decode::<Claims>(
&token, &token,
&DecodingKey::from_secret("secret".as_ref()), &DecodingKey::from_secret("secret".as_ref()),
&Validation::default(), &Validation::default(),
) { )
Ok(_) => return Ok(Json("Logged in".to_owned())), .is_ok()
Err(_) => {} {
return Ok(Json("Logged in".to_owned()));
} }
} }
} }

View File

@@ -1,23 +1,15 @@
use crate::entity::prelude::*;
use crate::models::generic::GenericResponse;
use argon2::password_hash::rand_core::OsRng;
use argon2::password_hash::SaltString;
use argon2::Argon2;
use argon2::PasswordHash;
use argon2::PasswordHasher;
use axum::{extract::State, http::StatusCode, Json};
use chrono::Utc;
use sea_orm::ColumnTrait;
use sea_orm::EntityTrait;
use sea_orm::InsertResult;
use sea_orm::QueryFilter;
use sea_orm::Set;
use crate::{ use crate::{
entity::user::{self, Entity}, entity::{prelude::*, user},
models::auth::RegisterRequest, models::{auth::RegisterRequest, generic::GenericResponse},
server::server_state::ServerState, server::server_state::ServerState,
}; };
use argon2::{
password_hash::{rand_core::OsRng, SaltString},
Argon2, PasswordHash, PasswordHasher,
};
use axum::{extract::State, http::StatusCode, Json};
use chrono::Utc;
use sea_orm::{ColumnTrait, EntityTrait, QueryFilter, Set};
pub async fn post_register_user( pub async fn post_register_user(
State(state): State<ServerState>, State(state): State<ServerState>,
@@ -59,7 +51,7 @@ pub async fn post_register_user(
username: Set(username), username: Set(username),
password_hash_and_salt: Set(phc_string), password_hash_and_salt: Set(phc_string),
nickname: Set({ nickname: Set({
if register_info.nickname == "" { if register_info.nickname.is_empty() {
None None
} else { } else {
Some(register_info.nickname) Some(register_info.nickname)
@@ -69,7 +61,7 @@ pub async fn post_register_user(
last_active_time: Set(Utc::now().naive_utc()), last_active_time: Set(Utc::now().naive_utc()),
is_admin: Set(false), is_admin: Set(false),
email: Set({ email: Set({
if register_info.email == "" { if register_info.email.is_empty() {
None None
} else { } else {
Some(register_info.email) Some(register_info.email)
@@ -79,11 +71,16 @@ pub async fn post_register_user(
forgot_password_request: Set(None), forgot_password_request: Set(None),
..Default::default() ..Default::default()
}; };
// TODO -> error handling let db_resp = user::Entity::insert(new_user).exec(&state.db_conn).await;
let db_resp = user::Entity::insert(new_user) match db_resp {
.exec(&state.db_conn) Ok(_) => {}
.await Err(_) => {
.unwrap(); return (
StatusCode::INTERNAL_SERVER_ERROR,
return (StatusCode::OK, Json(GenericResponse::ok())); Json(GenericResponse::err("Database error")),
);
}
};
(StatusCode::OK, Json(GenericResponse::ok()))
} }

View File

@@ -1,3 +1,4 @@
pub mod auth; pub mod auth;
pub mod pool;
pub mod routes; pub mod routes;
pub mod server_state; pub mod server_state;

View File

@@ -0,0 +1,25 @@
use crate::{
// entity::{prelude::*, user},
models::{game_result::GameResult, generic::GenericResponse},
server::server_state::ServerState,
};
use axum::{
extract::{Json, State},
http::StatusCode,
};
pub async fn post_game_result(
State(state): State<ServerState>,
Json(game_result): Json<GameResult>,
) -> (StatusCode, Result<(), Json<GenericResponse>>) {
(
StatusCode::BAD_REQUEST,
Err(Json(GenericResponse {
status: "Oopsie we had a fucky wucky".to_owned(),
})),
)
// if (game_result.loser == "ferris"){
// throw 406 "Not Acceptable; Ferris cannot lose"
// }
}

1
src/server/pool/mod.rs Normal file
View File

@@ -0,0 +1 @@
pub mod add_match;

View File

@@ -1,8 +1,6 @@
// (Server only) Routes // (Server only) Routes
use crate::endpoints::{FORGOT_PASSWORD, LOGIN, LOGIN_TEST, REGISTER}; use crate::endpoints::{ADD_MATCH, FORGOT_PASSWORD, LOGIN, LOGIN_TEST, REGISTER};
use axum::routing::{post, Router}; use axum::routing::{post, Router};
use futures::executor::block_on;
use sea_orm::Database;
use super::{ use super::{
auth::{ auth::{
@@ -10,6 +8,7 @@ use super::{
login::{post_login_user, post_test_login}, login::{post_login_user, post_test_login},
register::post_register_user, register::post_register_user,
}, },
pool::add_match::post_game_result,
server_state::ServerState, server_state::ServerState,
}; };
@@ -17,6 +16,7 @@ pub fn get_api_router(state: ServerState) -> Router {
Router::new() Router::new()
.route(REGISTER, post(post_register_user)) .route(REGISTER, post(post_register_user))
.route(LOGIN, post(post_login_user)) .route(LOGIN, post(post_login_user))
.route(ADD_MATCH, post(post_game_result))
.route(LOGIN_TEST, post(post_test_login)) .route(LOGIN_TEST, post(post_test_login))
.route(FORGOT_PASSWORD, post(post_forgot_password)) .route(FORGOT_PASSWORD, post(post_forgot_password))
.with_state(state) .with_state(state)

View File

@@ -1,3 +1,5 @@
use std::fmt::Display;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Clone)] #[derive(Serialize, Deserialize, Clone)]
@@ -8,13 +10,28 @@ pub enum LoginState {
} }
#[derive(Serialize, Deserialize, Clone)] #[derive(Serialize, Deserialize, Clone)]
pub enum GameState { pub enum ContentState {
None, None,
Pool, Pool,
Pickleball, Pickleball,
TableTennis, TableTennis,
} }
impl Display for ContentState {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}",
match self {
ContentState::None => "",
ContentState::Pool => "Pool",
ContentState::Pickleball => "Pickle Ball",
ContentState::TableTennis => "Table Tennis",
}
)
}
}
#[derive(Serialize, Deserialize, Clone)] #[derive(Serialize, Deserialize, Clone)]
pub enum OpenState { pub enum OpenState {
Open, Open,

View File

@@ -1,107 +0,0 @@
use crate::{components::layout::Layout, state_enums::GameState};
use perseus::prelude::*;
use serde::{Deserialize, Serialize};
use sycamore::prelude::*;
use web_sys::Event;
cfg_if::cfg_if! {
if #[cfg(client)] {
use crate::global_state::AppStateRx;
use crate::templates::get_api_path;
use chrono::Utc;
}
}
// Reactive page
#[derive(Serialize, Deserialize, Clone, ReactiveState)]
#[rx(alias = "PageStateRx")]
struct PageState {
winner: String,
new_user: String,
}
fn add_game_form_page<'a, G: Html>(cx: BoundedScope<'_, 'a>, state: &'a PageStateRx) -> View<G> {
let handle_add_match = move |_event: Event| {
#[cfg(client)]
{
// state.winner.get().as_ref().clone()
spawn_local_scoped(cx, async move {})
}
};
let handle_add_user = move |_event: Event| {
#[cfg(client)]
{
// state.winner.get().as_ref().clone()
spawn_local_scoped(cx, async move {})
}
};
view! { cx,
Layout(title = "Add Game Results", game = GameState::Pool) {
div (class = "flex flex-wrap") {
select {
option (value="red")
option (value="blue")
}
}
div (class = "flex flex-wrap") {
input (bind:value = state.winner,
class = "appearance-none block w-full bg-gray-200 text-gray-700 border \
border-red-500 rounded py-3 px-4 mb-3 leading-tight focus:outline-none \
focus:bg-white",)
}
div (class = "flex flex-wrap") {
button(on:click = handle_add_match,
class = "flex-shrink-0 bg-teal-500 hover:bg-teal-700 border-teal-500 \
hover:border-teal-700 text-sm border-4 text-white py-1 px-2 rounded",
) {
"Add result"
}
}
div (class = "flex flex-wrap") {
input (bind:value = state.new_user,
class = "appearance-none block w-full bg-gray-200 text-gray-700 border \
border-red-500 rounded py-3 px-4 mb-3 leading-tight focus:outline-none \
focus:bg-white",)
}
div (class = "flex flex-wrap") {
button(on:click = handle_add_user,
class = "flex-shrink-0 bg-teal-500 hover:bg-teal-700 border-teal-500 \
hover:border-teal-700 text-sm border-4 text-white py-1 px-2 rounded",
) {
"Add new user"
}
}
}
}
}
#[engine_only_fn]
async fn get_request_state(
_info: StateGeneratorInfo<()>,
_req: Request,
) -> Result<PageState, BlamedError<std::convert::Infallible>> {
Ok(PageState {
winner: "Ferris".to_owned(),
new_user: "newguy".to_owned(),
})
}
#[engine_only_fn]
fn head(cx: Scope) -> View<SsrNode> {
view! { cx,
title { "Add Game Form" }
}
}
// Template
pub fn get_template<G: Html>() -> Template<G> {
Template::build("add-game-form")
.request_state_fn(get_request_state)
.view_with_state(add_game_form_page)
.head(head)
.build()
}

View File

@@ -1,10 +1,10 @@
use crate::{components::layout::Layout, state_enums::GameState}; use crate::{components::layout::Layout, state_enums::ContentState};
use perseus::prelude::*; use perseus::prelude::*;
use sycamore::prelude::*; use sycamore::prelude::*;
fn index_page<G: Html>(cx: Scope) -> View<G> { fn index_page<G: Html>(cx: Scope) -> View<G> {
view! { cx, view! { cx,
Layout(title = "Index", game = GameState::Pool) { Layout(content_state = ContentState::None) {
// Anything we put in here will be rendered inside the `<main>` block of the layout // Anything we put in here will be rendered inside the `<main>` block of the layout
p { "Hello World!" } p { "Hello World!" }
br {} br {}

View File

@@ -1,11 +1,13 @@
pub mod add_game_form;
pub mod index; pub mod index;
pub mod one_v_one_board; pub mod pickleball;
pub mod overall_board; pub mod pool;
pub mod table_tennis;
pub mod user;
#[cfg(client)] #[cfg(client)]
use perseus::utils::get_path_prefix_client; use perseus::utils::get_path_prefix_client;
#[cfg(client)]
pub fn get_api_path(path: &str) -> String { pub fn get_api_path(path: &str) -> String {
#[cfg(engine)] #[cfg(engine)]
{ {

View File

@@ -0,0 +1,27 @@
use crate::{components::layout::Layout, state_enums::ContentState};
use perseus::prelude::*;
use sycamore::prelude::*;
fn index_page<G: Html>(cx: Scope) -> View<G> {
view! { cx,
Layout(content_state = ContentState::Pickleball) {
// Anything we put in here will be rendered inside the `<main>` block of the layout
p { "Hello World!" }
br {}
}
}
}
#[engine_only_fn]
fn head(cx: Scope) -> View<SsrNode> {
view! { cx,
title { "Index Page" }
}
}
pub fn get_template<G: Html>() -> Template<G> {
Template::build("pickleball")
.view(index_page)
.head(head)
.build()
}

View File

@@ -0,0 +1 @@
pub mod index;

View File

@@ -0,0 +1,110 @@
use crate::{
components::{layout::Layout, sub_components::error_block::ErrorBlock},
state_enums::ContentState,
};
use perseus::prelude::*;
use serde::{Deserialize, Serialize};
use sycamore::prelude::*;
use web_sys::Event;
cfg_if::cfg_if! {
if #[cfg(client)] {
use crate::{
endpoints::ADD_MATCH,
models::{game_result::GameResult, generic::GenericResponse},
templates::get_api_path,
};
use crate::entity::sea_orm_active_enums::GameType;
use reqwest::StatusCode;
}
}
// Reactive page
#[derive(Serialize, Deserialize, Clone, ReactiveState)]
#[rx(alias = "PageStateRx")]
struct PageState {
winner: String,
loser: String,
error: String,
}
fn add_game_form_page<'a, G: Html>(cx: BoundedScope<'_, 'a>, state: &'a PageStateRx) -> View<G> {
let handle_add_match = move |_event: Event| {
#[cfg(client)]
{
let var_name = async move {
let game_result = GameResult {
winner: (*state.winner.get()).clone(),
loser: (*state.loser.get()).clone(),
game_type: GameType::Pool,
};
let client = reqwest::Client::new();
let response = client
.post(get_api_path(ADD_MATCH).as_str())
.json(&game_result)
.send()
.await
.unwrap();
if response.status() != StatusCode::OK {
let response = response.json::<GenericResponse>().await.unwrap();
state.error.set(response.status.to_string());
return;
}
// let response = response.json::<())>().await.unwrap();
};
let var_name = var_name;
spawn_local_scoped(cx, var_name)
}
};
view! { cx,
Layout(content_state = ContentState::Pool) {
ErrorBlock(error = state.error.clone())
div (class = "label") { span (class = "label-text") { "Winner" } }
input (bind:value = state.winner, class = "input input-bordered w-full m-2")
div (class = "label") { span (class = "label-text") { "Loser" } }
input (bind:value = state.loser, class = "input input-bordered w-full m-2")
div (class = "flex justify-center") {
button (on:click = handle_add_match, class="btn"){"Record Match"}
}
}
}
}
#[engine_only_fn]
async fn get_request_state(
_info: StateGeneratorInfo<()>,
_req: Request,
) -> Result<PageState, BlamedError<std::convert::Infallible>> {
Ok(PageState {
winner: String::new(),
loser: String::new(),
error: String::new(),
})
}
#[engine_only_fn]
fn head(cx: Scope) -> View<SsrNode> {
view! { cx,
title { "Add Game Form" }
}
}
// Template
pub fn get_template<G: Html>() -> Template<G> {
Template::build("pool/add-game-form")
.request_state_fn(get_request_state)
.view_with_state(add_game_form_page)
.head(head)
.build()
}

View File

@@ -0,0 +1,24 @@
use crate::{components::layout::Layout, state_enums::ContentState};
use perseus::prelude::*;
use sycamore::prelude::*;
fn index_page<G: Html>(cx: Scope) -> View<G> {
view! { cx,
Layout(content_state = ContentState::Pool) {
// Anything we put in here will be rendered inside the `<main>` block of the layout
p { "Hello World!" }
br {}
}
}
}
#[engine_only_fn]
fn head(cx: Scope) -> View<SsrNode> {
view! { cx,
title { "Index Page" }
}
}
pub fn get_template<G: Html>() -> Template<G> {
Template::build("pool").view(index_page).head(head).build()
}

View File

@@ -0,0 +1,4 @@
pub mod add_game_form;
pub mod index;
pub mod one_v_one_board;
pub mod overall_board;

View File

@@ -1,4 +1,4 @@
use crate::{components::layout::Layout, state_enums::GameState}; use crate::{components::layout::Layout, state_enums::ContentState};
use perseus::prelude::*; use perseus::prelude::*;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use sycamore::prelude::*; use sycamore::prelude::*;
@@ -9,7 +9,7 @@ struct PageState {}
fn one_v_one_board_page<'a, G: Html>(cx: BoundedScope<'_, 'a>, _state: &'a PageStateRx) -> View<G> { fn one_v_one_board_page<'a, G: Html>(cx: BoundedScope<'_, 'a>, _state: &'a PageStateRx) -> View<G> {
view! { cx, view! { cx,
Layout(title = "1v1 Leaderboard", game = GameState::Pool) { Layout(content_state = ContentState::Pool) {
p { "leaderboard" } p { "leaderboard" }
} }
} }
@@ -31,7 +31,7 @@ fn head(cx: Scope) -> View<SsrNode> {
} }
pub fn get_template<G: Html>() -> Template<G> { pub fn get_template<G: Html>() -> Template<G> {
Template::build("one-v-one-board") Template::build("pool/one-v-one-board")
.request_state_fn(get_request_state) .request_state_fn(get_request_state)
.view_with_state(one_v_one_board_page) .view_with_state(one_v_one_board_page)
.head(head) .head(head)

View File

@@ -1,4 +1,4 @@
use crate::{components::layout::Layout, global_state::AppStateRx, state_enums::GameState}; use crate::{components::layout::Layout, global_state::AppStateRx, state_enums::ContentState};
use perseus::prelude::*; use perseus::prelude::*;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
@@ -12,7 +12,7 @@ fn overall_board_page<'a, G: Html>(cx: BoundedScope<'_, 'a>, _state: &'a PageSta
let _global_state = Reactor::<G>::from_cx(cx).get_global_state::<AppStateRx>(cx); let _global_state = Reactor::<G>::from_cx(cx).get_global_state::<AppStateRx>(cx);
view! { cx, view! { cx,
Layout(title = "Overall Leaderboard", game = GameState::Pool) { Layout(content_state = ContentState::Pool) {
ul { ul {
(View::new_fragment( (View::new_fragment(
vec![], vec![],
@@ -38,7 +38,7 @@ fn head(cx: Scope) -> View<SsrNode> {
} }
pub fn get_template<G: Html>() -> Template<G> { pub fn get_template<G: Html>() -> Template<G> {
Template::build("overall-board") Template::build("pool/overall-board")
.request_state_fn(get_request_state) .request_state_fn(get_request_state)
.view_with_state(overall_board_page) .view_with_state(overall_board_page)
.head(head) .head(head)

View File

@@ -0,0 +1,27 @@
use crate::{components::layout::Layout, state_enums::ContentState};
use perseus::prelude::*;
use sycamore::prelude::*;
fn index_page<G: Html>(cx: Scope) -> View<G> {
view! { cx,
Layout(content_state = ContentState::TableTennis) {
// Anything we put in here will be rendered inside the `<main>` block of the layout
p { "Hello World!" }
br {}
}
}
}
#[engine_only_fn]
fn head(cx: Scope) -> View<SsrNode> {
view! { cx,
title { "Index Page" }
}
}
pub fn get_template<G: Html>() -> Template<G> {
Template::build("table_tennis")
.view(index_page)
.head(head)
.build()
}

View File

@@ -0,0 +1 @@
pub mod index;

View File

@@ -0,0 +1 @@

View File

@@ -1,3 +1,5 @@
const { default: daisyui } = require("daisyui");
module.exports = { module.exports = {
purge: { purge: {
mode: "all", mode: "all",
@@ -10,5 +12,8 @@ module.exports = {
}, },
theme: {}, theme: {},
variants: {}, variants: {},
plugins: [], plugins: [require("daisyui")],
daisyui: {
themes: ["light", "dark", "lemonade", "autumn", "nord"],
},
}; };