working proto
This commit is contained in:
1
.gitignore
vendored
1
.gitignore
vendored
@@ -1,3 +1,4 @@
|
|||||||
Todos.db
|
Todos.db
|
||||||
target/
|
target/
|
||||||
style/output.css
|
style/output.css
|
||||||
|
.env
|
||||||
|
|||||||
2442
Cargo.lock
generated
2442
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
77
Cargo.toml
77
Cargo.toml
@@ -7,44 +7,71 @@ edition = "2021"
|
|||||||
crate-type = ["cdylib", "rlib"]
|
crate-type = ["cdylib", "rlib"]
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-files = { version = "0.6.6", optional = true }
|
axum = { version = "0.7", optional = true }
|
||||||
actix-web = { version = "4.8", optional = true, features = ["macros"] }
|
jsonwebtoken = { version = "9", optional = true }
|
||||||
anyhow = "1.0"
|
tokio = { version = "1.39", features = ["rt-multi-thread"], optional = true }
|
||||||
broadcaster = "1.0"
|
tower = { version = "0.4", optional = true }
|
||||||
console_log = "1.0"
|
tower-http = { version = "0.5", features = ["fs", "trace"], optional = true }
|
||||||
console_error_panic_hook = "0.1.7"
|
sqlx = { version = "0.8", features = [
|
||||||
serde = { version = "1.0", features = ["derive"] }
|
|
||||||
futures = "0.3.30"
|
|
||||||
leptos = { git = "https://github.com/leptos-rs/leptos" }
|
|
||||||
leptos_router = { git = "https://github.com/leptos-rs/leptos" }
|
|
||||||
leptos_meta = { git = "https://github.com/leptos-rs/leptos" }
|
|
||||||
leptos_actix = { git = "https://github.com/leptos-rs/leptos", optional = true }
|
|
||||||
log = "0.4.22"
|
|
||||||
simple_logger = "5.0"
|
|
||||||
gloo = { git = "https://github.com/rustwasm/gloo" }
|
|
||||||
sqlx = { version = "0.8.0", features = [
|
|
||||||
"runtime-tokio-rustls",
|
"runtime-tokio-rustls",
|
||||||
"sqlite",
|
"sqlite",
|
||||||
|
"mysql",
|
||||||
|
"chrono",
|
||||||
], optional = true }
|
], optional = true }
|
||||||
|
mail-send = { version = "0.4.7", optional = true }
|
||||||
|
regex = { version = "1.10", optional = true }
|
||||||
|
|
||||||
|
serde = { version = "1.0", features = ["derive"] }
|
||||||
|
|
||||||
|
console_error_panic_hook = { version = "0.1", optional = true }
|
||||||
|
|
||||||
|
leptos = { version = "0.6.15" }
|
||||||
|
leptos_meta = { version = "0.6.15" }
|
||||||
|
leptos_axum = { version = "0.6.11", optional = true }
|
||||||
|
leptos_router = { version = "0.6.15" }
|
||||||
|
|
||||||
|
tracing = { version = "0.1" }
|
||||||
|
tracing-subscriber = { version = "0.3", features = ["fmt"] }
|
||||||
|
tracing-wasm = { version = "0.2", optional = true }
|
||||||
|
|
||||||
wasm-bindgen = "0.2.93"
|
wasm-bindgen = "0.2.93"
|
||||||
tokio = { version = "1.39", features = ["rt", "time"], optional = true }
|
|
||||||
server_fn = { version = "0.6", features = ["cbor"] }
|
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
hydrate = ["leptos/hydrate"]
|
default = ["ssr", "hydrate"]
|
||||||
|
hydrate = [
|
||||||
|
"leptos/hydrate",
|
||||||
|
"leptos_meta/hydrate",
|
||||||
|
"leptos_router/hydrate",
|
||||||
|
"dep:tracing-wasm",
|
||||||
|
"dep:console_error_panic_hook",
|
||||||
|
]
|
||||||
ssr = [
|
ssr = [
|
||||||
"dep:actix-files",
|
|
||||||
"dep:actix-web",
|
|
||||||
"dep:sqlx",
|
|
||||||
"leptos/ssr",
|
"leptos/ssr",
|
||||||
"leptos_actix",
|
|
||||||
"leptos_meta/ssr",
|
"leptos_meta/ssr",
|
||||||
"leptos_router/ssr",
|
"leptos_router/ssr",
|
||||||
|
"dep:leptos_axum",
|
||||||
|
"dep:axum",
|
||||||
|
"dep:jsonwebtoken",
|
||||||
"dep:tokio",
|
"dep:tokio",
|
||||||
|
"dep:tower",
|
||||||
|
"dep:tower-http",
|
||||||
|
"dep:sqlx",
|
||||||
|
"dep:regex",
|
||||||
|
"dep:mail-send",
|
||||||
]
|
]
|
||||||
|
|
||||||
[package.metadata.cargo-all-features]
|
[package.metadata.cargo-all-features]
|
||||||
denylist = ["actix-files", "actix-web", "leptos_actix", "sqlx"]
|
denylist = [
|
||||||
|
"axum",
|
||||||
|
"tower",
|
||||||
|
"tower-http",
|
||||||
|
"tokio",
|
||||||
|
"sqlx",
|
||||||
|
"leptos_axum",
|
||||||
|
"jsonwebtoken",
|
||||||
|
"regex",
|
||||||
|
"mail-send",
|
||||||
|
]
|
||||||
skip_feature_sets = [["csr", "ssr"], ["csr", "hydrate"], ["ssr", "hydrate"]]
|
skip_feature_sets = [["csr", "ssr"], ["csr", "hydrate"], ["ssr", "hydrate"]]
|
||||||
|
|
||||||
[package.metadata.leptos]
|
[package.metadata.leptos]
|
||||||
@@ -60,7 +87,7 @@ style-file = "style/output.css"
|
|||||||
# [Optional] Files in the asset-dir will be copied to the site-root directory
|
# [Optional] Files in the asset-dir will be copied to the site-root directory
|
||||||
assets-dir = "public"
|
assets-dir = "public"
|
||||||
# The IP and port (ex: 127.0.0.1:3000) where the server serves the content. Use it in your server setup.
|
# The IP and port (ex: 127.0.0.1:3000) where the server serves the content. Use it in your server setup.
|
||||||
site-addr = "127.0.0.1:3000"
|
site-addr = "127.0.0.1:3002"
|
||||||
# The port to use for automatic reload monitoring
|
# The port to use for automatic reload monitoring
|
||||||
reload-port = 3001
|
reload-port = 3001
|
||||||
# [Optional] Command to use when running end2end tests. It will run in the end2end dir.
|
# [Optional] Command to use when running end2end tests. It will run in the end2end dir.
|
||||||
|
|||||||
@@ -1,4 +0,0 @@
|
|||||||
extend = [
|
|
||||||
{ path = "../cargo-make/main.toml" },
|
|
||||||
{ path = "../cargo-make/cargo-leptos-test.toml" },
|
|
||||||
]
|
|
||||||
@@ -3,16 +3,20 @@ source : https://github.com/Oishh/leptos-axum-tailwind-start
|
|||||||
wasm-pack build --target=web --debug --no-default-features --features=hydrate
|
wasm-pack build --target=web --debug --no-default-features --features=hydrate
|
||||||
cargo run --no-default-features --features=ssr
|
cargo run --no-default-features --features=ssr
|
||||||
|
|
||||||
npx tailwindcss -i ./input.css -o ./pkg/output.css --watch
|
npx tailwindcss -i ./input.css -o ./style/output.css --watch
|
||||||
|
|
||||||
## features
|
## features
|
||||||
[x] ssr
|
[x] ssr
|
||||||
[ ] MySQL
|
[x] MySQL
|
||||||
[x] tailwindcss
|
[x] tailwindcss
|
||||||
[x] router
|
[x] router
|
||||||
|
[ ] value gestion des erreurs
|
||||||
[ ] deploy
|
[ ] deploy
|
||||||
|
|
||||||
## pages
|
## pages
|
||||||
[ ] liens
|
[ ] liens
|
||||||
[ ] formulaire
|
[ ] formulaire
|
||||||
[ ] recap capteurs
|
[ ] recap capteurs
|
||||||
|
|
||||||
|
|
||||||
|
// https://github.com/Bechma/realworld-leptos
|
||||||
|
|||||||
9
migrations/20221207194615_init.up.sql
Normal file
9
migrations/20221207194615_init.up.sql
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
CREATE TABLE IF NOT EXISTS data (
|
||||||
|
id int(11) NOT NULL AUTO_INCREMENT,
|
||||||
|
service varchar(12) NOT NULL,
|
||||||
|
device varchar(12) NOT NULL,
|
||||||
|
type varchar(12) NOT NULL,
|
||||||
|
data varchar(12) NOT NULL,
|
||||||
|
date_data datetime NOT NULL,
|
||||||
|
PRIMARY KEY (id)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
CREATE TABLE IF NOT EXISTS todos
|
|
||||||
(
|
|
||||||
id INTEGER NOT NULL PRIMARY KEY,
|
|
||||||
title VARCHAR,
|
|
||||||
completed BOOLEAN
|
|
||||||
);
|
|
||||||
48
src/app.rs
48
src/app.rs
@@ -1,34 +1,34 @@
|
|||||||
use crate::values::FormValues;
|
use leptos::*;
|
||||||
use crate::todo::TodoApp;
|
|
||||||
use leptos::prelude::*;
|
|
||||||
use leptos_meta::*;
|
use leptos_meta::*;
|
||||||
use leptos_router::{
|
use leptos_router::*;
|
||||||
components::{FlatRoutes, Route, Router},
|
|
||||||
ParamSegment, SsrMode, StaticSegment,
|
use crate::routes::*;
|
||||||
};
|
|
||||||
|
|
||||||
#[component]
|
#[component]
|
||||||
pub fn App() -> impl IntoView {
|
pub fn App() -> impl IntoView {
|
||||||
// Provides context that manages stylesheets, titles, meta tags, etc.
|
|
||||||
provide_meta_context();
|
provide_meta_context();
|
||||||
let fallback = || view! { "Page not found." }.into_view();
|
|
||||||
|
|
||||||
view! {
|
view! {
|
||||||
<Router>
|
<Stylesheet href="/pkg/rust_leptos.css"/>
|
||||||
<nav class="flex gap-5 px-2 py-1 ">
|
|
||||||
<a href="/">Home</a>
|
<Title text="Welcome to Leptos"/>
|
||||||
<a href="/formulaire">Formulaire</a>
|
|
||||||
<a href="/todos">Todos</a>
|
<div class="dark:bg-slate-950 dark:text-white h-screen flex flex-col">
|
||||||
</nav>
|
<Router>
|
||||||
<main>
|
<nav class="flex gap-5 px-2 py-1 ">
|
||||||
<FlatRoutes fallback>
|
<a href="/">Home</a>
|
||||||
<Route path=StaticSegment("/") view=Home ssr=SsrMode::Async/>
|
<a href="/formulaire">Formulaire</a>
|
||||||
<Route path=StaticSegment("/formulaire") view=FormValues ssr=SsrMode::Async />
|
</nav>
|
||||||
<Route path=StaticSegment("/todos") view=TodoApp ssr=SsrMode::Async />
|
<main class="flex-1">
|
||||||
<Route path=StaticSegment("/*any") view=NotFound ssr=SsrMode::Async/>
|
<Routes>
|
||||||
</FlatRoutes>
|
<Route path="/" view=move || view! { <Home/> }/>
|
||||||
</main>
|
<Route path="/formulaire" view=move || view! { <FormValues/> }/>
|
||||||
</Router>
|
//<Route path="/*any" view=move || view! { <NotFound/> }/>
|
||||||
|
</Routes>
|
||||||
|
</main>
|
||||||
|
<footer>Footer</footer>
|
||||||
|
</Router>
|
||||||
|
</div>
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
26
src/database.rs
Normal file
26
src/database.rs
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
static DB: std::sync::OnceLock<sqlx::MySqlPool> = std::sync::OnceLock::new();
|
||||||
|
|
||||||
|
async fn create_pool() -> sqlx::MySqlPool {
|
||||||
|
let database_url = std::env::var("DATABASE_URL").expect("no database url specify");
|
||||||
|
dbg!(&database_url);
|
||||||
|
let pool = sqlx::mysql::MySqlPoolOptions::new()
|
||||||
|
.max_connections(4)
|
||||||
|
.connect(database_url.as_str())
|
||||||
|
.await
|
||||||
|
.expect("could not connect to database_url");
|
||||||
|
|
||||||
|
sqlx::migrate!()
|
||||||
|
.run(&pool)
|
||||||
|
.await
|
||||||
|
.expect("migrations failed");
|
||||||
|
|
||||||
|
pool
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn init_db() -> Result<(), sqlx::Pool<sqlx::MySql>> {
|
||||||
|
DB.set(create_pool().await)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_db<'a>() -> &'a sqlx::MySqlPool {
|
||||||
|
DB.get().expect("database unitialized")
|
||||||
|
}
|
||||||
16
src/lib.rs
16
src/lib.rs
@@ -1,18 +1,18 @@
|
|||||||
pub mod app;
|
pub mod app;
|
||||||
pub mod todo;
|
#[cfg(feature = "ssr")]
|
||||||
pub mod values;
|
pub(crate) mod database;
|
||||||
|
pub(crate) mod models;
|
||||||
|
pub(crate) mod routes;
|
||||||
|
#[cfg(feature = "ssr")]
|
||||||
|
pub mod setup;
|
||||||
|
|
||||||
#[cfg(feature = "hydrate")]
|
#[cfg(feature = "hydrate")]
|
||||||
#[wasm_bindgen::prelude::wasm_bindgen]
|
#[wasm_bindgen::prelude::wasm_bindgen]
|
||||||
pub fn hydrate() {
|
pub fn hydrate() {
|
||||||
use app::App;
|
use app::App;
|
||||||
use todo::TodoApp;
|
use leptos::*;
|
||||||
|
|
||||||
use crate::app::*;
|
|
||||||
use crate::todo::*;
|
|
||||||
use crate::values::*;
|
|
||||||
console_error_panic_hook::set_once();
|
console_error_panic_hook::set_once();
|
||||||
_ = console_log::init_with_level(log::Level::Debug);
|
|
||||||
|
|
||||||
leptos::mount::hydrate_body(App);
|
mount_to_body(move || view! { <App/> });
|
||||||
}
|
}
|
||||||
|
|||||||
79
src/main.rs
79
src/main.rs
@@ -1,75 +1,12 @@
|
|||||||
mod todo;
|
|
||||||
mod values;
|
|
||||||
|
|
||||||
#[cfg(feature = "ssr")]
|
#[cfg(feature = "ssr")]
|
||||||
mod ssr {
|
#[tokio::main]
|
||||||
pub use actix_files::Files;
|
async fn main() {
|
||||||
pub use actix_web::*;
|
rust_leptos::setup::init_app(None).await;
|
||||||
pub use leptos::prelude::*;
|
|
||||||
pub use leptos_actix::{generate_route_list, LeptosRoutes};
|
|
||||||
pub use rust_leptos::app::*;
|
|
||||||
|
|
||||||
#[get("/style.css")]
|
|
||||||
pub async fn css() -> impl Responder {
|
|
||||||
actix_files::NamedFile::open_async("./style/output.css").await
|
|
||||||
}
|
|
||||||
|
|
||||||
#[get("/favicon.ico")]
|
|
||||||
pub async fn favicon() -> impl Responder {
|
|
||||||
actix_files::NamedFile::open_async("./target/site/favicon.ico").await
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "ssr")]
|
#[cfg(not(feature = "ssr"))]
|
||||||
#[actix_web::main]
|
pub fn main() {
|
||||||
async fn main() -> std::io::Result<()> {
|
// no client-side main function
|
||||||
use self::{ssr::*, values::ssr::*};
|
// unless we want this to work with e.g., Trunk for pure client-side testing
|
||||||
|
// see lib.rs for hydration function instead
|
||||||
use leptos_meta::*;
|
|
||||||
|
|
||||||
let mut conn = db().await.expect("couldn't connect to DB");
|
|
||||||
sqlx::migrate!()
|
|
||||||
.run(&mut conn)
|
|
||||||
.await
|
|
||||||
.expect("could not run SQLx migrations");
|
|
||||||
|
|
||||||
let conf = get_configuration(None).unwrap();
|
|
||||||
let addr = conf.leptos_options.site_addr;
|
|
||||||
println!("listening on http://{}", &addr);
|
|
||||||
|
|
||||||
HttpServer::new(move || {
|
|
||||||
// Generate the list of routes in your Leptos App
|
|
||||||
let routes = generate_route_list(App);
|
|
||||||
let leptos_options = &conf.leptos_options;
|
|
||||||
let site_root = &leptos_options.site_root;
|
|
||||||
|
|
||||||
App::new()
|
|
||||||
.service(css)
|
|
||||||
.leptos_routes(routes, {
|
|
||||||
let leptos_options = leptos_options.clone();
|
|
||||||
move || {
|
|
||||||
use leptos::prelude::*;
|
|
||||||
view! {
|
|
||||||
<!DOCTYPE html>
|
|
||||||
<html lang="en">
|
|
||||||
<head>
|
|
||||||
<meta charset="utf-8"/>
|
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1"/>
|
|
||||||
<Stylesheet href="/pkg/rust_leptos.css"/>
|
|
||||||
<AutoReload options=leptos_options.clone() />
|
|
||||||
<HydrationScripts options=leptos_options.clone()/>
|
|
||||||
<MetaTags/>
|
|
||||||
</head>
|
|
||||||
<body class="dark:bg-slate-900 dark:text-gray-50">
|
|
||||||
<App/>
|
|
||||||
</body>
|
|
||||||
</html>
|
|
||||||
}
|
|
||||||
}})
|
|
||||||
.service(Files::new("/", site_root))
|
|
||||||
.wrap(middleware::Compress::default())
|
|
||||||
})
|
|
||||||
.bind(&addr)?
|
|
||||||
.run()
|
|
||||||
.await
|
|
||||||
}
|
}
|
||||||
|
|||||||
3
src/models/mod.rs
Normal file
3
src/models/mod.rs
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
mod value;
|
||||||
|
pub use value::Value;
|
||||||
|
pub use value::OPTIONS;
|
||||||
81
src/models/value.rs
Normal file
81
src/models/value.rs
Normal file
@@ -0,0 +1,81 @@
|
|||||||
|
use chrono::prelude::*;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct Option {
|
||||||
|
pub value: &'static str,
|
||||||
|
pub name: &'static str,
|
||||||
|
service: &'static str,
|
||||||
|
device: &'static str,
|
||||||
|
r_type: &'static str,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub const OPTIONS: &[Option] = &[
|
||||||
|
Option {
|
||||||
|
value: "citerne",
|
||||||
|
name: "Citerne",
|
||||||
|
service: "home",
|
||||||
|
device: "citerne",
|
||||||
|
r_type: "height",
|
||||||
|
},
|
||||||
|
Option {
|
||||||
|
value: "eau",
|
||||||
|
name: "Eau",
|
||||||
|
service: "home",
|
||||||
|
device: "eau",
|
||||||
|
r_type: "volume",
|
||||||
|
},
|
||||||
|
Option {
|
||||||
|
value: "elec-hight",
|
||||||
|
name: "Electricité heure pleine",
|
||||||
|
service: "home",
|
||||||
|
device: "elec",
|
||||||
|
r_type: "pleine",
|
||||||
|
},
|
||||||
|
Option {
|
||||||
|
value: "elec-low",
|
||||||
|
name: "Electricité heure creuse",
|
||||||
|
service: "home",
|
||||||
|
device: "elec",
|
||||||
|
r_type: "creuse",
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct Value {
|
||||||
|
id: u16,
|
||||||
|
service: String,
|
||||||
|
capteur: String,
|
||||||
|
type_donnee: String,
|
||||||
|
donnee: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Value {
|
||||||
|
#[cfg(feature = "ssr")]
|
||||||
|
pub async fn insert(
|
||||||
|
device: String,
|
||||||
|
value: String,
|
||||||
|
) -> Result<sqlx::mysql::MySqlQueryResult, sqlx::Error> {
|
||||||
|
let option = match find_option(&device) {
|
||||||
|
Ok(option) => option,
|
||||||
|
Err(err) => panic!("{}", err),
|
||||||
|
};
|
||||||
|
|
||||||
|
sqlx::query!(
|
||||||
|
"INSERT INTO data(service, device, type, data, date_data) VALUES (?, ?, ?, ?, NOW())",
|
||||||
|
option.service,
|
||||||
|
option.device,
|
||||||
|
option.r_type,
|
||||||
|
value,
|
||||||
|
)
|
||||||
|
.execute(crate::database::get_db())
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn find_option(value: &str) -> Result<&Option, &str> {
|
||||||
|
OPTIONS
|
||||||
|
.iter()
|
||||||
|
.find(|&option| option.value == value)
|
||||||
|
.ok_or("No option found with the given value")
|
||||||
|
}
|
||||||
3
src/routes/mod.rs
Normal file
3
src/routes/mod.rs
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
pub use value::*;
|
||||||
|
|
||||||
|
mod value;
|
||||||
51
src/routes/value.rs
Normal file
51
src/routes/value.rs
Normal file
@@ -0,0 +1,51 @@
|
|||||||
|
use leptos::*;
|
||||||
|
use leptos_meta::*;
|
||||||
|
use leptos_router::*;
|
||||||
|
|
||||||
|
use crate::models::OPTIONS;
|
||||||
|
|
||||||
|
#[server(ValueAction, "/api")]
|
||||||
|
pub async fn add_value(device: String, value: String) -> Result<(), ServerFnError> {
|
||||||
|
crate::models::Value::insert(device, value)
|
||||||
|
.await
|
||||||
|
.map(|_| ())
|
||||||
|
.map_err(|x| {
|
||||||
|
let err = format!("Error while posting a comment: {x:?}");
|
||||||
|
tracing::error!("{err}");
|
||||||
|
ServerFnError::ServerError("Could not post a comment, try again later".into())
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[component]
|
||||||
|
pub fn FormValues() -> impl IntoView {
|
||||||
|
let value_action = create_server_action::<ValueAction>();
|
||||||
|
let result = value_action.version();
|
||||||
|
let reset_value = create_rw_signal("");
|
||||||
|
//let add_value = ServerAction::<AddValue>::new();
|
||||||
|
//let value = add_value.value();
|
||||||
|
//let has_error = move || value.with(|val| matches!(val, Some(Err(_))));
|
||||||
|
|
||||||
|
view! {
|
||||||
|
<div class="my-0 mx-auto max-w-3xl text-center">
|
||||||
|
<h2 class="p-6 text-4xl">"Formulaire"</h2>
|
||||||
|
|
||||||
|
<ActionForm action=value_action attr:class="border">
|
||||||
|
<div>
|
||||||
|
<label class="block">Capteur</label>
|
||||||
|
<select name="device" class="dark:bg-slate-800 px-2 py-1">
|
||||||
|
{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="value" prop:value=move || reset_value.get() class="text-center dark:bg-slate-800 dark:text-white px-2 py-1" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<button type="submit" class="bg-slate-600 px-2 py-1 w-48 mt-3">Valider</button>
|
||||||
|
</div>
|
||||||
|
</ActionForm>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
}
|
||||||
49
src/setup.rs
Normal file
49
src/setup.rs
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
use leptos::*;
|
||||||
|
use leptos_axum::{generate_route_list, LeptosRoutes};
|
||||||
|
|
||||||
|
use crate::app::App;
|
||||||
|
|
||||||
|
/// # Panics
|
||||||
|
///
|
||||||
|
/// Will panic if anything is badly setup from database, or web server
|
||||||
|
pub async fn init_app(configuration_path: Option<&str>) {
|
||||||
|
tracing_subscriber::fmt()
|
||||||
|
.with_level(true)
|
||||||
|
.with_max_level(tracing::Level::INFO)
|
||||||
|
.init();
|
||||||
|
// Init the pool into static
|
||||||
|
crate::database::init_db()
|
||||||
|
.await
|
||||||
|
.expect("problem during initialization of the database");
|
||||||
|
|
||||||
|
// Get leptos configuration
|
||||||
|
let conf = get_configuration(configuration_path).await.unwrap();
|
||||||
|
let addr = conf.leptos_options.site_addr;
|
||||||
|
// Generate the list of routes in your Leptos App
|
||||||
|
let routes = generate_route_list(|| view! { <App/> });
|
||||||
|
let leptos_options = conf.leptos_options;
|
||||||
|
let serve_dir = tower_http::services::ServeDir::new(&leptos_options.site_root)
|
||||||
|
.append_index_html_on_directories(false);
|
||||||
|
|
||||||
|
let app = axum::Router::new()
|
||||||
|
.leptos_routes(&leptos_options, routes, || view! { <App/> })
|
||||||
|
.fallback_service(serve_dir)
|
||||||
|
.layer(
|
||||||
|
tower_http::trace::TraceLayer::new_for_http()
|
||||||
|
.make_span_with(
|
||||||
|
tower_http::trace::DefaultMakeSpan::new().level(tracing::Level::INFO),
|
||||||
|
)
|
||||||
|
.on_request(tower_http::trace::DefaultOnRequest::new().level(tracing::Level::INFO))
|
||||||
|
.on_response(
|
||||||
|
tower_http::trace::DefaultOnResponse::new().level(tracing::Level::INFO),
|
||||||
|
)
|
||||||
|
.on_failure(
|
||||||
|
tower_http::trace::DefaultOnFailure::new().level(tracing::Level::ERROR),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
//.layer(axum::middleware::from_fn(crate::auth::auth_middleware))
|
||||||
|
.with_state(leptos_options);
|
||||||
|
|
||||||
|
let listener = tokio::net::TcpListener::bind(addr).await.unwrap();
|
||||||
|
axum::serve(listener, app).await.unwrap();
|
||||||
|
}
|
||||||
172
src/todo.rs
172
src/todo.rs
@@ -1,172 +0,0 @@
|
|||||||
use leptos::either::Either;
|
|
||||||
use leptos::prelude::*;
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
//use server_fn::ServerFnError;
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
|
||||||
#[cfg_attr(feature = "ssr", derive(sqlx::FromRow))]
|
|
||||||
pub struct Todo {
|
|
||||||
id: u16,
|
|
||||||
title: String,
|
|
||||||
completed: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[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?)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[server]
|
|
||||||
pub async fn get_todos() -> Result<Vec<Todo>, ServerFnError> {
|
|
||||||
use self::ssr::*;
|
|
||||||
|
|
||||||
// this is just an example of how to access server context injected in the handlers
|
|
||||||
let req_parts = use_context::<leptos_actix::Request>();
|
|
||||||
|
|
||||||
if let Some(req_parts) = req_parts {
|
|
||||||
println!("Path = {:?}", req_parts.path());
|
|
||||||
}
|
|
||||||
|
|
||||||
use futures::TryStreamExt;
|
|
||||||
|
|
||||||
let mut conn = db().await?;
|
|
||||||
|
|
||||||
let mut todos = Vec::new();
|
|
||||||
let mut rows = sqlx::query_as::<_, Todo>("SELECT * FROM todos").fetch(&mut conn);
|
|
||||||
while let Some(row) = rows.try_next().await? {
|
|
||||||
todos.push(row);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Lines below show how to set status code and headers on the response
|
|
||||||
// let resp = expect_context::<ResponseOptions>();
|
|
||||||
// resp.set_status(StatusCode::IM_A_TEAPOT);
|
|
||||||
// resp.insert_header(SET_COOKIE, HeaderValue::from_str("fizz=buzz").unwrap());
|
|
||||||
|
|
||||||
Ok(todos)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[server]
|
|
||||||
pub async fn add_todo(title: String) -> Result<(), ServerFnError> {
|
|
||||||
use self::ssr::*;
|
|
||||||
let mut conn = db().await?;
|
|
||||||
|
|
||||||
// fake API delay
|
|
||||||
std::thread::sleep(std::time::Duration::from_millis(250));
|
|
||||||
|
|
||||||
match sqlx::query("INSERT INTO todos (title, completed) VALUES ($1, false)")
|
|
||||||
.bind(title)
|
|
||||||
.execute(&mut conn)
|
|
||||||
.await
|
|
||||||
{
|
|
||||||
Ok(_row) => Ok(()),
|
|
||||||
Err(e) => Err(ServerFnError::ServerError(e.to_string())),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[server]
|
|
||||||
pub async fn delete_todo(id: u16) -> Result<(), ServerFnError> {
|
|
||||||
use self::ssr::*;
|
|
||||||
let mut conn = db().await?;
|
|
||||||
|
|
||||||
Ok(sqlx::query("DELETE FROM todos WHERE id = $1")
|
|
||||||
.bind(id)
|
|
||||||
.execute(&mut conn)
|
|
||||||
.await
|
|
||||||
.map(|_| ())?)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[component]
|
|
||||||
pub fn TodoApp() -> impl IntoView {
|
|
||||||
view! {
|
|
||||||
<header>
|
|
||||||
<h1>"My Tasks"</h1>
|
|
||||||
</header>
|
|
||||||
<main>
|
|
||||||
<Todos/>
|
|
||||||
</main>
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[component]
|
|
||||||
pub fn Todos() -> impl IntoView {
|
|
||||||
let add_todo = ServerMultiAction::<AddTodo>::new();
|
|
||||||
let submissions = add_todo.submissions();
|
|
||||||
let delete_todo = ServerAction::<DeleteTodo>::new();
|
|
||||||
|
|
||||||
// list of todos is loaded from the server in reaction to changes
|
|
||||||
let todos = Resource::new(
|
|
||||||
move || {
|
|
||||||
(
|
|
||||||
delete_todo.version().get(),
|
|
||||||
add_todo.version().get(),
|
|
||||||
delete_todo.version().get(),
|
|
||||||
)
|
|
||||||
},
|
|
||||||
move |_| get_todos(),
|
|
||||||
);
|
|
||||||
|
|
||||||
let existing_todos = move || {
|
|
||||||
Suspend::new(async move {
|
|
||||||
todos.await.map(|todos| {
|
|
||||||
if todos.is_empty() {
|
|
||||||
Either::Left(view! { <p>"No tasks were found."</p> })
|
|
||||||
} else {
|
|
||||||
Either::Right(
|
|
||||||
todos
|
|
||||||
.iter()
|
|
||||||
.map(move |todo| {
|
|
||||||
let id = todo.id;
|
|
||||||
view! {
|
|
||||||
<li>
|
|
||||||
{todo.title.clone()} <ActionForm action=delete_todo>
|
|
||||||
<input type="hidden" name="id" value=id/>
|
|
||||||
<input type="submit" value="X"/>
|
|
||||||
</ActionForm>
|
|
||||||
</li>
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.collect::<Vec<_>>(),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
})
|
|
||||||
};
|
|
||||||
|
|
||||||
view! {
|
|
||||||
<MultiActionForm action=add_todo>
|
|
||||||
<label>"Add a Todo" <input type="text" name="title"/></label>
|
|
||||||
<input type="submit" value="Add"/>
|
|
||||||
</MultiActionForm>
|
|
||||||
<div>
|
|
||||||
<Transition fallback=move || view! { <p>"Loading..."</p> }>
|
|
||||||
// TODO: ErrorBoundary here seems to break Suspense in Actix
|
|
||||||
// <ErrorBoundary fallback=|errors| view! { <p>"Error: " {move || format!("{:?}", errors.get())}</p> }>
|
|
||||||
<ul>
|
|
||||||
{existing_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::<Vec<_>>()
|
|
||||||
}}
|
|
||||||
|
|
||||||
</ul>
|
|
||||||
// </ErrorBoundary>
|
|
||||||
</Transition>
|
|
||||||
</div>
|
|
||||||
}
|
|
||||||
}
|
|
||||||
118
src/values.rs
118
src/values.rs
@@ -1,118 +0,0 @@
|
|||||||
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?)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[component]
|
|
||||||
fn Form() -> impl IntoView {
|
|
||||||
view! {
|
|
||||||
<div class="my-0 mx-auto max-w-3xl text-center">
|
|
||||||
<h2 class="p-6 text-4xl">"Formulaire"</h2>
|
|
||||||
</div>
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[component]
|
|
||||||
pub fn FormValues() -> impl IntoView {
|
|
||||||
let add_value = ServerAction::<AddValue>::new();
|
|
||||||
let value = add_value.value();
|
|
||||||
let has_error = move || value.with(|val| matches!(val, Some(Err(_))));
|
|
||||||
|
|
||||||
view! {
|
|
||||||
<div class="my-0 mx-auto max-w-3xl text-center">
|
|
||||||
<h2 class="p-6 text-4xl">"Formulaire"</h2>
|
|
||||||
|
|
||||||
<ActionForm action=add_value attr:class="border">
|
|
||||||
<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())),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -558,6 +558,10 @@ video {
|
|||||||
margin-bottom: 0px;
|
margin-bottom: 0px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.mt-3 {
|
||||||
|
margin-top: 0.75rem;
|
||||||
|
}
|
||||||
|
|
||||||
.block {
|
.block {
|
||||||
display: block;
|
display: block;
|
||||||
}
|
}
|
||||||
@@ -570,60 +574,49 @@ video {
|
|||||||
height: 100vh;
|
height: 100vh;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.w-48 {
|
||||||
|
width: 12rem;
|
||||||
|
}
|
||||||
|
|
||||||
.max-w-3xl {
|
.max-w-3xl {
|
||||||
max-width: 48rem;
|
max-width: 48rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
.gap-3 {
|
.flex-1 {
|
||||||
gap: 0.75rem;
|
flex: 1 1 0%;
|
||||||
}
|
}
|
||||||
|
|
||||||
.rounded-lg {
|
.flex-col {
|
||||||
border-radius: 0.5rem;
|
flex-direction: column;
|
||||||
}
|
}
|
||||||
|
|
||||||
.bg-amber-600 {
|
.gap-5 {
|
||||||
|
gap: 1.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.border {
|
||||||
|
border-width: 1px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.bg-slate-600 {
|
||||||
--tw-bg-opacity: 1;
|
--tw-bg-opacity: 1;
|
||||||
background-color: rgb(217 119 6 / var(--tw-bg-opacity));
|
background-color: rgb(71 85 105 / var(--tw-bg-opacity));
|
||||||
}
|
}
|
||||||
|
|
||||||
.p-6 {
|
.p-6 {
|
||||||
padding: 1.5rem;
|
padding: 1.5rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
.px-10 {
|
|
||||||
padding-left: 2.5rem;
|
|
||||||
padding-right: 2.5rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.px-2 {
|
.px-2 {
|
||||||
padding-left: 0.5rem;
|
padding-left: 0.5rem;
|
||||||
padding-right: 0.5rem;
|
padding-right: 0.5rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
.px-5 {
|
|
||||||
padding-left: 1.25rem;
|
|
||||||
padding-right: 1.25rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.py-1 {
|
.py-1 {
|
||||||
padding-top: 0.25rem;
|
padding-top: 0.25rem;
|
||||||
padding-bottom: 0.25rem;
|
padding-bottom: 0.25rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
.py-3 {
|
|
||||||
padding-top: 0.75rem;
|
|
||||||
padding-bottom: 0.75rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.pb-10 {
|
|
||||||
padding-bottom: 2.5rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.text-left {
|
|
||||||
text-align: left;
|
|
||||||
}
|
|
||||||
|
|
||||||
.text-center {
|
.text-center {
|
||||||
text-align: center;
|
text-align: center;
|
||||||
}
|
}
|
||||||
@@ -633,29 +626,29 @@ video {
|
|||||||
line-height: 2.5rem;
|
line-height: 2.5rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
.text-gray-50 {
|
.\*\:text-black > * {
|
||||||
--tw-text-opacity: 1;
|
--tw-text-opacity: 1;
|
||||||
color: rgb(249 250 251 / var(--tw-text-opacity));
|
color: rgb(0 0 0 / var(--tw-text-opacity));
|
||||||
}
|
|
||||||
|
|
||||||
.text-white {
|
|
||||||
--tw-text-opacity: 1;
|
|
||||||
color: rgb(255 255 255 / var(--tw-text-opacity));
|
|
||||||
}
|
|
||||||
|
|
||||||
.hover\:bg-sky-700:hover {
|
|
||||||
--tw-bg-opacity: 1;
|
|
||||||
background-color: rgb(3 105 161 / var(--tw-bg-opacity));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@media (prefers-color-scheme: dark) {
|
@media (prefers-color-scheme: dark) {
|
||||||
.dark\:bg-slate-900 {
|
.dark\:bg-slate-800 {
|
||||||
--tw-bg-opacity: 1;
|
--tw-bg-opacity: 1;
|
||||||
background-color: rgb(15 23 42 / var(--tw-bg-opacity));
|
background-color: rgb(30 41 59 / var(--tw-bg-opacity));
|
||||||
}
|
}
|
||||||
|
|
||||||
.dark\:bg-slate-950 {
|
.dark\:bg-slate-950 {
|
||||||
--tw-bg-opacity: 1;
|
--tw-bg-opacity: 1;
|
||||||
background-color: rgb(2 6 23 / var(--tw-bg-opacity));
|
background-color: rgb(2 6 23 / var(--tw-bg-opacity));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.dark\:text-white {
|
||||||
|
--tw-text-opacity: 1;
|
||||||
|
color: rgb(255 255 255 / var(--tw-text-opacity));
|
||||||
|
}
|
||||||
|
|
||||||
|
.dark\:text-black {
|
||||||
|
--tw-text-opacity: 1;
|
||||||
|
color: rgb(0 0 0 / var(--tw-text-opacity));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user