add router

This commit is contained in:
Romulus21
2024-09-02 23:20:37 +02:00
parent abcbc16d24
commit 9bc48ff63d
10 changed files with 190 additions and 159 deletions

View File

@@ -1,157 +1,47 @@
use cfg_if::cfg_if;
use leptos::*;
use crate::values::FormValues;
use crate::todo::TodoApp;
use leptos::prelude::*;
use leptos_meta::*;
use leptos_router::*;
use serde::{Deserialize, Serialize};
pub struct Option {
value: &'static str,
name: &'static str,
topic: &'static str,
}
pub const OPTIONS: &[Option] = &[
Option {
value: "citerne",
name: "Citerne",
topic: "home/citerne/height",
},
Option {
value: "eau",
name: "Eau",
topic: "home/eau/volume",
},
Option {
value: "elec-hight",
name: "Electricité heure pleine",
topic: "home/elec-hight/pleine",
},
Option {
value: "elec-low",
name: "Electricité heure creuse",
topic: "home/elec-low/creuse",
},
];
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Value {
id: u16,
service: String,
capteur: String,
type_donnee: String,
donnee: String,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ssr", derive(sqlx::FromRow))]
struct HeftyData {
capteur: String,
value: String,
}
#[cfg(feature = "ssr")]
pub mod ssr {
// use http::{header::SET_COOKIE, HeaderMap, HeaderValue, StatusCode};
use leptos::server_fn::ServerFnError;
use sqlx::{Connection, SqliteConnection};
pub async fn db() -> Result<SqliteConnection, ServerFnError> {
Ok(SqliteConnection::connect("sqlite:Todos.db").await?)
}
}
use leptos_router::{
components::{FlatRoutes, Route, Router},
ParamSegment, SsrMode, StaticSegment,
};
#[component]
pub fn App() -> impl IntoView {
// Provides context that manages stylesheets, titles, meta tags, etc.
provide_meta_context();
let fallback = || view! { "Page not found." }.into_view();
view! {
<Stylesheet id="leptos" href="/pkg/tailwind.css"/>
<Link rel="shortcut icon" type_="image/ico" href="/favicon.ico"/>
<Router>
<nav class="px-2 py-1 flex gap-3">
<nav class="flex gap-5 px-2 py-1 ">
<a href="/">Home</a>
<a href="/formulaire">Formulaire</a>
<a href="/todos">Todos</a>
</nav>
<main class="dark:bg-slate-900 text-gray-50 h-screen">
<Routes>
<Route path="" view= move || view! { <Home/> }/>
<Route path="/formulaire" view= move || view! { <Form/> }/>
</Routes>
<main>
<FlatRoutes fallback>
<Route path=StaticSegment("/") view=Home ssr=SsrMode::Async/>
<Route path=StaticSegment("/formulaire") view=FormValues ssr=SsrMode::Async />
<Route path=StaticSegment("/todos") view=TodoApp ssr=SsrMode::Async />
<Route path=StaticSegment("/*any") view=NotFound ssr=SsrMode::Async/>
</FlatRoutes>
</main>
</Router>
}
}
#[component]
fn Home() -> impl IntoView {
let (count, set_count) = create_signal(0);
pub fn Home() -> impl IntoView {
view! {
<div class="my-0 mx-auto max-w-3xl text-center">
<h2 class="p-6 text-4xl">"Welcome to Leptos with Tailwind"</h2>
<p class="px-10 pb-10 text-left">"Tailwind will scan your Rust files for Tailwind class names and compile them into a CSS file."</p>
<button
class="bg-amber-600 hover:bg-sky-700 px-5 py-3 text-white rounded-lg"
on:click=move |_| set_count.update(|count| *count += 1)
>
"Something's here | "
{move || if count() == 0 {
"Click me!".to_string()
} else {
count().to_string()
}}
" | Some more text"
</button>
</div>
<h1>Home</h1>
}
}
#[component]
fn Form() -> impl IntoView {
let add_value = create_server_action::<AddValue>();
let value = add_value.value();
let has_error = move || value.with(|val| matches!(val, Some(Err(_))));
pub fn NotFound() -> impl IntoView {
view! {
<div class="my-0 mx-auto max-w-3xl text-center">
<h2 class="p-6 text-4xl">"Form"</h2>
<ActionForm action=add_value>
<div>
<label class="block">Capteur</label>
<select name="hefty_arg[capteur]">
{OPTIONS.into_iter()
.map(|option| view! { <option value={option.value}>{option.name}</option>})
.collect::<Vec<_>>()}
</select>
</div>
<div>
<label class="block">Valeur</label>
<input type="text" name="hefty_arg[value]" />
</div>
<div>
<button type="submit">Valider</button>
</div>
</ActionForm>
</div>
}
}
#[server(AddValue, "/api/add-value")]
pub async fn add_value(hefty_arg: HeftyData) -> Result<(), ServerFnError> {
use self::ssr::*;
let mut conn = db().await?;
dbg!(&hefty_arg);
match sqlx::query("INSERT INTO donnees (service, donnee) VALUES ($1, $2)")
.bind(hefty_arg.capteur)
.bind(hefty_arg.value)
.execute(&mut conn)
.await
{
Ok(_) => Ok(()),
Err(e) => Err(ServerFnError::ServerError(e.to_string())),
<h1>Not Found</h1>
}
}