Réécriture de lara-bermite en Rust (Axum, Leptos, Tailwind)

Application de suivi de la pluviométrie et de la météo, portée depuis
Laravel + React vers Leptos 0.8 (SSR + hydratation) sur Axum, avec
Tailwind CSS v4 et SQLite.

- Pages : accueil (chiffres clés, comparaison mois par mois avec l'an
  dernier), pluviométrie (graphique par jour/semaine/mois/année),
  liste des mesures (édition en place), météo OpenWeatherMap,
  profil (emplacement, thème clair/sombre), authentification et
  réinitialisation du mot de passe par e-mail.
- Sessions tower-sessions en SQLite ; mots de passe Argon2, les hash
  bcrypt de Laravel restent valides et sont convertis à la connexion.
- Import unique des données MySQL de lara-bermite (bin import_mysql).
- PWA : manifest et service worker « réseau d'abord ».
- Makefile de cross-compilation aarch64 et service systemd pour le Pi.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Romulus21andClaude Opus 5.5 committed 2026-10-14 23:24:03 +02:00
1 parent 4a005dd25e
commit 6ecbefbcf6
52 files changed
+9870 -2

No files matched your search

+11
View File
@@ -0,0 +1,11 @@
DATABASE_URL=sqlite:bermite.db
# URL publique, utilisée dans le lien de réinitialisation du mot de passe.
APP_URL=http://127.0.0.1:3004
OPEN_WEATHER_MAP_API_KEY=
# Sans SMTP_HOST, le lien de réinitialisation est seulement écrit dans les logs.
SMTP_HOST=
SMTP_PORT=465
SMTP_USERNAME=
SMTP_PASSWORD=
MAIL_FROM="Bermite <bermite@example.com>"
REGISTRATION_ENABLED=false
+5
View File
@@ -1 +1,6 @@
/target /target
/dist
.env
*.db
*.db-shm
*.db-wal
Generated
+4122
View File
File diff suppressed because it is too large. Load diff
+95
View File
@@ -3,4 +3,99 @@ name = "bermite_rs"
version = "0.1.0" version = "0.1.0"
edition = "2024" edition = "2024"
[lib]
crate-type = ["cdylib", "rlib"]
[[bin]]
name = "bermite_rs"
path = "src/main.rs"
# Import unique des données de lara-bermite (MySQL) vers SQLite.
[[bin]]
name = "import_mysql"
path = "src/bin/import_mysql.rs"
required-features = ["ssr", "import"]
[dependencies] [dependencies]
leptos = "0.8"
leptos_meta = "0.8"
leptos_router = "0.8"
serde = { version = "1", features = ["derive"] }
chrono = { version = "0.4", default-features = false, features = ["clock", "serde", "std", "wasmbind"] }
# Client (WASM)
console_error_panic_hook = { version = "0.1", optional = true }
wasm-bindgen = { version = "=0.2.128", optional = true }
# Serveur uniquement
axum = { version = "0.8", optional = true }
leptos_axum = { version = "0.8", optional = true }
tokio = { version = "1", features = ["rt-multi-thread", "macros", "sync", "time"], optional = true }
sqlx = { version = "0.8", default-features = false, features = ["runtime-tokio", "sqlite", "migrate", "macros"], optional = true }
tower-sessions = { version = "0.14", optional = true }
tower-sessions-sqlx-store = { version = "0.15", features = ["sqlite"], optional = true }
argon2 = { version = "0.5", optional = true }
bcrypt = { version = "0.17", optional = true }
sha2 = { version = "0.10", optional = true }
hex = { version = "0.4", optional = true }
dotenvy = { version = "0.15", optional = true }
reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"], optional = true }
lettre = { version = "0.11", default-features = false, features = ["builder", "hostname", "smtp-transport", "tokio1", "tokio1-rustls-tls"], optional = true }
serde_json = { version = "1", optional = true }
[dev-dependencies]
tokio = { version = "1", features = ["rt-multi-thread", "macros"] }
[features]
hydrate = [
"leptos/hydrate",
"dep:console_error_panic_hook",
"dep:wasm-bindgen",
]
ssr = [
"dep:axum",
"dep:tokio",
"dep:leptos_axum",
"dep:sqlx",
"dep:tower-sessions",
"dep:tower-sessions-sqlx-store",
"dep:argon2",
"dep:bcrypt",
"dep:sha2",
"dep:hex",
"dep:dotenvy",
"dep:reqwest",
"dep:lettre",
"dep:serde_json",
"leptos/ssr",
"leptos_meta/ssr",
"leptos_router/ssr",
]
import = ["sqlx/mysql"]
# Profil optimisé en taille pour le bundle WASM en release
[profile.wasm-release]
inherits = "release"
opt-level = 'z'
lto = true
codegen-units = 1
panic = "abort"
[package.metadata.leptos]
output-name = "bermite_rs"
bin-target = "bermite_rs"
site-root = "target/site"
site-pkg-dir = "pkg"
tailwind-input-file = "style/tailwind.css"
# Fichiers copiés tels quels à la racine du site (icônes, manifest, service worker…)
assets-dir = "public"
site-addr = "127.0.0.1:3004"
reload-port = 3005
browserquery = "defaults"
# Passer à "PROD" en production : active notamment le cookie de session `Secure`
env = "DEV"
bin-features = ["ssr"]
bin-default-features = false
lib-features = ["hydrate"]
lib-default-features = false
lib-profile-release = "wasm-release"
+86
View File
@@ -0,0 +1,86 @@
# Build de bermite_rs pour Raspberry Pi (aarch64, Raspberry Pi OS 64 bits).
#
# Le front (wasm) ne dépend pas de l'architecture : il est construit par
# cargo-leptos. Le serveur est cross-compilé avec cargo-zigbuild, car sqlx
# compile SQLite en C et a donc besoin d'un compilateur C pour aarch64.
#
# make setup installe la cible Rust et cargo-zigbuild (zig à installer à part)
# make dev lance le serveur de développement (rechargement automatique)
# make test lance les tests
# make pi produit dist/ prêt à copier sur le Pi
# make deploy copie dist/ vers $(PI_HOST):$(PI_DIR) et redémarre le service
# make import MYSQL_URL=mysql://user:pass@127.0.0.1/lara-bermite
# importe les données de lara-bermite dans bermite.db (une seule fois)
APP := bermite_rs
SERVICE := bermite
TARGET := aarch64-unknown-linux-gnu
# Version de glibc visée : 2.28 couvre Buster, Bullseye et Bookworm.
GLIBC := 2.28
DIST := dist
SITE_ADDR := 127.0.0.1:3004
PI_HOST ?= raspiweb
PI_DIR ?= /home/pi/Scripts/$(SERVICE)
BIN := target/$(TARGET)/release/$(APP)
.PHONY: all dev test pi setup front server dist deploy import clean
all: pi
dev:
cargo leptos watch
test:
cargo test --features ssr
setup:
rustup target add $(TARGET) wasm32-unknown-unknown
cargo install --locked cargo-zigbuild
@command -v zig >/dev/null || echo "⚠ zig introuvable : installez-le (ex. 'sudo snap install zig --classic --beta' ou https://ziglang.org/download/)"
pi: dist
front:
cargo leptos build --release --frontend-only
server:
LEPTOS_OUTPUT_NAME=$(APP) cargo zigbuild --release \
--target $(TARGET).$(GLIBC) \
--bin $(APP) --no-default-features --features ssr
dist: front server
rm -rf $(DIST)
mkdir -p $(DIST)
cp $(BIN) $(DIST)/
cp -r target/site $(DIST)/site
cp deploy/$(SERVICE).service $(DIST)/
printf '%s\n' \
'LEPTOS_ENV=PROD' \
'LEPTOS_SITE_ROOT=site' \
'LEPTOS_SITE_PKG_DIR=pkg' \
'LEPTOS_SITE_ADDR=$(SITE_ADDR)' \
'DATABASE_URL=sqlite:bermite.db' \
'APP_URL=https://bermite.rodev.fr' \
'OPEN_WEATHER_MAP_API_KEY=' \
'SMTP_HOST=' \
'SMTP_PORT=465' \
'SMTP_USERNAME=' \
'SMTP_PASSWORD=' \
'MAIL_FROM="Bermite <romain@rodev.fr>"' \
'REGISTRATION_ENABLED=false' > $(DIST)/.env.example
@echo "✔ $(DIST)/ prêt — sur le Pi : cp .env.example .env, compléter, puis ./$(APP)"
deploy: dist
ssh $(PI_HOST) 'mkdir -p $(PI_DIR)'
rsync -av --exclude '.env' --exclude '*.db*' $(DIST)/ $(PI_HOST):$(PI_DIR)/
ssh $(PI_HOST) 'sudo systemctl restart $(SERVICE)'
import:
@test -n "$(MYSQL_URL)" || (echo "usage : make import MYSQL_URL=mysql://user:pass@hote/base" && exit 2)
cargo run --release --bin import_mysql --features ssr,import -- "$(MYSQL_URL)" sqlite:bermite.db
clean:
rm -rf $(DIST)
cargo clean --target $(TARGET)
+60
View File
@@ -0,0 +1,60 @@
# Bermite (Rust)
Réécriture de [lara-bermite](../../domotique/lara-bermite) (Laravel + React) en Rust :
**Axum**, **Leptos 0.8** (rendu serveur + hydratation) et **Tailwind CSS v4**, avec SQLite.
Application de suivi de la pluviométrie et de la météo (OpenWeatherMap) :
| URL | Page |
| --- | --- |
| `/` | cumuls mensuels de l'année et de l'an dernier, ajout d'une mesure |
| `/pluviometrie` | graphique par jour / semaine / mois / année, total, 5 dernières mesures |
| `/pluviometrie/mesures` | liste paginée, édition en place, suppression |
| `/meteo` | météo actuelle et prévisions à 5 jours (détail par tranche de 3 h) |
| `/profile` | emplacement des prévisions, thème clair / sombre, déconnexion |
| `/connexion`, `/mot-de-passe-oubliee`, `/changer-le-mot-de-passe/:token` | authentification |
| `/sinscrire` | inscription, seulement si `REGISTRATION_ENABLED=true` |
C'est aussi une PWA installable (manifest + service worker « réseau d'abord » pour
consulter hors ligne les pages déjà vues).
## Développement
```sh
cp .env.example .env # puis renseigner OPEN_WEATHER_MAP_API_KEY
make dev # cargo leptos watch → http://127.0.0.1:3004
make test # cargo test --features ssr
```
Sans `SMTP_HOST`, le lien de réinitialisation du mot de passe est écrit dans les logs.
## Reprise des données de lara-bermite
```sh
make import MYSQL_URL='mysql://utilisateur:motdepasse@127.0.0.1/lara-bermite'
```
Copie `users`, `locations` et `rainfalls` (identifiants conservés) dans `bermite.db`,
et refuse de s'exécuter si la base contient déjà des utilisateurs. Les mots de passe
bcrypt de Laravel restent valides ; ils sont convertis en Argon2 à la connexion suivante.
## Déploiement sur le Raspberry Pi
```sh
make pi # dist/ : binaire aarch64 (cargo-zigbuild) + site/ + service systemd
make deploy # rsync vers raspiweb:/home/pi/Scripts/bermite puis redémarrage
```
Première installation sur le Pi : copier `dist/.env.example` en `.env` et le compléter,
y placer `bermite.db` (issue de `make import`), installer `bermite.service` dans
`/etc/systemd/system/`, puis faire pointer le vhost nginx de bermite.rodev.fr vers
`127.0.0.1:3004`.
## Organisation du code
- `src/main.rs` — serveur Axum : base, sessions (tower-sessions en SQLite, 7 jours), routes Leptos
- `src/server.rs` — configuration, contexte, mots de passe (Argon2 + bcrypt hérité), jetons
- `src/auth.rs`, `src/rainfall.rs`, `src/weather.rs`, `src/location.rs`, `src/profile.rs` — server functions
- `src/rainfall/graph.rs` — regroupement des mesures (fonctions pures, testées)
- `src/app.rs`, `src/pages/`, `src/components.rs`, `src/ui.rs`, `src/chart.rs` — interface
- `src/bin/import_mysql.rs` — import depuis MySQL
+5
View File
@@ -0,0 +1,5 @@
fn main() {
// `sqlx::migrate!()` embarque les migrations à la compilation : sans cette ligne,
// ajouter un nouveau fichier dans `migrations/` ne déclenche pas de recompilation.
println!("cargo:rerun-if-changed=migrations");
}
+25
View File
@@ -0,0 +1,25 @@
[Unit]
Description=Bermite (serveur Leptos)
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
User=pi
Group=pi
# Le binaire lit .env et sert site/ relativement à ce dossier.
WorkingDirectory=/home/pi/Scripts/bermite
ExecStart=/home/pi/Scripts/bermite/bermite_rs
Restart=on-failure
RestartSec=5
# Durcissement : seul le dossier de l'application est accessible en écriture
# (pour la base SQLite).
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=read-only
ReadWritePaths=/home/pi/Scripts/bermite
[Install]
WantedBy=multi-user.target
+42
View File
@@ -0,0 +1,42 @@
-- Schéma initial, repris de lara-bermite (users, locations, rainfalls, password_reset_tokens).
CREATE TABLE users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
email TEXT NOT NULL UNIQUE,
-- Argon2id, ou bcrypt (`$2y$…`) pour les comptes importés de Laravel pas encore reconnectés.
password_hash TEXT NOT NULL,
theme TEXT NOT NULL DEFAULT 'system',
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE locations (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL REFERENCES users (id) ON DELETE CASCADE,
latitude REAL NOT NULL,
longitude REAL NOT NULL,
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX locations_user_id ON locations (user_id);
CREATE TABLE rainfalls (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL REFERENCES users (id) ON DELETE CASCADE,
-- Format AAAA-MM-JJ : l'ordre lexicographique est l'ordre chronologique.
date TEXT NOT NULL,
-- Hauteur d'eau en mm.
value INTEGER NOT NULL CHECK (value BETWEEN 1 AND 1000),
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX rainfalls_user_id_date ON rainfalls (user_id, date);
-- Un seul jeton actif par adresse ; seul son SHA-256 est stocké.
CREATE TABLE password_reset_tokens (
email TEXT PRIMARY KEY,
token_hash TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

+109
View File
@@ -0,0 +1,109 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
version="1.1"
width="100px"
height="100px"
style="shape-rendering:geometricPrecision; text-rendering:geometricPrecision; image-rendering:optimizeQuality; fill-rule:evenodd; clip-rule:evenodd"
id="svg340"
sodipodi:docname="10d@2x.svg"
inkscape:version="1.2.2 (b0a8486541, 2022-12-01)"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg">
<defs
id="defs344" />
<sodipodi:namedview
id="namedview342"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:showpageshadow="2"
inkscape:pageopacity="0.0"
inkscape:pagecheckerboard="0"
inkscape:deskcolor="#d1d1d1"
showgrid="false"
inkscape:zoom="6.9860105"
inkscape:cx="32.49351"
inkscape:cy="52.032559"
inkscape:window-width="1850"
inkscape:window-height="1136"
inkscape:window-x="70"
inkscape:window-y="27"
inkscape:window-maximized="1"
inkscape:current-layer="svg340" />
<g
id="g1598"
transform="matrix(1.6409281,0,0,1.6409281,-33.288122,-29.848421)">
<ellipse
style="fill:#ec6d4b;fill-opacity:0.945098;stroke-width:5.31402;stroke-linecap:square;stroke-linejoin:round;paint-order:fill markers stroke"
id="path517"
cx="62.378757"
cy="37.581673"
rx="15.100805"
ry="14.837029" />
<g
id="g314">
<path
style="opacity:0.956"
fill="#f2f1f1"
d="m 50.5,30.5 c 2.052249,1.654227 1.9412,3.9664 3,6 1.578183,1.489401 6.2139,1.5439 9,3 1.373984,1.322711 1.1816,3.9086 1,6 3.2882,-0.4844 5.9548,0.5156 8,3 1.3734,4.4358 0.04,7.9358 -4,10.5 -8.6603,0.4998 -17.3269,0.6664 -26,0.5 h -4 C 26.1179,60.2958 21.9513,55.2958 25,44.5 c 2.1413,-2.8208 4.9746,-4.1541 8.5,-4 -0.4488,-7.4279 3.0512,-11.4279 10.5,-12 2.4418,-0.0177 4.6085,0.649 6.5,2 z"
id="path312"
sodipodi:nodetypes="cccccccccccc" />
</g>
<g
id="g318">
<path
style="opacity:1;fill:#c3c3c4;fill-opacity:1"
fill="#4a4a4c"
d="m 40.332727,59.754949 c -1.3333,2.6667 -3.02894,2.408643 -2.382156,-0.172998 C 38.498371,57.549651 39.657107,57.688323 41.5,56.5 Z"
id="path316"
sodipodi:nodetypes="cccc" />
</g>
<g
id="g322">
<path
style="opacity:0.648"
fill="#464648"
d="m 53.5,60.5 c -0.275093,4.144916 -1.086323,5.991025 -2.088621,5.231821 C 49.111531,64.215714 51.9624,62.5514 53.5,60.5 Z"
id="path320"
sodipodi:nodetypes="ccc" />
</g>
<g
id="g326">
<path
style="opacity:0.642"
fill="#484749"
d="m 45.394906,62.835155 v 0 C 45.295028,64.774264 44.112,69.461504 42.5,68.5 c -1.276548,-0.758272 1.006762,-3.720805 2.894906,-5.664845 z"
id="path324"
sodipodi:nodetypes="cccc" />
</g>
<g
id="g330">
<path
style="opacity:0.655"
fill="#49484a"
d="m 38.323024,64.01566 c -0.510774,3.779491 -1.468353,4.712106 -2.85558,5.927272 C 34.086944,69.443332 34.4528,69.0004 34.5,67.5 c 0.3457,-1.3492 1.729695,-2.377354 3.823024,-3.48434 z"
id="path328"
sodipodi:nodetypes="cccc" />
</g>
<g
id="g334">
<path
style="opacity:0.629"
fill="#484849"
d="m 50.5,68.5 c -0.332574,3.804597 -0.243075,6.57837 -2,6 -1.287633,-0.914112 0.7702,-4.2028 2,-6 z"
id="path332"
sodipodi:nodetypes="ccc" />
</g>
<g
id="g338">
<path
style="opacity:0.536"
fill="#484849"
d="m 44.5,69.5 c -0.864872,3.818695 -1.946788,4.527584 -3.422663,4.213387 C 39.737799,72.940004 41.5,70.826657 44.5,69.5 Z"
id="path336"
sodipodi:nodetypes="ccc" />
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 3.9 KiB

+45
View File
@@ -0,0 +1,45 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
version="1.1"
width="100px"
height="100px"
style="shape-rendering:geometricPrecision; text-rendering:geometricPrecision; image-rendering:optimizeQuality; fill-rule:evenodd; clip-rule:evenodd"
id="svg340"
sodipodi:docname="01d.svg"
inkscape:version="1.2.2 (b0a8486541, 2022-12-01)"
inkscape:export-filename="01d.png"
inkscape:export-xdpi="96"
inkscape:export-ydpi="96"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg">
<defs
id="defs37" />
<sodipodi:namedview
id="namedview35"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:showpageshadow="2"
inkscape:pageopacity="0.0"
inkscape:pagecheckerboard="0"
inkscape:deskcolor="#d1d1d1"
showgrid="false"
inkscape:zoom="9.7"
inkscape:cx="31.340206"
inkscape:cy="50"
inkscape:window-width="1674"
inkscape:window-height="1173"
inkscape:window-x="2443"
inkscape:window-y="58"
inkscape:window-maximized="0"
inkscape:current-layer="svg340" />
<ellipse
style="fill:#ec6d4b;fill-opacity:1;stroke-width:15.5071;stroke-linecap:square;stroke-linejoin:round;paint-order:fill markers stroke"
cx="50"
cy="50"
rx="44.066483"
ry="43.296745"
id="ellipse2" />
</svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

+55
View File
@@ -0,0 +1,55 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
version="1.1"
width="100px"
height="100px"
style="shape-rendering:geometricPrecision; text-rendering:geometricPrecision; image-rendering:optimizeQuality; fill-rule:evenodd; clip-rule:evenodd"
id="svg340"
sodipodi:docname="02d.svg"
inkscape:version="1.2.2 (b0a8486541, 2022-12-01)"
inkscape:export-filename="02d.png"
inkscape:export-xdpi="96"
inkscape:export-ydpi="96"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg">
<defs
id="defs37" />
<sodipodi:namedview
id="namedview35"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:showpageshadow="2"
inkscape:pageopacity="0.0"
inkscape:pagecheckerboard="0"
inkscape:deskcolor="#d1d1d1"
showgrid="false"
inkscape:zoom="9.7"
inkscape:cx="48.659794"
inkscape:cy="50"
inkscape:window-width="1674"
inkscape:window-height="1173"
inkscape:window-x="2566"
inkscape:window-y="54"
inkscape:window-maximized="0"
inkscape:current-layer="svg340" />
<ellipse
style="fill:#ec6d4b;fill-opacity:1;stroke-width:8.71992;stroke-linecap:square;stroke-linejoin:round;paint-order:fill markers stroke"
cx="69.07093"
cy="44.12281"
rx="24.779335"
ry="24.346498"
id="ellipse2" />
<g
id="g6"
transform="matrix(1.6409281,0,0,1.6409281,-33.288122,-17.546011)"
style="fill:#f2f1f1;fill-opacity:1">
<path
fill="#f2f1f1"
d="m 50.5,30.5 c 2.052249,1.654227 1.9412,3.9664 3,6 1.578183,1.489401 6.2139,1.5439 9,3 1.373984,1.322711 1.1816,3.9086 1,6 3.2882,-0.4844 5.9548,0.5156 8,3 1.3734,4.4358 0.04,7.9358 -4,10.5 -8.6603,0.4998 -17.3269,0.6664 -26,0.5 h -4 C 26.1179,60.2958 21.9513,55.2958 25,44.5 c 2.1413,-2.8208 4.9746,-4.1541 8.5,-4 -0.4488,-7.4279 3.0512,-11.4279 10.5,-12 2.4418,-0.0177 4.6085,0.649 6.5,2 z"
id="path4"
style="fill:#f2f1f1;fill-opacity:1" />
</g>
</svg>

After

Width:  |  Height:  |  Size: 2.1 KiB

+48
View File
@@ -0,0 +1,48 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
version="1.1"
width="100px"
height="100px"
style="shape-rendering:geometricPrecision; text-rendering:geometricPrecision; image-rendering:optimizeQuality; fill-rule:evenodd; clip-rule:evenodd"
id="svg340"
sodipodi:docname="03d.svg"
inkscape:version="1.2.2 (b0a8486541, 2022-12-01)"
inkscape:export-filename="03d.png"
inkscape:export-xdpi="96"
inkscape:export-ydpi="96"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg">
<defs
id="defs37" />
<sodipodi:namedview
id="namedview35"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:showpageshadow="2"
inkscape:pageopacity="0.0"
inkscape:pagecheckerboard="0"
inkscape:deskcolor="#d1d1d1"
showgrid="false"
inkscape:zoom="9.7"
inkscape:cx="47.319588"
inkscape:cy="50"
inkscape:window-width="1674"
inkscape:window-height="1173"
inkscape:window-x="2566"
inkscape:window-y="54"
inkscape:window-maximized="0"
inkscape:current-layer="svg340" />
<g
id="g6"
transform="matrix(1.8275221,0,0,1.8275221,-37.772697,-30.485543)"
style="fill:#f2f1f1;fill-opacity:1">
<path
fill="#f2f1f1"
d="m 50.5,30.5 c 2.052249,1.654227 1.9412,3.9664 3,6 1.578183,1.489401 6.2139,1.5439 9,3 1.373984,1.322711 1.1816,3.9086 1,6 3.2882,-0.4844 5.9548,0.5156 8,3 1.3734,4.4358 0.04,7.9358 -4,10.5 -8.6603,0.4998 -17.3269,0.6664 -26,0.5 h -4 C 26.1179,60.2958 21.9513,55.2958 25,44.5 c 2.1413,-2.8208 4.9746,-4.1541 8.5,-4 -0.4488,-7.4279 3.0512,-11.4279 10.5,-12 2.4418,-0.0177 4.6085,0.649 6.5,2 z"
id="path4"
style="fill:#f2f1f1;fill-opacity:1" />
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.9 KiB

+48
View File
@@ -0,0 +1,48 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
version="1.1"
width="100px"
height="100px"
style="shape-rendering:geometricPrecision; text-rendering:geometricPrecision; image-rendering:optimizeQuality; fill-rule:evenodd; clip-rule:evenodd"
id="svg340"
sodipodi:docname="03d.svg"
inkscape:version="1.2.2 (b0a8486541, 2022-12-01)"
inkscape:export-filename="03d.png"
inkscape:export-xdpi="96"
inkscape:export-ydpi="96"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg">
<defs
id="defs37" />
<sodipodi:namedview
id="namedview35"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:showpageshadow="2"
inkscape:pageopacity="0.0"
inkscape:pagecheckerboard="0"
inkscape:deskcolor="#d1d1d1"
showgrid="false"
inkscape:zoom="9.7"
inkscape:cx="47.319588"
inkscape:cy="50"
inkscape:window-width="1674"
inkscape:window-height="1173"
inkscape:window-x="2566"
inkscape:window-y="54"
inkscape:window-maximized="0"
inkscape:current-layer="svg340" />
<g
id="g6"
transform="matrix(1.8275221,0,0,1.8275221,-37.772697,-30.485543)"
style="fill:#f2f1f1;fill-opacity:1">
<path
fill="#f2f1f1"
d="m 50.5,30.5 c 2.052249,1.654227 1.9412,3.9664 3,6 1.578183,1.489401 6.2139,1.5439 9,3 1.373984,1.322711 1.1816,3.9086 1,6 3.2882,-0.4844 5.9548,0.5156 8,3 1.3734,4.4358 0.04,7.9358 -4,10.5 -8.6603,0.4998 -17.3269,0.6664 -26,0.5 h -4 C 26.1179,60.2958 21.9513,55.2958 25,44.5 c 2.1413,-2.8208 4.9746,-4.1541 8.5,-4 -0.4488,-7.4279 3.0512,-11.4279 10.5,-12 2.4418,-0.0177 4.6085,0.649 6.5,2 z"
id="path4"
style="fill:#f2f1f1;fill-opacity:1" />
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.9 KiB

+62
View File
@@ -0,0 +1,62 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
version="1.1"
width="100px"
height="100px"
style="shape-rendering:geometricPrecision; text-rendering:geometricPrecision; image-rendering:optimizeQuality; fill-rule:evenodd; clip-rule:evenodd"
id="svg340"
sodipodi:docname="04d.svg"
inkscape:version="1.2.2 (b0a8486541, 2022-12-01)"
inkscape:export-filename="04d.png"
inkscape:export-xdpi="96"
inkscape:export-ydpi="96"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg">
<defs
id="defs37" />
<sodipodi:namedview
id="namedview35"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:showpageshadow="2"
inkscape:pageopacity="0.0"
inkscape:pagecheckerboard="0"
inkscape:deskcolor="#d1d1d1"
showgrid="false"
inkscape:zoom="9.7"
inkscape:cx="54.226804"
inkscape:cy="50"
inkscape:window-width="1674"
inkscape:window-height="1173"
inkscape:window-x="2566"
inkscape:window-y="54"
inkscape:window-maximized="0"
inkscape:current-layer="svg340" />
<g
id="g850"
transform="matrix(0.83428781,0,0,0.87762366,1.0190854,10.707957)">
<g
id="g290"
transform="matrix(1.8275221,0,0,1.8275221,-20.352991,-40.943646)"
style="fill:#8c8383;fill-opacity:1">
<path
fill="#f2f1f1"
d="m 50.5,30.5 c 2.052249,1.654227 1.9412,3.9664 3,6 1.578183,1.489401 6.2139,1.5439 9,3 1.373984,1.322711 1.1816,3.9086 1,6 3.2882,-0.4844 5.9548,0.5156 8,3 1.3734,4.4358 0.04,7.9358 -4,10.5 -8.6603,0.4998 -17.3269,0.6664 -26,0.5 h -4 C 26.1179,60.2958 21.9513,55.2958 25,44.5 c 2.1413,-2.8208 4.9746,-4.1541 8.5,-4 -0.4488,-7.4279 3.0512,-11.4279 10.5,-12 2.4418,-0.0177 4.6085,0.649 6.5,2 z"
id="path288"
style="fill:#8c8383;fill-opacity:1" />
</g>
<g
id="g6"
transform="matrix(1.8275221,0,0,1.8275221,-37.772697,-30.485543)"
style="fill:#f2f1f1;fill-opacity:1">
<path
fill="#f2f1f1"
d="m 50.5,30.5 c 2.052249,1.654227 1.9412,3.9664 3,6 1.578183,1.489401 6.2139,1.5439 9,3 1.373984,1.322711 1.1816,3.9086 1,6 3.2882,-0.4844 5.9548,0.5156 8,3 1.3734,4.4358 0.04,7.9358 -4,10.5 -8.6603,0.4998 -17.3269,0.6664 -26,0.5 h -4 C 26.1179,60.2958 21.9513,55.2958 25,44.5 c 2.1413,-2.8208 4.9746,-4.1541 8.5,-4 -0.4488,-7.4279 3.0512,-11.4279 10.5,-12 2.4418,-0.0177 4.6085,0.649 6.5,2 z"
id="path4"
style="fill:#f2f1f1;fill-opacity:1" />
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 2.6 KiB

+116
View File
@@ -0,0 +1,116 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
version="1.1"
width="100px"
height="100px"
style="shape-rendering:geometricPrecision; text-rendering:geometricPrecision; image-rendering:optimizeQuality; fill-rule:evenodd; clip-rule:evenodd"
id="svg340"
sodipodi:docname="09d.svg"
inkscape:version="1.2.2 (b0a8486541, 2022-12-01)"
inkscape:export-filename="09d.png"
inkscape:export-xdpi="96"
inkscape:export-ydpi="96"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg">
<defs
id="defs895" />
<sodipodi:namedview
id="namedview893"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:showpageshadow="2"
inkscape:pageopacity="0.0"
inkscape:pagecheckerboard="0"
inkscape:deskcolor="#d1d1d1"
showgrid="false"
inkscape:zoom="9.7"
inkscape:cx="40.412371"
inkscape:cy="50"
inkscape:window-width="1674"
inkscape:window-height="1173"
inkscape:window-x="2520"
inkscape:window-y="178"
inkscape:window-maximized="0"
inkscape:current-layer="svg340" />
<g
id="g1097"
transform="translate(-1.1004244,-0.35495727)">
<g
id="g850"
transform="matrix(0.83428781,0,0,0.87762366,2.1195098,-1.5930028)"
style="clip-rule:evenodd;fill-rule:evenodd;image-rendering:optimizeQuality;shape-rendering:geometricPrecision;text-rendering:geometricPrecision">
<g
id="g290"
transform="matrix(1.8275221,0,0,1.8275221,-20.352991,-40.943646)"
style="fill:#8c8383;fill-opacity:1">
<path
fill="#f2f1f1"
d="m 50.5,30.5 c 2.052249,1.654227 1.9412,3.9664 3,6 1.578183,1.489401 6.2139,1.5439 9,3 1.373984,1.322711 1.1816,3.9086 1,6 3.2882,-0.4844 5.9548,0.5156 8,3 1.3734,4.4358 0.04,7.9358 -4,10.5 -8.6603,0.4998 -17.3269,0.6664 -26,0.5 h -4 C 26.1179,60.2958 21.9513,55.2958 25,44.5 c 2.1413,-2.8208 4.9746,-4.1541 8.5,-4 -0.4488,-7.4279 3.0512,-11.4279 10.5,-12 2.4418,-0.0177 4.6085,0.649 6.5,2 z"
id="path288"
style="fill:#8c8383;fill-opacity:1" />
</g>
<g
id="g6"
transform="matrix(1.8275221,0,0,1.8275221,-37.772697,-30.485543)"
style="fill:#f2f1f1;fill-opacity:1">
<path
fill="#f2f1f1"
d="m 50.5,30.5 c 2.052249,1.654227 1.9412,3.9664 3,6 1.578183,1.489401 6.2139,1.5439 9,3 1.373984,1.322711 1.1816,3.9086 1,6 3.2882,-0.4844 5.9548,0.5156 8,3 1.3734,4.4358 0.04,7.9358 -4,10.5 -8.6603,0.4998 -17.3269,0.6664 -26,0.5 h -4 C 26.1179,60.2958 21.9513,55.2958 25,44.5 c 2.1413,-2.8208 4.9746,-4.1541 8.5,-4 -0.4488,-7.4279 3.0512,-11.4279 10.5,-12 2.4418,-0.0177 4.6085,0.649 6.5,2 z"
id="path4"
style="fill:#f2f1f1;fill-opacity:1" />
</g>
</g>
<g
id="g868"
transform="matrix(1.6409281,0,0,1.6409281,-33.288122,-29.848421)">
<path
fill="#4a4a4c"
d="m 40.332727,59.754949 c -1.3333,2.6667 -3.02894,2.408643 -2.382156,-0.172998 C 38.498371,57.549651 39.657107,57.688323 41.5,56.5 Z"
id="path866" />
</g>
<g
id="g872"
transform="matrix(1.6409281,0,0,1.6409281,-33.288122,-29.848421)">
<path
fill="#4a4a4c"
d="m 53.5,60.5 c -0.275093,4.144916 -1.086323,5.991025 -2.088621,5.231821 C 49.111531,64.215714 51.9624,62.5514 53.5,60.5 Z"
id="path870" />
</g>
<g
id="g876"
transform="matrix(1.6409281,0,0,1.6409281,-33.288122,-29.848421)">
<path
fill="#4a4a4c"
d="m 45.394906,62.835155 v 0 C 45.295028,64.774264 44.112,69.461504 42.5,68.5 c -1.276548,-0.758272 1.006762,-3.720805 2.894906,-5.664845 z"
id="path874" />
</g>
<g
id="g880"
transform="matrix(1.6409281,0,0,1.6409281,-33.288122,-29.848421)">
<path
fill="#4a4a4c"
d="m 38.323024,64.01566 c -0.510774,3.779491 -1.468353,4.712106 -2.85558,5.927272 C 34.086944,69.443332 34.4528,69.0004 34.5,67.5 c 0.3457,-1.3492 1.729695,-2.377354 3.823024,-3.48434 z"
id="path878" />
</g>
<g
id="g884"
transform="matrix(1.6409281,0,0,1.6409281,-33.288122,-29.848421)">
<path
style="opacity:0.629"
fill="#4a4a4c"
d="m 50.5,68.5 c -0.332574,3.804597 -0.243075,6.57837 -2,6 -1.287633,-0.914112 0.7702,-4.2028 2,-6 z"
id="path882" />
</g>
<g
id="g888"
transform="matrix(1.6409281,0,0,1.6409281,-33.288122,-29.848421)">
<path
fill="#4a4a4c"
d="m 44.5,69.5 c -0.864872,3.818695 -1.946788,4.527584 -3.422663,4.213387 C 39.737799,72.940004 41.5,70.826657 44.5,69.5 Z"
id="path886" />
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 4.8 KiB

+102
View File
@@ -0,0 +1,102 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
version="1.1"
width="100px"
height="100px"
style="shape-rendering:geometricPrecision; text-rendering:geometricPrecision; image-rendering:optimizeQuality; fill-rule:evenodd; clip-rule:evenodd"
id="svg340"
sodipodi:docname="10d.svg"
inkscape:version="1.2.2 (b0a8486541, 2022-12-01)"
inkscape:export-filename="10d.png"
inkscape:export-xdpi="96"
inkscape:export-ydpi="96"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg">
<defs
id="defs37" />
<sodipodi:namedview
id="namedview35"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:showpageshadow="2"
inkscape:pageopacity="0.0"
inkscape:pagecheckerboard="0"
inkscape:deskcolor="#d1d1d1"
showgrid="false"
inkscape:zoom="9.7"
inkscape:cx="23.917526"
inkscape:cy="50"
inkscape:window-width="1674"
inkscape:window-height="1173"
inkscape:window-x="2650"
inkscape:window-y="50"
inkscape:window-maximized="0"
inkscape:current-layer="svg340" />
<ellipse
style="fill:#ec6d4b;fill-opacity:1;stroke-width:8.71992;stroke-linecap:square;stroke-linejoin:round;paint-order:fill markers stroke"
cx="69.07093"
cy="31.820402"
rx="24.779335"
ry="24.346498"
id="ellipse2" />
<g
id="g6"
transform="matrix(1.6409281,0,0,1.6409281,-33.288122,-29.848421)">
<path
fill="#f2f1f1"
d="m 50.5,30.5 c 2.052249,1.654227 1.9412,3.9664 3,6 1.578183,1.489401 6.2139,1.5439 9,3 1.373984,1.322711 1.1816,3.9086 1,6 3.2882,-0.4844 5.9548,0.5156 8,3 1.3734,4.4358 0.04,7.9358 -4,10.5 -8.6603,0.4998 -17.3269,0.6664 -26,0.5 h -4 C 26.1179,60.2958 21.9513,55.2958 25,44.5 c 2.1413,-2.8208 4.9746,-4.1541 8.5,-4 -0.4488,-7.4279 3.0512,-11.4279 10.5,-12 2.4418,-0.0177 4.6085,0.649 6.5,2 z"
id="path4" />
</g>
<g
id="g10"
transform="matrix(1.6409281,0,0,1.6409281,-33.288122,-29.848421)">
<path
fill="#4a4a4c"
d="m 40.332727,59.754949 c -1.3333,2.6667 -3.02894,2.408643 -2.382156,-0.172998 C 38.498371,57.549651 39.657107,57.688323 41.5,56.5 Z"
id="path8" />
</g>
<g
id="g14"
transform="matrix(1.6409281,0,0,1.6409281,-33.288122,-29.848421)">
<path
fill="#4a4a4c"
d="m 53.5,60.5 c -0.275093,4.144916 -1.086323,5.991025 -2.088621,5.231821 C 49.111531,64.215714 51.9624,62.5514 53.5,60.5 Z"
id="path12" />
</g>
<g
id="g18"
transform="matrix(1.6409281,0,0,1.6409281,-33.288122,-29.848421)">
<path
fill="#4a4a4c"
d="m 45.394906,62.835155 v 0 C 45.295028,64.774264 44.112,69.461504 42.5,68.5 c -1.276548,-0.758272 1.006762,-3.720805 2.894906,-5.664845 z"
id="path16" />
</g>
<g
id="g22"
transform="matrix(1.6409281,0,0,1.6409281,-33.288122,-29.848421)">
<path
fill="#4a4a4c"
d="m 38.323024,64.01566 c -0.510774,3.779491 -1.468353,4.712106 -2.85558,5.927272 C 34.086944,69.443332 34.4528,69.0004 34.5,67.5 c 0.3457,-1.3492 1.729695,-2.377354 3.823024,-3.48434 z"
id="path20" />
</g>
<g
id="g26"
transform="matrix(1.6409281,0,0,1.6409281,-33.288122,-29.848421)">
<path
style="opacity:0.629"
fill="#4a4a4c"
d="m 50.5,68.5 c -0.332574,3.804597 -0.243075,6.57837 -2,6 -1.287633,-0.914112 0.7702,-4.2028 2,-6 z"
id="path24" />
</g>
<g
id="g30"
transform="matrix(1.6409281,0,0,1.6409281,-33.288122,-29.848421)">
<path
fill="#4a4a4c"
d="m 44.5,69.5 c -0.864872,3.818695 -1.946788,4.527584 -3.422663,4.213387 C 39.737799,72.940004 41.5,70.826657 44.5,69.5 Z"
id="path28" />
</g>
</svg>

After

Width:  |  Height:  |  Size: 3.8 KiB

+52
View File
@@ -0,0 +1,52 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
version="1.1"
width="100px"
height="100px"
style="shape-rendering:geometricPrecision; text-rendering:geometricPrecision; image-rendering:optimizeQuality; fill-rule:evenodd; clip-rule:evenodd"
id="svg340"
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg">
<g transform="matrix(1.6409281,0,0,1.6409281,-33.288122,-29.848421)">
<ellipse
style="fill:#ec6d4b;fill-opacity:0.945098;stroke-width:5.31402;stroke-linecap:square;stroke-linejoin:round;paint-order:fill markers stroke"
cx="62.378757"
cy="37.581673"
rx="15.100805"
ry="14.837029" />
<g>
<path
fill="#f2f1f1"
d="m 50.5,30.5 c 2.052249,1.654227 1.9412,3.9664 3,6 1.578183,1.489401 6.2139,1.5439 9,3 1.373984,1.322711 1.1816,3.9086 1,6 3.2882,-0.4844 5.9548,0.5156 8,3 1.3734,4.4358 0.04,7.9358 -4,10.5 -8.6603,0.4998 -17.3269,0.6664 -26,0.5 h -4 C 26.1179,60.2958 21.9513,55.2958 25,44.5 c 2.1413,-2.8208 4.9746,-4.1541 8.5,-4 -0.4488,-7.4279 3.0512,-11.4279 10.5,-12 2.4418,-0.0177 4.6085,0.649 6.5,2 z" />
</g>
<g>
<path
fill="#4a4a4c"
d="m 40.332727,59.754949 c -1.3333,2.6667 -3.02894,2.408643 -2.382156,-0.172998 C 38.498371,57.549651 39.657107,57.688323 41.5,56.5 Z" />
</g>
<g>
<path fill="#4a4a4c"
d="m 53.5,60.5 c -0.275093,4.144916 -1.086323,5.991025 -2.088621,5.231821 C 49.111531,64.215714 51.9624,62.5514 53.5,60.5 Z" />
</g>
<g>
<path
fill="#4a4a4c"
d="m 45.394906,62.835155 v 0 C 45.295028,64.774264 44.112,69.461504 42.5,68.5 c -1.276548,-0.758272 1.006762,-3.720805 2.894906,-5.664845 z" />
</g>
<g>
<path
fill="#4a4a4c"
d="m 38.323024,64.01566 c -0.510774,3.779491 -1.468353,4.712106 -2.85558,5.927272 C 34.086944,69.443332 34.4528,69.0004 34.5,67.5 c 0.3457,-1.3492 1.729695,-2.377354 3.823024,-3.48434 z" />
</g>
<g>
<path
style="opacity:0.629"
fill="#4a4a4c"
d="m 50.5,68.5 c -0.332574,3.804597 -0.243075,6.57837 -2,6 -1.287633,-0.914112 0.7702,-4.2028 2,-6 z" />
</g>
<g>
<path fill="#4a4a4c"
d="m 44.5,69.5 c -0.864872,3.818695 -1.946788,4.527584 -3.422663,4.213387 C 39.737799,72.940004 41.5,70.826657 44.5,69.5 Z" />
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 2.3 KiB

+18
View File
@@ -0,0 +1,18 @@
{
"name": "Bermite",
"short_name": "Bermite",
"description": "Application de suivi météo et de pluviométrie",
"lang": "fr",
"id": "/",
"start_url": "/",
"scope": "/",
"display": "standalone",
"theme_color": "#1d4ed8",
"background_color": "#ffffff",
"icons": [
{ "src": "/pwa-64x64.png", "sizes": "64x64", "type": "image/png" },
{ "src": "/pwa-192x192.png", "sizes": "192x192", "type": "image/png" },
{ "src": "/pwa-512x512.png", "sizes": "512x512", "type": "image/png", "purpose": "any" },
{ "src": "/maskable-icon-512x512.png", "sizes": "512x512", "type": "image/png", "purpose": "maskable" }
]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

+21
View File
@@ -0,0 +1,21 @@
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bermite — hors ligne</title>
<style>
body { font-family: system-ui, sans-serif; margin: 0; color: #111827; background: #fff; }
header { background: #1d4ed8; color: #fff; padding: 12px 20px; font-size: 1.25rem; font-weight: 700; }
main { padding: 20px; }
@media (prefers-color-scheme: dark) { body { background: #111827; color: #fff; } }
</style>
</head>
<body>
<header>Bermite</header>
<main>
<p>Vous êtes hors ligne et cette page n'a pas encore été consultée.</p>
<p><a href="/" style="color: inherit">Réessayer</a></p>
</main>
</body>
</html>
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 620 B

+2
View File
@@ -0,0 +1,2 @@
User-agent: *
Disallow: /
+59
View File
@@ -0,0 +1,59 @@
// Service worker de Bermite : permet de consulter hors ligne les pages déjà visitées.
//
// Stratégie « réseau d'abord » pour toutes les requêtes GET : la version en ligne est
// toujours servie quand le serveur répond (pas de risque de servir un ancien wasm après
// un déploiement), le cache ne sert qu'en secours. Les server functions (POST) ne sont
// jamais interceptées.
const CACHE = 'bermite-v1';
const PRECACHE = [
'/offline.html',
'/pkg/bermite_rs.css',
'/pkg/bermite_rs.js',
'/pkg/bermite_rs.wasm',
'/favicon.svg',
'/manifest.webmanifest',
'/images/icons/weather.svg',
];
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(CACHE)
// Un fichier manquant ne doit pas empêcher l'installation.
.then((cache) => Promise.allSettled(PRECACHE.map((url) => cache.add(url))))
.then(() => self.skipWaiting()),
);
});
self.addEventListener('activate', (event) => {
event.waitUntil(
caches.keys()
.then((keys) => Promise.all(keys.filter((key) => key !== CACHE).map((key) => caches.delete(key))))
.then(() => self.clients.claim()),
);
});
self.addEventListener('fetch', (event) => {
const request = event.request;
const url = new URL(request.url);
if (request.method !== 'GET' || url.origin !== self.location.origin || url.pathname.startsWith('/api/')) {
return;
}
event.respondWith(
fetch(request)
.then((response) => {
if (response.ok && !response.redirected) {
const copy = response.clone();
caches.open(CACHE).then((cache) => cache.put(request, copy));
}
return response;
})
.catch(async () => {
const cached = await caches.match(request);
if (cached) return cached;
if (request.mode === 'navigate') return caches.match('/offline.html');
return Response.error();
}),
);
});
+282
View File
@@ -0,0 +1,282 @@
use crate::{
auth::{self, Login, Logout, Register, ResetPassword, User},
icons::{Icon, IconName},
location::SaveLocation,
pages::{
auth::{ForgotPasswordPage, LoginPage, RegisterPage, ResetPasswordPage},
home::HomePage,
profile::ProfilePage,
rainfall::{RainfallGraphPage, RainfallIndexPage},
weather::WeatherPage,
},
profile::UpdateTheme,
ui::Loading,
};
use leptos::prelude::*;
use leptos_meta::{Html, Meta, MetaTags, Stylesheet, Title, provide_meta_context};
use leptos_router::{
SsrMode,
components::{A, Redirect, Route, Router, Routes},
path,
};
pub fn shell(options: LeptosOptions) -> impl IntoView {
view! {
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#2563eb" />
<meta name="description" content="Application de suivi météo et de pluviométrie" />
<link rel="icon" href="/favicon.ico" sizes="64x64" />
<link rel="icon" href="/favicon.svg" sizes="any" type="image/svg+xml" />
<link rel="apple-touch-icon" href="/apple-touch-icon-180x180.png" sizes="180x180" />
<link rel="manifest" href="/manifest.webmanifest" />
<link rel="preconnect" href="https://fonts.bunny.net" />
<link href="https://fonts.bunny.net/css?family=figtree:400,500,600,700&display=swap" rel="stylesheet" />
<AutoReload options=options.clone() />
<HydrationScripts options />
<MetaTags />
// Service worker : mise en cache pour l'usage hors ligne (voir public/sw.js).
<script>
"if ('serviceWorker' in navigator) { window.addEventListener('load', () => navigator.serviceWorker.register('/sw.js')) }"
</script>
</head>
<body class="min-h-screen bg-slate-50 font-sans text-slate-900 antialiased dark:bg-slate-950 dark:text-slate-100">
<App />
</body>
</html>
}
}
/// Utilisateur courant, partagé par l'en-tête et les pages. Rechargé après chaque
/// connexion, déconnexion ou modification du profil.
#[derive(Clone, Copy)]
pub struct CurrentUser(pub Resource<Result<Option<User>, ServerFnError>>);
#[component]
pub fn App() -> impl IntoView {
provide_meta_context();
let login = ServerAction::<Login>::new();
let logout = ServerAction::<Logout>::new();
let register = ServerAction::<Register>::new();
let reset = ServerAction::<ResetPassword>::new();
let save_location = ServerAction::<SaveLocation>::new();
let update_theme = ServerAction::<UpdateTheme>::new();
let user = Resource::new(
move || {
(
login.version().get(),
logout.version().get(),
register.version().get(),
save_location.version().get(),
update_theme.version().get(),
)
},
|_| auth::get_user(),
);
provide_context(CurrentUser(user));
// Apparence choisie dans le profil, posée sur `<html>` (sans attribut : suit le système).
let theme = move || {
user.get()
.and_then(Result::ok)
.flatten()
.and_then(|user| user.theme.html_attr())
};
view! {
<Stylesheet id="leptos" href="/pkg/bermite_rs.css" />
<Title text="Bermite" />
<Meta name="color-scheme" content="light dark" />
// Sous un `Transition` : le serveur attend l'utilisateur avant de rendre `<html>`,
// ce qui évite un éclair de mauvais thème.
<Transition>
<Html {..} data-theme=theme />
</Transition>
<Router>
<Header />
// Marge basse sur mobile : la barre d'onglets est fixée en bas de l'écran.
<main class="pb-24 sm:pb-0">
<Routes fallback=|| view! { <p class="m-5">"Page introuvable."</p> }>
<Route path=path!("/") view=HomePage ssr=SsrMode::Async />
<Route
path=path!("/connexion")
view=move || view! { <LoginPage login /> }
ssr=SsrMode::Async
/>
<Route
path=path!("/sinscrire")
view=move || view! { <RegisterPage register /> }
ssr=SsrMode::Async
/>
<Route path=path!("/mot-de-passe-oubliee") view=ForgotPasswordPage ssr=SsrMode::Async />
<Route
path=path!("/changer-le-mot-de-passe/:token")
view=move || view! { <ResetPasswordPage reset /> }
ssr=SsrMode::Async
/>
<Route
path=path!("/profile")
view=move || view! { <ProfilePage logout save_location update_theme /> }
ssr=SsrMode::Async
/>
<Route path=path!("/meteo") view=WeatherPage ssr=SsrMode::Async />
<Route path=path!("/pluviometrie") view=RainfallGraphPage ssr=SsrMode::Async />
<Route path=path!("/pluviometrie/mesures") view=RainfallIndexPage ssr=SsrMode::Async />
</Routes>
</main>
<TabBar />
</Router>
}
}
/// Liens de navigation principaux : (adresse, libellé, icône, correspondance exacte).
const NAV: [(&str, &str, IconName, bool); 3] = [
("/", "Accueil", IconName::Home, true),
("/pluviometrie", "Pluviométrie", IconName::CloudRain, false),
("/meteo", "Météo", IconName::CloudSun, false),
];
#[component]
fn Header() -> impl IntoView {
let CurrentUser(user) = expect_context();
view! {
<header class="sticky top-0 z-20 border-b border-slate-200 bg-white/80 backdrop-blur dark:border-slate-800 dark:bg-slate-900/80">
<div class="mx-auto flex h-16 max-w-5xl items-center justify-between gap-4 px-4 sm:px-6">
<A href="/" attr:class="flex items-center gap-2.5 font-bold tracking-tight">
<img src="/favicon.svg" alt="" width="32" height="32" class="size-8" />
<span class="text-lg">"Bermite"</span>
</A>
<Transition>
{move || {
user.get()
.map(|user| match user {
Ok(Some(user)) => {
let initial = user
.name
.chars()
.next()
.map(|c| c.to_uppercase().to_string())
.unwrap_or_default();
view! {
// Le lien actif reçoit `aria-current="page"` du routeur.
<nav class="hidden items-center gap-1 sm:flex" aria-label="Navigation principale">
{NAV
.into_iter()
.map(|(href, label, icon, exact)| {
view! {
<A
href=href
exact=exact
attr:class="flex items-center gap-2 rounded-full px-3.5 py-1.5 text-sm font-medium text-slate-600 transition hover:bg-slate-100 hover:text-slate-900 aria-[current=page]:bg-blue-50 aria-[current=page]:text-blue-700 dark:text-slate-300 dark:hover:bg-slate-800 dark:hover:text-white dark:aria-[current=page]:bg-blue-500/15 dark:aria-[current=page]:text-blue-300"
>
<Icon icon class="size-4" />
{label}
</A>
}
})
.collect_view()}
</nav>
<A
href="/profile"
attr:class="flex items-center gap-2 rounded-full py-1 pr-1 pl-3 text-sm font-medium text-slate-700 transition hover:bg-slate-100 aria-[current=page]:bg-slate-100 dark:text-slate-200 dark:hover:bg-slate-800 dark:aria-[current=page]:bg-slate-800"
attr:title="Mon profil"
>
<span class="hidden max-w-32 truncate sm:inline">{user.name}</span>
<span class="flex size-8 items-center justify-center rounded-full bg-gradient-to-br from-blue-500 to-indigo-600 font-semibold text-white">
{initial}
</span>
</A>
}
.into_any()
}
_ => {
view! {
<A href="/connexion" attr:class="btn-ghost">
"Connexion"
</A>
}
.into_any()
}
})
}}
</Transition>
</div>
</header>
}
}
/// Barre d'onglets en bas de l'écran, sur mobile, pour un utilisateur connecté.
#[component]
fn TabBar() -> impl IntoView {
let CurrentUser(user) = expect_context();
let tabs = NAV
.into_iter()
.chain([("/profile", "Profil", IconName::User, false)])
.collect::<Vec<_>>();
view! {
<Transition>
{move || {
matches!(user.get(), Some(Ok(Some(_))))
.then(|| {
view! {
<nav
class="fixed inset-x-0 bottom-0 z-20 border-t border-slate-200 bg-white/90 pb-[env(safe-area-inset-bottom)] backdrop-blur sm:hidden dark:border-slate-800 dark:bg-slate-900/90"
aria-label="Navigation principale"
>
<div class="grid grid-cols-4">
{tabs
.clone()
.into_iter()
.map(|(href, label, icon, exact)| {
view! {
<A
href=href
exact=exact
attr:class="flex flex-col items-center gap-1 py-2.5 text-[11px] font-medium text-slate-500 transition aria-[current=page]:text-blue-600 dark:text-slate-400 dark:aria-[current=page]:text-blue-400"
>
<Icon icon class="size-6" />
{label}
</A>
}
})
.collect_view()}
</div>
</nav>
}
})
}}
</Transition>
}
}
/// N'affiche `render` que pour un utilisateur connecté ; redirige sinon vers /connexion.
///
/// L'utilisateur est rechargé par la page elle-même : juste après une connexion, la
/// ressource globale de l'en-tête peut encore être périmée.
#[component]
pub fn Protected<F, V>(render: F) -> impl IntoView
where
F: Fn(User) -> V + Send + Sync + 'static,
V: IntoView + 'static,
{
let user = Resource::new(|| (), |_| auth::get_user());
view! {
<Suspense fallback=|| view! { <div class="mx-auto max-w-5xl px-4 py-8 sm:px-6"><Loading height="h-64" /></div> }>
{move || {
user.get()
.map(|user| match user {
Ok(Some(user)) => render(user).into_any(),
// Au rendu serveur, `Redirect` répond par un vrai 302 aux navigateurs.
_ => view! { <Redirect path="/connexion" /> }.into_any(),
})
}}
</Suspense>
}
}
+390
View File
@@ -0,0 +1,390 @@
//! Authentification : utilisateur courant, connexion, mot de passe oublié, inscription.
//!
//! Les corps des `#[server]` ne sont compilés que côté serveur ; le client
//! n'en garde que la signature (un appel HTTP généré par la macro).
use leptos::prelude::*;
use serde::{Deserialize, Serialize};
use crate::{errors::field_error, location::Location, profile::Theme};
#[cfg(feature = "ssr")]
use crate::{
mail,
server::{self, USER_ID_KEY},
};
/// Utilisateur connecté, tel qu'exposé au front (jamais de hash de mot de passe ici).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct User {
pub id: i64,
pub name: String,
pub email: String,
pub theme: Theme,
pub locations: Vec<Location>,
}
impl User {
pub fn has_location(&self) -> bool {
!self.locations.is_empty()
}
}
pub const PASSWORD_MAX: usize = 128;
pub const EMAIL_MAX: usize = 254;
/// Durée de validité d'un lien de réinitialisation.
pub const RESET_TOKEN_HOURS: i64 = 24;
/// Met l'adresse en forme canonique : sans espaces autour, en minuscules.
pub fn normalize_email(email: &str) -> String {
email.trim().to_lowercase()
}
/// Validation pragmatique (pas la RFC complète) d'une adresse déjà normalisée.
pub fn validate_email(email: &str) -> Result<(), &'static str> {
const INVALID: &str = "Adresse e-mail invalide.";
if email.len() > EMAIL_MAX {
return Err(INVALID);
}
let Some((local, domain)) = email.split_once('@') else {
return Err(INVALID);
};
let local_ok = !local.is_empty()
&& local
.chars()
.all(|c| !c.is_whitespace() && !c.is_control() && !"@<>()[],;:\\\"".contains(c));
let domain_ok = domain.contains('.')
&& domain.split('.').all(|label| {
!label.is_empty() && label.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')
});
if local_ok && domain_ok {
Ok(())
} else {
Err(INVALID)
}
}
/// Même règle que lara-bermite : au moins 8 caractères dont une majuscule,
/// une minuscule et un chiffre.
pub fn validate_password(password: &str) -> Result<(), &'static str> {
const RULES: &str = "Le mot de passe doit contenir au moins 8 caractères, dont une majuscule, une minuscule et un chiffre.";
let len = password.chars().count();
if len > PASSWORD_MAX {
return Err("Le mot de passe doit faire au plus 128 caractères.");
}
let ok = len >= 8
&& password.chars().any(|c| c.is_uppercase())
&& password.chars().any(|c| c.is_lowercase())
&& password.chars().any(|c| c.is_ascii_digit());
if ok { Ok(()) } else { Err(RULES) }
}
/// Valide un nouveau mot de passe et sa confirmation (réinitialisation, inscription).
pub fn validate_new_password(password: &str, confirmation: &str) -> Result<(), ServerFnError> {
validate_password(password).map_err(|e| field_error("password", e))?;
if password != confirmation {
return Err(field_error(
"password_confirmation",
"La confirmation ne correspond pas au mot de passe.",
));
}
Ok(())
}
/// Renvoie l'utilisateur connecté, ou `None` s'il n'y a pas de session valide.
#[server]
pub async fn get_user() -> Result<Option<User>, ServerFnError> {
let session = server::session().await?;
let Some(user_id) = session
.get::<i64>(USER_ID_KEY)
.await
.map_err(server::internal_error)?
else {
return Ok(None);
};
let pool = server::pool()?;
let row = sqlx::query_as::<_, (i64, String, String, String)>(
"SELECT id, name, email, theme FROM users WHERE id = ?1",
)
.bind(user_id)
.fetch_optional(&pool)
.await
.map_err(server::internal_error)?;
let Some((id, name, email, theme)) = row else {
// L'utilisateur a été supprimé : on invalide la session orpheline.
session.flush().await.map_err(server::internal_error)?;
return Ok(None);
};
let locations = crate::location::user_locations(&pool, id).await?;
Ok(Some(User {
id,
name,
email,
theme: Theme::parse(&theme).unwrap_or_default(),
locations,
}))
}
/// Connecte l'utilisateur si les identifiants sont corrects.
#[server]
pub async fn login(email: String, password: String) -> Result<(), ServerFnError> {
// Message identique pour « compte inconnu » et « mauvais mot de passe ».
const INVALID: &str = "Ces identifiants ne correspondent à aucun compte.";
if password.chars().count() > PASSWORD_MAX {
return Err(ServerFnError::new(INVALID));
}
let pool = server::pool()?;
let row =
sqlx::query_as::<_, (i64, String)>("SELECT id, password_hash FROM users WHERE email = ?1")
.bind(normalize_email(&email))
.fetch_optional(&pool)
.await
.map_err(server::internal_error)?;
let user_id = row.as_ref().map(|(id, _)| *id);
let stored_hash = row.map(|(_, hash)| hash);
let legacy = stored_hash.as_deref().is_some_and(server::is_legacy_hash);
if !server::verify_password(password.clone(), stored_hash).await {
return Err(ServerFnError::new(INVALID));
}
// `verify_password` ne renvoie `true` que si l'utilisateur existe.
let user_id = user_id.expect("utilisateur existant");
// Compte importé de Laravel : on remplace le hash bcrypt par un hash Argon2.
if legacy {
let hash = server::hash_password(password).await?;
sqlx::query(
"UPDATE users SET password_hash = ?1, updated_at = CURRENT_TIMESTAMP WHERE id = ?2",
)
.bind(hash)
.bind(user_id)
.execute(&pool)
.await
.map_err(server::internal_error)?;
}
start_session(user_id).await?;
leptos_axum::redirect("/");
Ok(())
}
/// Déconnecte l'utilisateur et détruit sa session.
#[server]
pub async fn logout() -> Result<(), ServerFnError> {
server::session()
.await?
.flush()
.await
.map_err(server::internal_error)?;
leptos_axum::redirect("/connexion");
Ok(())
}
/// Envoie un lien de réinitialisation si l'adresse correspond à un compte.
///
/// La réponse est la même que l'adresse existe ou non, et l'e-mail part en tâche de fond :
/// ni le message ni le temps de réponse ne révèlent quels comptes existent.
#[server]
pub async fn forgot_password(email: String) -> Result<(), ServerFnError> {
let email = normalize_email(&email);
validate_email(&email).map_err(|e| field_error("email", e))?;
let pool = server::pool()?;
let exists = sqlx::query_scalar::<_, i64>("SELECT id FROM users WHERE email = ?1")
.bind(&email)
.fetch_optional(&pool)
.await
.map_err(server::internal_error)?
.is_some();
if !exists {
return Ok(());
}
let token = server::random_token();
sqlx::query(
"INSERT INTO password_reset_tokens (email, token_hash, created_at) \
VALUES (?1, ?2, CURRENT_TIMESTAMP) \
ON CONFLICT (email) DO UPDATE SET token_hash = excluded.token_hash, created_at = excluded.created_at",
)
.bind(&email)
.bind(server::token_hash(&token))
.execute(&pool)
.await
.map_err(server::internal_error)?;
let config = server::config()?;
let link = format!("{}/changer-le-mot-de-passe/{token}", config.app_url);
tokio::spawn(async move {
if let Err(e) = mail::send_reset_link(&config, &email, &link).await {
leptos::logging::error!("envoi du lien de réinitialisation impossible : {e}");
}
});
Ok(())
}
/// Change le mot de passe à partir d'un lien de réinitialisation valide.
#[server]
pub async fn reset_password(
token: String,
email: String,
password: String,
password_confirmation: String,
) -> Result<(), ServerFnError> {
const INVALID: &str = "Ce lien de réinitialisation est invalide ou a expiré.";
let email = normalize_email(&email);
validate_email(&email).map_err(|e| field_error("email", e))?;
validate_new_password(&password, &password_confirmation)?;
let pool = server::pool()?;
let valid = sqlx::query_scalar::<_, i64>(
"SELECT 1 FROM password_reset_tokens \
WHERE email = ?1 AND token_hash = ?2 AND created_at > datetime('now', ?3)",
)
.bind(&email)
.bind(server::token_hash(&token))
.bind(format!("-{RESET_TOKEN_HOURS} hours"))
.fetch_optional(&pool)
.await
.map_err(server::internal_error)?
.is_some();
if !valid {
return Err(ServerFnError::new(INVALID));
}
let hash = server::hash_password(password).await?;
let mut tx = pool.begin().await.map_err(server::internal_error)?;
sqlx::query(
"UPDATE users SET password_hash = ?1, updated_at = CURRENT_TIMESTAMP WHERE email = ?2",
)
.bind(hash)
.bind(&email)
.execute(&mut *tx)
.await
.map_err(server::internal_error)?;
sqlx::query("DELETE FROM password_reset_tokens WHERE email = ?1")
.bind(&email)
.execute(&mut *tx)
.await
.map_err(server::internal_error)?;
tx.commit().await.map_err(server::internal_error)?;
leptos_axum::redirect("/connexion");
Ok(())
}
/// Les inscriptions sont-elles ouvertes (`REGISTRATION_ENABLED=true`) ?
#[server]
pub async fn registration_open() -> Result<bool, ServerFnError> {
Ok(server::config()?.registration_enabled)
}
/// Crée un compte puis connecte l'utilisateur. Refusé si les inscriptions sont fermées.
#[server]
pub async fn register(
name: String,
email: String,
password: String,
password_confirmation: String,
) -> Result<(), ServerFnError> {
if !server::config()?.registration_enabled {
return Err(ServerFnError::new("Les inscriptions ne sont pas ouvertes."));
}
let name = name.trim().to_string();
if !(3..=100).contains(&name.chars().count()) {
return Err(field_error(
"name",
"Le nom doit faire entre 3 et 100 caractères.",
));
}
let email = normalize_email(&email);
validate_email(&email).map_err(|e| field_error("email", e))?;
validate_new_password(&password, &password_confirmation)?;
let hash = server::hash_password(password).await?;
let result = sqlx::query("INSERT INTO users (name, email, password_hash) VALUES (?1, ?2, ?3)")
.bind(&name)
.bind(&email)
.bind(&hash)
.execute(&server::pool()?)
.await;
let user_id = match result {
Ok(done) => done.last_insert_rowid(),
Err(sqlx::Error::Database(e)) if e.is_unique_violation() => {
return Err(field_error(
"email",
"Un compte existe déjà avec cette adresse.",
));
}
Err(e) => return Err(server::internal_error(e)),
};
start_session(user_id).await?;
leptos_axum::redirect("/");
Ok(())
}
/// Ouvre une session pour `user_id`, en renouvelant l'identifiant de session
/// (`cycle_id`) contre la fixation de session.
#[cfg(feature = "ssr")]
async fn start_session(user_id: i64) -> Result<(), ServerFnError> {
let session = server::session().await?;
session.cycle_id().await.map_err(server::internal_error)?;
session
.insert(USER_ID_KEY, user_id)
.await
.map_err(server::internal_error)?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn email_normalization() {
assert_eq!(normalize_email(" Alice@Example.COM "), "alice@example.com");
}
#[test]
fn email_validation() {
assert!(validate_email("alice@example.com").is_ok());
for email in [
"",
"alice",
"alice@",
"@example.com",
"alice@example",
"a b@example.com",
] {
assert!(
validate_email(email).is_err(),
"{email} devrait être invalide"
);
}
}
#[test]
fn password_rules_match_laravel() {
assert!(validate_password("Abcdefg1").is_ok());
assert!(validate_password("Abcdef1").is_err(), "trop court");
assert!(validate_password("abcdefg1").is_err(), "sans majuscule");
assert!(validate_password("ABCDEFG1").is_err(), "sans minuscule");
assert!(validate_password("Abcdefgh").is_err(), "sans chiffre");
assert!(
validate_password(&format!("Ab1{}", "a".repeat(130))).is_err(),
"trop long"
);
}
#[test]
fn confirmation_must_match() {
assert!(validate_new_password("Abcdefg1", "Abcdefg1").is_ok());
let error = validate_new_password("Abcdefg1", "Abcdefg2").unwrap_err();
assert!(crate::errors::error_for_field(&error, "password_confirmation").is_some());
}
}
+127
View File
@@ -0,0 +1,127 @@
//! Import unique des données de lara-bermite (MySQL) dans la base SQLite de bermite_rs.
//!
//! ```sh
//! cargo run --bin import_mysql --features ssr,import -- \
//! mysql://utilisateur:motdepasse@127.0.0.1/lara_bermite sqlite:bermite.db
//! ```
//!
//! Copie `users`, `locations` et `rainfalls` en conservant les identifiants. Les hash
//! bcrypt de Laravel sont repris tels quels : ils restent valides et sont convertis en
//! Argon2 à la connexion suivante. Les sessions et jetons ne sont pas repris.
//! Refuse de s'exécuter si la base cible contient déjà des utilisateurs.
use bermite_rs::server::connect_db;
use sqlx::{MySqlPool, Row};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut args = std::env::args().skip(1);
let (Some(mysql_url), Some(sqlite_url)) = (args.next(), args.next()) else {
eprintln!("usage : import_mysql <url mysql> <url sqlite>");
std::process::exit(2);
};
let mysql = MySqlPool::connect(&mysql_url).await?;
let sqlite = connect_db(&sqlite_url).await?;
let existing: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM users")
.fetch_one(&sqlite)
.await?;
if existing > 0 {
return Err(format!(
"la base cible contient déjà {existing} utilisateur(s) : import annulé"
)
.into());
}
// Les conversions sont faites côté MySQL : entiers signés, dates en texte.
let users = sqlx::query(
"SELECT CAST(id AS SIGNED) AS id, name, email, password, \
DATE_FORMAT(COALESCE(created_at, NOW()), '%Y-%m-%d %H:%i:%s') AS created_at, \
DATE_FORMAT(COALESCE(updated_at, NOW()), '%Y-%m-%d %H:%i:%s') AS updated_at \
FROM users ORDER BY id",
)
.fetch_all(&mysql)
.await?;
let locations = sqlx::query(
"SELECT CAST(id AS SIGNED) AS id, CAST(user_id AS SIGNED) AS user_id, latitude, longitude, \
DATE_FORMAT(COALESCE(created_at, NOW()), '%Y-%m-%d %H:%i:%s') AS created_at \
FROM locations ORDER BY id",
)
.fetch_all(&mysql)
.await?;
let rainfalls = sqlx::query(
"SELECT CAST(id AS SIGNED) AS id, CAST(user_id AS SIGNED) AS user_id, \
DATE_FORMAT(date, '%Y-%m-%d') AS date, CAST(value AS SIGNED) AS value, \
DATE_FORMAT(COALESCE(created_at, NOW()), '%Y-%m-%d %H:%i:%s') AS created_at, \
DATE_FORMAT(COALESCE(updated_at, NOW()), '%Y-%m-%d %H:%i:%s') AS updated_at \
FROM rainfalls ORDER BY id",
)
.fetch_all(&mysql)
.await?;
let mut tx = sqlite.begin().await?;
for row in &users {
sqlx::query(
"INSERT INTO users (id, name, email, password_hash, created_at, updated_at) \
VALUES (?1, ?2, lower(trim(?3)), ?4, ?5, ?6)",
)
.bind(row.try_get::<i64, _>("id")?)
.bind(row.try_get::<String, _>("name")?)
.bind(row.try_get::<String, _>("email")?)
.bind(row.try_get::<String, _>("password")?)
.bind(row.try_get::<String, _>("created_at")?)
.bind(row.try_get::<String, _>("updated_at")?)
.execute(&mut *tx)
.await?;
}
for row in &locations {
sqlx::query("INSERT INTO locations (id, user_id, latitude, longitude, created_at) VALUES (?1, ?2, ?3, ?4, ?5)")
.bind(row.try_get::<i64, _>("id")?)
.bind(row.try_get::<i64, _>("user_id")?)
.bind(row.try_get::<f64, _>("latitude")?)
.bind(row.try_get::<f64, _>("longitude")?)
.bind(row.try_get::<String, _>("created_at")?)
.execute(&mut *tx)
.await?;
}
let mut skipped = 0;
for row in &rainfalls {
let value: i64 = row.try_get("value")?;
// La contrainte SQLite impose 1 à 1000 mm, comme la validation de Laravel.
if !(1..=1000).contains(&value) {
eprintln!(
"mesure {} ignorée : valeur {value} hors limites",
row.try_get::<i64, _>("id")?
);
skipped += 1;
continue;
}
sqlx::query(
"INSERT INTO rainfalls (id, user_id, date, value, created_at, updated_at) \
VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
)
.bind(row.try_get::<i64, _>("id")?)
.bind(row.try_get::<i64, _>("user_id")?)
.bind(row.try_get::<String, _>("date")?)
.bind(value)
.bind(row.try_get::<String, _>("created_at")?)
.bind(row.try_get::<String, _>("updated_at")?)
.execute(&mut *tx)
.await?;
}
tx.commit().await?;
println!(
"import terminé : {} utilisateur(s), {} emplacement(s), {} mesure(s){}",
users.len(),
locations.len(),
rainfalls.len() - skipped,
if skipped > 0 {
format!(" ({skipped} ignorée(s))")
} else {
String::new()
},
);
Ok(())
}
+304
View File
@@ -0,0 +1,304 @@
//! Graphique en colonnes (une ou plusieurs séries), en HTML et CSS.
//!
//! Les barres sont des `<div>` dont la hauteur est un pourcentage de la zone de tracé :
//! le graphique occupe toute la largeur disponible sans JavaScript ni mesure du
//! conteneur, et le texte n'est jamais déformé. Conventions : barres de 24 px au plus,
//! coins arrondis en haut et droits sur la ligne de base, 2 px d'écart entre barres
//! voisines, grille discrète, une seule valeur écrite (le maximum, pour une série
//! seule) ; le détail de chaque colonne est dans l'infobulle.
use leptos::prelude::*;
/// Hauteur de la zone de tracé, en pixels.
const PLOT_HEIGHT: u32 = 240;
/// Nombre maximal de libellés sur l'axe horizontal (écran large / petit écran).
const MAX_AXIS_LABELS: usize = 12;
const MAX_AXIS_LABELS_SMALL: usize = 5;
/// Au-delà, les barres se touchent (plus d'écart de 2 px).
const MAX_GAPPED_COLUMNS: usize = 60;
/// Une série : son nom (légende, infobulle) et la classe de couleur de ses barres.
#[derive(Clone, Debug, PartialEq)]
pub struct Series {
pub name: String,
pub color: &'static str,
}
/// Une colonne : son libellé et une valeur par série (`None` : pas de barre).
#[derive(Clone, Debug, PartialEq)]
pub struct Column {
/// Libellé de l'axe horizontal.
pub label: String,
/// Titre de l'infobulle (par défaut, le libellé).
pub title: Option<String>,
pub values: Vec<Option<i64>>,
}
/// Graduation « ronde » de l'axe vertical (1, 2, 5 × 10ⁿ) pour environ 4 intervalles.
pub fn nice_step(max: i64) -> i64 {
let raw = (max.max(1) as f64 / 4.0).max(1.0);
let magnitude = 10f64.powf(raw.log10().floor());
let step = [1.0, 2.0, 5.0, 10.0]
.into_iter()
.map(|m| m * magnitude)
.find(|step| *step >= raw)
.unwrap_or(10.0 * magnitude);
step as i64
}
/// Haut de l'axe : premier multiple de `step` supérieur ou égal au maximum.
fn axis_top(max: i64, step: i64) -> i64 {
(max.max(1) + step - 1) / step * step
}
#[component]
pub fn ColumnChart(
series: Vec<Series>,
columns: Vec<Column>,
/// Unité des valeurs (infobulle).
#[prop(default = "mm")]
unit: &'static str,
#[prop(optional, into)] loading: Signal<bool>,
) -> impl IntoView {
let hovered = RwSignal::new(None::<usize>);
let max = columns
.iter()
.flat_map(|c| c.values.iter().flatten())
.copied()
.max()
.unwrap_or(0);
let step = nice_step(max);
let top = axis_top(max, step);
let percent = move |value: i64| value as f64 / top as f64 * 100.0;
let ticks: Vec<i64> = (0..=top / step).map(|i| i * step).collect();
let n = columns.len().max(1);
let label_every = n.div_ceil(MAX_AXIS_LABELS);
let label_every_small = n.div_ceil(MAX_AXIS_LABELS_SMALL);
let gap = if columns.len() <= MAX_GAPPED_COLUMNS {
"gap-[2px]"
} else {
""
};
// Une série seule : on écrit la valeur de la plus haute colonne, et rien d'autre.
let max_index = (series.len() == 1 && max > 0)
.then(|| {
columns
.iter()
.position(|c| c.values.first().copied().flatten() == Some(max))
})
.flatten();
let multi = series.len() > 1;
let tooltip_columns = columns.clone();
let tooltip_series = series.clone();
view! {
<div class="flex flex-col gap-3 transition-opacity" class=("opacity-50", move || loading.try_get().unwrap_or(false))>
{multi
.then(|| {
view! {
<ul class="flex flex-wrap gap-x-4 gap-y-1 text-sm" aria-label="Légende">
{series
.iter()
.map(|s| {
view! {
<li class="flex items-center gap-1.5">
<span class=format!("size-2.5 rounded-sm {}", s.color)></span>
<span class="muted">{s.name.clone()}</span>
</li>
}
})
.collect_view()}
</ul>
}
})}
<div class="flex pt-5">
// Graduations de l'axe vertical.
<div class="relative w-9 shrink-0" style=format!("height: {PLOT_HEIGHT}px") aria-hidden="true">
{ticks
.iter()
.map(|&tick| {
view! {
<span
class="muted absolute right-2 translate-y-1/2 text-[11px] tabular-nums"
style=format!("bottom: {}%", percent(tick))
>
{tick}
</span>
}
})
.collect_view()}
</div>
<div
class="relative min-w-0 flex-1"
style=format!("height: {PLOT_HEIGHT}px")
on:pointerleave=move |_| hovered.set(None)
>
// Lignes de la grille (la ligne de base un ton plus marqué).
{ticks
.iter()
.map(|&tick| {
let class = if tick == 0 {
"absolute inset-x-0 border-t border-slate-300 dark:border-slate-600"
} else {
"absolute inset-x-0 border-t border-slate-100 dark:border-slate-800"
};
view! { <div class=class style=format!("bottom: {}%", percent(tick))></div> }
})
.collect_view()}
<div class=format!("absolute inset-0 flex items-end {gap}") role="img" aria-label="Graphique en colonnes">
{columns
.iter()
.enumerate()
.map(|(i, column)| {
let bars = column
.values
.iter()
.zip(&series)
.map(|(value, s)| {
let value = value.unwrap_or(0);
let label = (max_index == Some(i))
.then(|| {
view! {
<span class="mb-1 text-[11px] font-semibold tabular-nums">{value}</span>
}
});
view! {
<div class="flex h-full w-full max-w-6 min-w-0 flex-col items-center justify-end">
{label}
<div
class=format!("w-full rounded-t-[4px] transition-[height] {}", s.color)
style=format!("height: {}%", percent(value))
></div>
</div>
}
})
.collect_view();
view! {
<div
class=format!(
"flex h-full min-w-0 flex-1 cursor-default items-end justify-center rounded-t-md transition-colors {gap}",
)
class=("bg-slate-500/10", move || hovered.try_get().flatten() == Some(i))
on:pointerenter=move |_| hovered.set(Some(i))
on:click=move |_| hovered.set(Some(i))
>
{bars}
</div>
}
})
.collect_view()}
</div>
// Infobulle de la colonne survolée.
{move || {
hovered
.try_get()
.flatten()
.and_then(|i| tooltip_columns.get(i).map(|c| (i, c.clone())))
.map(|(i, column)| {
let center = (i as f64 + 0.5) / n as f64 * 100.0;
// Recentrée vers l'intérieur près des bords.
let shift = if center < 20.0 {
"0%"
} else if center > 80.0 {
"-100%"
} else {
"-50%"
};
view! {
<div
class="pointer-events-none absolute -top-2 z-10 min-w-36 rounded-lg border border-slate-200 bg-white px-3 py-2 text-sm shadow-lg dark:border-slate-700 dark:bg-slate-800"
style=format!("left: {center}%; transform: translate({shift}, -100%)")
>
<div class="mb-1 font-semibold whitespace-nowrap">
{column.title.clone().unwrap_or(column.label.clone())}
</div>
{column
.values
.iter()
.zip(&tooltip_series)
.map(|(value, s)| {
view! {
<div class="flex items-center justify-between gap-4 whitespace-nowrap">
<span class="flex items-center gap-1.5">
<span class=format!("size-2 rounded-sm {}", s.color)></span>
<span class="muted">{s.name.clone()}</span>
</span>
<span class="font-semibold tabular-nums">
{match value {
Some(v) => format!("{v} {unit}"),
None => "—".to_string(),
}}
</span>
</div>
}
})
.collect_view()}
</div>
}
})
}}
</div>
</div>
// Libellés de l'axe horizontal : un sur `label_every` (un sur `label_every_small` sur mobile).
<div class="ml-9 flex h-4" aria-hidden="true">
{columns
.iter()
.enumerate()
.map(|(i, column)| {
let wide = i % label_every == 0;
let small = i % label_every_small == 0;
// Le premier et le dernier libellé sont alignés sur les bords, pour ne pas déborder.
let anchor = if i == 0 {
"left-0"
} else if i + 1 == columns.len() {
"right-0"
} else {
"left-1/2 -translate-x-1/2"
};
let visibility = match (wide, small) {
(true, true) => "",
(true, false) => "max-sm:invisible",
(false, true) => "sm:invisible",
(false, false) => "invisible",
};
view! {
<div class="relative min-w-0 flex-1">
<span class=format!(
"muted absolute {anchor} text-[11px] whitespace-nowrap {visibility}",
)>{column.label.clone()}</span>
</div>
}
})
.collect_view()}
</div>
</div>
}
// Effacement du type : la vue est très imbriquée.
.into_any()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn nice_steps() {
assert_eq!(nice_step(0), 1);
assert_eq!(nice_step(4), 1);
assert_eq!(nice_step(10), 5);
assert_eq!(nice_step(23), 10);
assert_eq!(nice_step(80), 20);
assert_eq!(nice_step(260), 100);
assert_eq!(nice_step(1000), 500);
}
#[test]
fn axis_top_rounds_up_to_a_step() {
assert_eq!(axis_top(0, 1), 1);
assert_eq!(axis_top(20, 5), 20);
assert_eq!(axis_top(42, 10), 50);
}
}
+325
View File
@@ -0,0 +1,325 @@
//! Blocs de la pluviométrie partagés entre l'accueil et la page Pluviométrie.
use chrono::Datelike;
use leptos::{html, prelude::*};
use leptos_router::components::A;
use crate::{
chart::{Column, ColumnChart, Series},
errors::error_message,
icons::{Icon, IconName},
rainfall::{
self, AddRainfall, MonthlySummary,
graph::{month_name, month_short},
},
ui::{
Card, ErrorBanner, Field, Loading, StatTile, SubmitButton, SuccessBanner, field_error_of,
general_error_of, succeeded,
},
weather::weekday_fr,
};
/// Nombre avec séparateur de milliers à la française (espace fine insécable).
pub fn format_number(value: i64) -> String {
let digits = value.unsigned_abs().to_string();
let mut out = String::new();
for (i, c) in digits.chars().enumerate() {
if i > 0 && (digits.len() - i).is_multiple_of(3) {
out.push('\u{202f}');
}
out.push(c);
}
if value < 0 { format!("-{out}") } else { out }
}
/// « mardi 14 octobre » à partir d'une date AAAA-MM-JJ.
pub fn format_long_date(date: &str) -> String {
chrono::NaiveDate::parse_from_str(date, "%Y-%m-%d")
.map(|d| {
format!(
"{} {} {}",
weekday_fr(d.weekday()),
d.day(),
month_name(d.month()).to_lowercase()
)
})
.unwrap_or_else(|_| date.to_string())
}
/// Formulaire « Nouvelle mesure ».
#[component]
pub fn AddRainfallForm(add: ServerAction<AddRainfall>) -> impl IntoView {
let value = add.value();
let form = NodeRef::<html::Form>::new();
let today = rainfall::today().format("%Y-%m-%d").to_string();
// Vide le formulaire après un ajout réussi (`ActionForm` ne le fait pas) ; la date
// revient à sa valeur par défaut, aujourd'hui.
Effect::new(move |_| {
if succeeded(value).get()
&& let Some(form) = form.get()
{
form.reset();
}
});
view! {
<Card title="Nouvelle mesure" icon=IconName::Plus>
<ActionForm action=add node_ref=form attr:class="flex flex-col gap-4">
<Show when=move || succeeded(value).get()>
<SuccessBanner>"Mesure enregistrée."</SuccessBanner>
</Show>
<ErrorBanner message=general_error_of(value) />
<div class="grid grid-cols-2 gap-3">
<Field label="Date" name="date" kind="date" value=today error=field_error_of(value, "date") />
<Field
label="Pluie (mm)"
name="value"
kind="number"
min="1"
max="1000"
step="1"
inputmode="numeric"
placeholder="0"
error=field_error_of(value, "value")
/>
</div>
<SubmitButton pending=add.pending() class="w-full">
<Icon icon=IconName::Check class="size-4" />
"Enregistrer"
</SubmitButton>
</ActionForm>
</Card>
}
}
/// Les 5 dernières mesures. `reload` : signal qui change après chaque ajout.
#[component]
pub fn LastRainfalls(#[prop(into)] reload: Signal<usize>) -> impl IntoView {
let last = Resource::new(move || reload.get(), |_| rainfall::list_rainfalls(5));
view! {
<Card title="Dernières mesures" icon=IconName::List>
<Transition fallback=|| view! { <Loading height="h-40" /> }>
{move || {
last.get()
.map(|result| match result {
Ok(page) if page.items.is_empty() => {
view! { <p class="muted py-4 text-center text-sm">"Aucune mesure pour l'instant."</p> }
.into_any()
}
Ok(page) => {
view! {
<ul class="-my-2 divide-y divide-slate-100 dark:divide-slate-800">
{page
.items
.into_iter()
.map(|r| {
view! {
<li class="flex items-center justify-between gap-3 py-2.5">
<span class="first-letter:uppercase">{format_long_date(&r.date)}</span>
<span class="rounded-full bg-blue-50 px-2.5 py-0.5 text-sm font-semibold text-blue-700 tabular-nums dark:bg-blue-500/10 dark:text-blue-300">
{r.value} " mm"
</span>
</li>
}
})
.collect_view()}
</ul>
}
.into_any()
}
Err(e) => view! { <ErrorBanner message=Some(error_message(&e)) /> }.into_any(),
})
}}
</Transition>
<A
href="/pluviometrie/mesures"
attr:class="mt-4 flex items-center justify-center gap-1.5 rounded-lg border border-slate-200 py-2 text-sm font-medium text-slate-600 transition hover:bg-slate-50 hover:text-slate-900 dark:border-slate-700 dark:text-slate-300 dark:hover:bg-slate-800 dark:hover:text-white"
>
"Toutes les mesures"
<Icon icon=IconName::ArrowRight class="size-4" />
</A>
</Card>
}
}
/// Chiffres clés et comparaison mois par mois avec l'an dernier (page d'accueil).
#[component]
pub fn YearOverview(#[prop(into)] reload: Signal<usize>) -> impl IntoView {
let summary = Resource::new(move || reload.get(), |_| rainfall::last_months());
let last = Resource::new(move || reload.get(), |_| rainfall::list_rainfalls(1));
view! {
<Transition fallback=|| {
view! {
<div class="grid gap-4 sm:grid-cols-3">
<Loading height="h-28" />
<Loading height="h-28" />
<Loading height="h-28" />
</div>
<Loading height="h-80" />
}
}>
{move || {
let last = last.get().and_then(Result::ok).and_then(|page| page.items.into_iter().next());
summary
.get()
.map(|result| match result {
Ok(summary) => view! { <Overview summary last /> }.into_any(),
Err(e) => view! { <ErrorBanner message=Some(error_message(&e)) /> }.into_any(),
})
}}
</Transition>
}
}
#[component]
fn Overview(summary: MonthlySummary, last: Option<rainfall::Rainfall>) -> impl IntoView {
let year = summary.current_year;
let month = rainfall::today().month();
let this_month = summary.rows.iter().find(|r| r.month == month).cloned();
let difference = summary.total_current - summary.total_previous_to_date;
let year_detail = format!(
"{} mm à la même date en {} ({}{})",
format_number(summary.total_previous_to_date),
year - 1,
if difference >= 0 { "+" } else { "" },
format_number(difference),
);
let series = vec![
Series {
name: year.to_string(),
color: "bg-chart-1",
},
Series {
name: (year - 1).to_string(),
color: "bg-chart-2",
},
];
let columns = summary
.rows
.iter()
.map(|row| Column {
label: month_short(row.month).to_string(),
title: Some(row.label.clone()),
values: vec![row.current, Some(row.previous)],
})
.collect::<Vec<_>>();
view! {
<div class="grid grid-cols-2 gap-3 sm:grid-cols-3 sm:gap-4">
<div class="col-span-2 sm:col-span-1">
<StatTile
label=format!("Cumul {year}")
value=format_number(summary.total_current)
unit="mm"
detail=year_detail
icon=IconName::Droplet
/>
</div>
<StatTile
label=format!("{} {year}", month_name(month))
value=format_number(this_month.as_ref().and_then(|r| r.current).unwrap_or(0))
unit="mm"
detail=format!(
"{} mm en {} {}",
format_number(this_month.map(|r| r.previous).unwrap_or(0)),
month_name(month).to_lowercase(),
year - 1,
)
icon=IconName::Calendar
/>
{match last {
Some(last) => {
view! {
<StatTile
label="Dernière mesure"
value=last.value.to_string()
unit="mm"
detail=format_long_date(&last.date)
icon=IconName::CloudRain
/>
}
.into_any()
}
None => {
view! {
<StatTile label="Dernière mesure" value="—" detail="Aucune mesure" icon=IconName::CloudRain />
}
.into_any()
}
}}
</div>
<Card title="Mois par mois" icon=IconName::CloudRain>
<ColumnChart series columns />
<details class="group mt-4 border-t border-slate-100 pt-3 dark:border-slate-800">
<summary class="muted flex cursor-pointer list-none items-center gap-1 text-sm font-medium hover:text-slate-900 dark:hover:text-white">
<Icon icon=IconName::ChevronDown class="size-4 transition-transform group-open:rotate-180" />
"Voir le tableau"
</summary>
<MonthTable summary />
</details>
</Card>
}
}
#[component]
fn MonthTable(summary: MonthlySummary) -> impl IntoView {
let year = summary.current_year;
view! {
<table class="mt-3 w-full text-sm tabular-nums">
<thead>
<tr class="muted border-b border-slate-200 text-left dark:border-slate-700">
<th class="py-2 font-medium">"Mois"</th>
<th class="py-2 text-right font-medium">{year}</th>
<th class="py-2 text-right font-medium">{year - 1}</th>
</tr>
</thead>
<tbody class="divide-y divide-slate-100 dark:divide-slate-800">
{summary
.rows
.into_iter()
.map(|row| {
view! {
<tr>
<td class="py-1.5">{row.label}</td>
<td class="py-1.5 text-right">{row.current.map(|v| format!("{v} mm"))}</td>
<td class="py-1.5 text-right">{row.previous} " mm"</td>
</tr>
}
})
.collect_view()}
</tbody>
<tfoot>
<tr class="border-t border-slate-200 font-semibold dark:border-slate-700">
<td class="py-2">"Total"</td>
<td class="py-2 text-right">{format_number(summary.total_current)} " mm"</td>
<td class="py-2 text-right">{format_number(summary.total_previous)} " mm"</td>
</tr>
</tfoot>
</table>
{summary
.first_year
.map(|first| view! { <p class="muted mt-2 text-right text-xs">"Mesures depuis " {first}</p> })}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn numbers_are_grouped_by_thousands() {
assert_eq!(format_number(0), "0");
assert_eq!(format_number(999), "999");
assert_eq!(format_number(1281), "1\u{202f}281");
assert_eq!(format_number(-1234567), "-1\u{202f}234\u{202f}567");
}
#[test]
fn long_dates_are_french() {
assert_eq!(format_long_date("2026-10-14"), "mercredi 14 octobre");
}
}
+72
View File
@@ -0,0 +1,72 @@
//! Erreurs des server functions, rattachées ou non à un champ de formulaire.
//!
//! Une erreur de champ est transportée dans le message de `ServerFnError` sous la
//! forme `champ` + séparateur + `message`, pour être affichée sous le bon `<input>`
//! (l'équivalent des erreurs 422 de Laravel).
use leptos::prelude::*;
const SEPARATOR: char = '\u{1f}';
/// Erreur de validation attachée au champ `field`.
pub fn field_error(field: &str, message: impl Into<String>) -> ServerFnError {
ServerFnError::new(format!("{field}{SEPARATOR}{}", message.into()))
}
fn split(error: &ServerFnError) -> (Option<&str>, String) {
match error {
ServerFnError::ServerError(message) => match message.split_once(SEPARATOR) {
Some((field, message)) => (Some(field), message.to_string()),
None => (None, message.clone()),
},
_ => (
None,
"Impossible de joindre le serveur. Réessayez.".to_string(),
),
}
}
/// Message lisible de l'erreur, qu'elle soit liée à un champ ou non.
pub fn error_message(error: &ServerFnError) -> String {
split(error).1
}
/// Message de l'erreur si elle concerne le champ `field`.
pub fn error_for_field(error: &ServerFnError, field: &str) -> Option<String> {
match split(error) {
(Some(f), message) if f == field => Some(message),
_ => None,
}
}
/// Message de l'erreur si elle ne concerne aucun champ en particulier.
pub fn general_error(error: &ServerFnError) -> Option<String> {
match split(error) {
(None, message) => Some(message),
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn field_errors_round_trip() {
let error = field_error("email", "Adresse invalide.");
assert_eq!(
error_for_field(&error, "email").as_deref(),
Some("Adresse invalide.")
);
assert_eq!(error_for_field(&error, "password"), None);
assert_eq!(general_error(&error), None);
assert_eq!(error_message(&error), "Adresse invalide.");
}
#[test]
fn general_errors_are_not_attached_to_fields() {
let error = ServerFnError::new("Boom");
assert_eq!(error_for_field(&error, "email"), None);
assert_eq!(general_error(&error).as_deref(), Some("Boom"));
}
}
+101
View File
@@ -0,0 +1,101 @@
//! Icônes SVG au trait (dessins de Lucide, licence ISC), en ligne pour éviter toute requête.
use leptos::prelude::*;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum IconName {
Home,
CloudRain,
CloudSun,
User,
Plus,
Trash,
Pencil,
Check,
X,
LogOut,
MapPin,
Droplet,
List,
Sun,
Moon,
Monitor,
ArrowRight,
ChevronDown,
Calendar,
}
impl IconName {
fn paths(self) -> &'static str {
match self {
IconName::Home => {
r#"<path d="M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8"/><path d="M3 10a2 2 0 0 1 .709-1.528l7-5.999a2 2 0 0 1 2.582 0l7 5.999A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/>"#
}
IconName::CloudRain => {
r#"<path d="M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242"/><path d="M16 14v6"/><path d="M8 14v6"/><path d="M12 16v6"/>"#
}
IconName::CloudSun => {
r#"<path d="M12 2v2"/><path d="m4.93 4.93 1.41 1.41"/><path d="M20 12h2"/><path d="m19.07 4.93-1.41 1.41"/><path d="M15.947 12.65a4 4 0 0 0-5.925-4.128"/><path d="M13 22H7a5 5 0 1 1 4.9-6H13a3 3 0 0 1 0 6Z"/>"#
}
IconName::User => {
r#"<path d="M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/>"#
}
IconName::Plus => r#"<path d="M5 12h14"/><path d="M12 5v14"/>"#,
IconName::Trash => {
r#"<path d="M3 6h18"/><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"/><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"/>"#
}
IconName::Pencil => {
r#"<path d="M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z"/>"#
}
IconName::Check => r#"<path d="M20 6 9 17l-5-5"/>"#,
IconName::X => r#"<path d="M18 6 6 18"/><path d="m6 6 12 12"/>"#,
IconName::LogOut => {
r#"<path d="m16 17 5-5-5-5"/><path d="M21 12H9"/><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/>"#
}
IconName::MapPin => {
r#"<path d="M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0"/><circle cx="12" cy="10" r="3"/>"#
}
IconName::Droplet => {
r#"<path d="M12 22a7 7 0 0 0 7-7c0-2-1-3.9-3-5.5s-3.5-4-4-6.5c-.5 2.5-2 4.9-4 6.5C6 11.1 5 13 5 15a7 7 0 0 0 7 7z"/>"#
}
IconName::List => {
r#"<path d="M3 6h.01"/><path d="M3 12h.01"/><path d="M3 18h.01"/><path d="M8 6h13"/><path d="M8 12h13"/><path d="M8 18h13"/>"#
}
IconName::Sun => {
r#"<circle cx="12" cy="12" r="4"/><path d="M12 2v2"/><path d="M12 20v2"/><path d="m4.93 4.93 1.41 1.41"/><path d="m17.66 17.66 1.41 1.41"/><path d="M2 12h2"/><path d="M20 12h2"/><path d="m6.34 17.66-1.41 1.41"/><path d="m19.07 4.93-1.41 1.41"/>"#
}
IconName::Moon => r#"<path d="M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z"/>"#,
IconName::Monitor => {
r#"<rect width="20" height="14" x="2" y="3" rx="2"/><path d="M8 21h8"/><path d="M12 17v4"/>"#
}
IconName::ArrowRight => r#"<path d="M5 12h14"/><path d="m12 5 7 7-7 7"/>"#,
IconName::ChevronDown => r#"<path d="m6 9 6 6 6-6"/>"#,
IconName::Calendar => {
r#"<path d="M8 2v4"/><path d="M16 2v4"/><rect width="18" height="18" x="3" y="4" rx="2"/><path d="M3 10h18"/>"#
}
}
}
}
/// Icône décorative (masquée aux lecteurs d'écran : le texte voisin porte le sens).
#[component]
pub fn Icon(icon: IconName, #[prop(optional, into)] class: String) -> impl IntoView {
let class = if class.is_empty() {
"size-5 shrink-0".to_string()
} else {
format!("shrink-0 {class}")
};
view! {
<svg
class=class
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
inner_html=icon.paths()
></svg>
}
}
+27
View File
@@ -0,0 +1,27 @@
// Les vues Leptos produisent des types très imbriqués (build WASM en release).
#![recursion_limit = "256"]
pub mod app;
pub mod auth;
pub mod chart;
pub mod components;
pub mod errors;
pub mod icons;
pub mod location;
#[cfg(feature = "ssr")]
pub mod mail;
pub mod pages;
pub mod profile;
pub mod rainfall;
#[cfg(feature = "ssr")]
pub mod server;
pub mod ui;
pub mod weather;
#[cfg(feature = "hydrate")]
#[wasm_bindgen::prelude::wasm_bindgen]
pub fn hydrate() {
use crate::app::*;
console_error_panic_hook::set_once();
leptos::mount::hydrate_body(App);
}
+101
View File
@@ -0,0 +1,101 @@
//! Emplacement de l'utilisateur, utilisé pour les prévisions météo.
use leptos::prelude::*;
use serde::{Deserialize, Serialize};
use crate::errors::field_error;
#[cfg(feature = "ssr")]
use crate::server;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Location {
pub id: i64,
pub latitude: f64,
pub longitude: f64,
}
/// Lit une coordonnée saisie (virgule acceptée) et vérifie ses bornes.
/// Arrondie à 5 décimales (≈ 1 m), comme la règle `decimal:3,5` de Laravel.
pub fn parse_coordinate(field: &str, value: &str, bound: f64) -> Result<f64, ServerFnError> {
let number: f64 = value
.trim()
.replace(',', ".")
.parse()
.map_err(|_| field_error(field, "Veuillez saisir un nombre."))?;
if !number.is_finite() || number.abs() > bound {
return Err(field_error(
field,
format!("La valeur doit être comprise entre -{bound} et {bound}."),
));
}
Ok((number * 100_000.0).round() / 100_000.0)
}
#[cfg(feature = "ssr")]
pub async fn user_locations(
pool: &sqlx::SqlitePool,
user_id: i64,
) -> Result<Vec<Location>, ServerFnError> {
let rows = sqlx::query_as::<_, (i64, f64, f64)>(
"SELECT id, latitude, longitude FROM locations WHERE user_id = ?1 ORDER BY id",
)
.bind(user_id)
.fetch_all(pool)
.await
.map_err(server::internal_error)?;
Ok(rows
.into_iter()
.map(|(id, latitude, longitude)| Location {
id,
latitude,
longitude,
})
.collect())
}
/// Enregistre l'emplacement de l'utilisateur (remplace le précédent s'il y en avait un).
#[server]
pub async fn save_location(latitude: String, longitude: String) -> Result<(), ServerFnError> {
let user_id = server::require_user_id().await?;
let latitude = parse_coordinate("latitude", &latitude, 90.0)?;
let longitude = parse_coordinate("longitude", &longitude, 180.0)?;
let pool = server::pool()?;
let mut tx = pool.begin().await.map_err(server::internal_error)?;
sqlx::query("DELETE FROM locations WHERE user_id = ?1")
.bind(user_id)
.execute(&mut *tx)
.await
.map_err(server::internal_error)?;
sqlx::query("INSERT INTO locations (user_id, latitude, longitude) VALUES (?1, ?2, ?3)")
.bind(user_id)
.bind(latitude)
.bind(longitude)
.execute(&mut *tx)
.await
.map_err(server::internal_error)?;
tx.commit().await.map_err(server::internal_error)?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn coordinates_are_parsed_and_rounded() {
assert_eq!(
parse_coordinate("latitude", "45.123456", 90.0).unwrap(),
45.12346
);
assert_eq!(parse_coordinate("latitude", " -1,5 ", 90.0).unwrap(), -1.5);
}
#[test]
fn out_of_range_coordinates_are_rejected() {
assert!(parse_coordinate("latitude", "91", 90.0).is_err());
assert!(parse_coordinate("longitude", "-180.1", 180.0).is_err());
assert!(parse_coordinate("longitude", "abc", 180.0).is_err());
assert!(parse_coordinate("longitude", "NaN", 180.0).is_err());
}
}
+65
View File
@@ -0,0 +1,65 @@
//! Envoi des e-mails (serveur uniquement).
use lettre::{
AsyncSmtpTransport, AsyncTransport, Message, Tokio1Executor, message::MultiPart,
transport::smtp::authentication::Credentials,
};
use crate::server::Config;
/// Envoie le lien de réinitialisation du mot de passe (texte du mail de lara-bermite).
///
/// Sans SMTP configuré (développement), le lien est seulement écrit dans les logs.
pub async fn send_reset_link(config: &Config, to: &str, link: &str) -> Result<(), String> {
let Some(smtp) = &config.smtp else {
leptos::logging::log!("SMTP non configuré — lien de réinitialisation pour {to} : {link}");
return Ok(());
};
let text = format!(
"Créer un nouveau mot de passe\n\n\
Veuillez suivre ce lien pour réinitialiser votre mot de passe (valable 24 heures) :\n\
{link}\n\n\
Si vous n'êtes pas à l'origine de cette demande, ignorez ce message.\n\n\
Merci,\nBermite\n"
);
let html = format!(
r#"<h1>Créer un nouveau mot de passe</h1>
<p>Veuillez cliquer sur le bouton ci-dessous pour réinitialiser votre mot de passe (valable 24 heures).</p>
<p><a href="{link}" style="display:inline-block;padding:8px 16px;background:#1d4ed8;color:#fff;border-radius:4px;text-decoration:none">Réinitialisation de mot de passe</a></p>
<p>Si le bouton ne fonctionne pas, essayez le lien suivant :<br>{link}</p>
<p>Merci,<br>Bermite</p>"#
);
let message = Message::builder()
.from(
config
.mail_from
.parse()
.map_err(|e| format!("MAIL_FROM invalide : {e}"))?,
)
.to(to
.parse()
.map_err(|e| format!("destinataire invalide : {e}"))?)
.subject("Bermite réinitialisation du mot de passe")
.multipart(MultiPart::alternative_plain_html(text, html))
.map_err(|e| e.to_string())?;
// Port 465 : TLS implicite (OVH) ; sinon STARTTLS.
let builder = if smtp.port == 465 {
AsyncSmtpTransport::<Tokio1Executor>::relay(&smtp.host)
} else {
AsyncSmtpTransport::<Tokio1Executor>::starttls_relay(&smtp.host)
}
.map_err(|e| e.to_string())?;
let transport = builder
.port(smtp.port)
.credentials(Credentials::new(
smtp.username.clone(),
smtp.password.clone(),
))
.build();
transport.send(message).await.map_err(|e| e.to_string())?;
Ok(())
}
+93 -2
View File
@@ -1,3 +1,94 @@
fn main() { #[cfg(feature = "ssr")]
println!("Hello, world!"); #[tokio::main]
async fn main() {
use axum::Router;
use bermite_rs::{
app::{App, shell},
server::{self, AppContext, Config},
};
use leptos::{logging::log, prelude::*};
use leptos_axum::{LeptosRoutes, generate_route_list};
use std::sync::Arc;
use tower_sessions::{
Expiry, SessionManagerLayer,
cookie::{SameSite, time::Duration},
session_store::ExpiredDeletion,
};
use tower_sessions_sqlx_store::SqliteStore;
// Le fichier .env est facultatif (en production, les variables peuvent venir de systemd).
let _ = dotenvy::dotenv();
let database_url = std::env::var("DATABASE_URL").unwrap_or_else(|_| "sqlite:bermite.db".into());
let pool = server::connect_db(&database_url)
.await
.expect("impossible d'ouvrir la base de données");
// Les sessions sont stockées en base : elles survivent à un redémarrage du serveur.
let session_store = SqliteStore::new(pool.clone());
session_store
.migrate()
.await
.expect("impossible de créer la table des sessions");
tokio::spawn(
session_store
.clone()
.continuously_delete_expired(tokio::time::Duration::from_secs(60 * 60)),
);
let conf = get_configuration(None).unwrap();
let addr = conf.leptos_options.site_addr;
let leptos_options = conf.leptos_options;
let is_prod = matches!(leptos_options.env, Env::PROD);
let config = Config::from_env();
if config.open_weather_map_api_key.is_none() {
log!("⚠ OPEN_WEATHER_MAP_API_KEY absente : la page Météo renverra une erreur");
}
let context = AppContext {
pool,
config: Arc::new(config),
http: reqwest::Client::builder()
.timeout(std::time::Duration::from_secs(10))
.build()
.expect("client HTTP"),
weather_cache: Default::default(),
};
let session_layer = SessionManagerLayer::new(session_store)
// Cookie `Secure` (HTTPS uniquement) en production. `HttpOnly` est activé par défaut.
.with_secure(is_prod)
// `Lax` : le cookie n'est pas envoyé sur les requêtes POST venant d'un autre site (CSRF).
.with_same_site(SameSite::Lax)
// Comme la SESSION_LIFETIME de lara-bermite : une semaine d'inactivité.
.with_expiry(Expiry::OnInactivity(Duration::days(7)));
let routes = generate_route_list(App);
let app = Router::new()
.leptos_routes_with_context(
&leptos_options,
routes,
{
let context = context.clone();
move || provide_context(context.clone())
},
{
let leptos_options = leptos_options.clone();
move || shell(leptos_options.clone())
},
)
.fallback(leptos_axum::file_and_error_handler(shell))
.layer(session_layer)
.with_state(leptos_options);
log!("listening on http://{}", &addr);
let listener = tokio::net::TcpListener::bind(&addr).await.unwrap();
axum::serve(listener, app.into_make_service())
.await
.unwrap();
}
#[cfg(not(feature = "ssr"))]
pub fn main() {
// Pas de `main` côté client : voir `hydrate()` dans lib.rs.
} }
+210
View File
@@ -0,0 +1,210 @@
//! Connexion, inscription, mot de passe oublié et réinitialisation.
use leptos::prelude::*;
use leptos_router::{components::A, hooks::use_params_map};
use crate::{
auth::{self, ForgotPassword, Login, Register, ResetPassword},
ui::{
ErrorBanner, Field, Loading, SubmitButton, SuccessBanner, field_error_of, general_error_of,
succeeded,
},
};
/// Écran centré des formulaires d'authentification : logo, titre, sous-titre, carte.
#[component]
fn AuthCard(title: &'static str, subtitle: &'static str, children: Children) -> impl IntoView {
view! {
<div class="flex min-h-[calc(100vh-4rem)] items-start justify-center px-4 py-10 sm:items-center">
<div class="w-full max-w-sm">
<div class="mb-6 flex flex-col items-center gap-3 text-center">
<img src="/favicon.svg" alt="" width="48" height="48" class="size-12" />
<div>
<h1 class="text-2xl font-bold tracking-tight">{title}</h1>
<p class="muted mt-1 text-sm">{subtitle}</p>
</div>
</div>
<div class="surface p-6">{children()}</div>
</div>
</div>
}
}
#[component]
pub fn LoginPage(login: ServerAction<Login>) -> impl IntoView {
let value = login.value();
view! {
<AuthCard title="Connexion" subtitle="Suivez votre pluviométrie et la météo">
<ActionForm action=login attr:class="flex flex-col gap-4">
<ErrorBanner message=general_error_of(value) />
<Field
label="E-mail"
name="email"
kind="email"
placeholder="vous@exemple.fr"
autocomplete="username"
autofocus=true
error=field_error_of(value, "email")
/>
<Field
label="Mot de passe"
name="password"
kind="password"
placeholder="******"
autocomplete="current-password"
error=field_error_of(value, "password")
/>
<SubmitButton pending=login.pending() class="mt-1 w-full">
"Valider"
</SubmitButton>
<A
href="/mot-de-passe-oubliee"
attr:class="text-center text-sm font-medium text-blue-600 hover:underline dark:text-blue-400"
>
"Mot de passe oublié ?"
</A>
</ActionForm>
</AuthCard>
}
}
#[component]
pub fn RegisterPage(register: ServerAction<Register>) -> impl IntoView {
let open = Resource::new(|| (), |_| auth::registration_open());
let value = register.value();
view! {
<Suspense fallback=|| view! { <div class="mx-auto max-w-sm px-4 py-10"><Loading height="h-80" /></div> }>
{move || {
open.get()
.map(|open| {
if !matches!(open, Ok(true)) {
return view! {
<AuthCard title="Inscriptions fermées" subtitle="Un compte est nécessaire, mais les inscriptions ne sont pas ouvertes.">
<A href="/connexion" attr:class="btn-primary w-full">"Se connecter"</A>
</AuthCard>
}
.into_any();
}
view! {
<AuthCard title="Créer un compte" subtitle="Quelques secondes suffisent">
<ActionForm action=register attr:class="flex flex-col gap-4">
<ErrorBanner message=general_error_of(value) />
<Field
label="Nom"
name="name"
autocomplete="name"
autofocus=true
error=field_error_of(value, "name")
/>
<Field
label="E-mail"
name="email"
kind="email"
autocomplete="email"
error=field_error_of(value, "email")
/>
<Field
label="Mot de passe"
name="password"
kind="password"
autocomplete="new-password"
error=field_error_of(value, "password")
/>
<Field
label="Confirmation du mot de passe"
name="password_confirmation"
kind="password"
autocomplete="new-password"
error=field_error_of(value, "password_confirmation")
/>
<SubmitButton pending=register.pending() class="mt-1 w-full">
"Valider"
</SubmitButton>
</ActionForm>
</AuthCard>
}
.into_any()
})
}}
</Suspense>
}
}
#[component]
pub fn ForgotPasswordPage() -> impl IntoView {
let forgot = ServerAction::<ForgotPassword>::new();
let value = forgot.value();
view! {
<AuthCard title="Mot de passe oublié" subtitle="Recevez un lien de réinitialisation par e-mail">
<ActionForm action=forgot attr:class="flex flex-col gap-4">
<Show when=move || succeeded(value).get()>
<SuccessBanner>
"Si un compte correspond à cette adresse, un e-mail vous a été envoyé pour modifier le mot de passe."
</SuccessBanner>
</Show>
<ErrorBanner message=general_error_of(value) />
<Field
label="E-mail"
name="email"
kind="email"
placeholder="vous@exemple.fr"
autocomplete="email"
autofocus=true
error=field_error_of(value, "email")
/>
<SubmitButton pending=forgot.pending() class="mt-1 w-full">
"Valider"
</SubmitButton>
<A
href="/connexion"
attr:class="text-center text-sm font-medium text-blue-600 hover:underline dark:text-blue-400"
>
"Retour à la connexion"
</A>
</ActionForm>
</AuthCard>
}
}
#[component]
pub fn ResetPasswordPage(reset: ServerAction<ResetPassword>) -> impl IntoView {
let params = use_params_map();
let token = move || params.with(|p| p.get("token").unwrap_or_default());
let value = reset.value();
view! {
<AuthCard title="Nouveau mot de passe" subtitle="Au moins 8 caractères, dont une majuscule, une minuscule et un chiffre">
<ActionForm action=reset attr:class="flex flex-col gap-4">
<ErrorBanner message=general_error_of(value) />
<input type="hidden" name="token" value=token />
<Field
label="E-mail"
name="email"
kind="email"
placeholder="vous@exemple.fr"
autocomplete="username"
autofocus=true
error=field_error_of(value, "email")
/>
<Field
label="Mot de passe"
name="password"
kind="password"
placeholder="******"
autocomplete="new-password"
error=field_error_of(value, "password")
/>
<Field
label="Confirmation du mot de passe"
name="password_confirmation"
kind="password"
placeholder="******"
autocomplete="new-password"
error=field_error_of(value, "password_confirmation")
/>
<SubmitButton pending=reset.pending() class="mt-1 w-full">
"Valider"
</SubmitButton>
</ActionForm>
</AuthCard>
}
}
+29
View File
@@ -0,0 +1,29 @@
//! Accueil : chiffres clés, comparaison avec l'an dernier et saisie rapide d'une mesure.
use leptos::prelude::*;
use crate::{
app::Protected,
components::{AddRainfallForm, LastRainfalls, YearOverview},
rainfall::AddRainfall,
ui::Page,
};
#[component]
pub fn HomePage() -> impl IntoView {
view! {
<Protected render=|user| {
let add = ServerAction::<AddRainfall>::new();
let reload = Signal::derive(move || add.version().get());
view! {
<Page title=format!("Bonjour {}", user.name) subtitle="Vos précipitations en un coup d'œil">
<YearOverview reload />
<div class="grid gap-5 md:grid-cols-2 md:items-start">
<AddRainfallForm add />
<LastRainfalls reload />
</div>
</Page>
}
} />
}
}
+5
View File
@@ -0,0 +1,5 @@
pub mod auth;
pub mod home;
pub mod profile;
pub mod rainfall;
pub mod weather;
+217
View File
@@ -0,0 +1,217 @@
//! Profil : identité, déconnexion, emplacement météo et apparence.
use leptos::{html, prelude::*};
use crate::{
app::{CurrentUser, Protected},
auth::Logout,
icons::{Icon, IconName},
location::SaveLocation,
profile::{Theme, UpdateTheme},
ui::{
Card, ErrorBanner, Field, Page, SubmitButton, field_error_of, general_error_of, succeeded,
},
};
#[component]
pub fn ProfilePage(
logout: ServerAction<Logout>,
save_location: ServerAction<SaveLocation>,
update_theme: ServerAction<UpdateTheme>,
) -> impl IntoView {
view! {
<Protected render=move |_| {
view! { <Profile logout save_location update_theme /> }
} />
}
}
#[component]
fn Profile(
logout: ServerAction<Logout>,
save_location: ServerAction<SaveLocation>,
update_theme: ServerAction<UpdateTheme>,
) -> impl IntoView {
// Ressource globale : rechargée après l'enregistrement d'un emplacement ou d'un thème.
let CurrentUser(user) = expect_context();
let user = move || user.get().and_then(Result::ok).flatten();
let editing_location = RwSignal::new(false);
Effect::new(move |_| {
if succeeded(save_location.value()).get() {
editing_location.set(false);
}
});
view! {
<Page title="Profil">
<Transition>
{move || {
user()
.map(|user| {
let initial = user.name.chars().next().map(|c| c.to_uppercase().to_string()).unwrap_or_default();
let location = user.locations.first().cloned();
let has_location = location.is_some();
let latitude = location.as_ref().map(|l| l.latitude.to_string()).unwrap_or_default();
let longitude = location.as_ref().map(|l| l.longitude.to_string()).unwrap_or_default();
view! {
<Card>
<div class="flex flex-wrap items-center gap-4">
<span class="flex size-14 items-center justify-center rounded-full bg-gradient-to-br from-blue-500 to-indigo-600 text-xl font-semibold text-white">
{initial}
</span>
<div class="min-w-0 flex-1">
<div class="truncate text-lg font-semibold">{user.name.clone()}</div>
<div class="muted truncate">{user.email.clone()}</div>
</div>
<ActionForm action=logout>
<button
type="submit"
class="btn-ghost border border-slate-200 hover:!border-red-200 hover:!bg-red-50 hover:!text-red-600 dark:border-slate-700 dark:hover:!border-red-500/30 dark:hover:!bg-red-500/10 dark:hover:!text-red-400"
>
<Icon icon=IconName::LogOut class="size-4" />
"Se déconnecter"
</button>
</ActionForm>
</div>
</Card>
<Card title="Emplacement météo" icon=IconName::MapPin>
{location
.map(|location| {
view! {
<div class="flex flex-wrap items-center justify-between gap-3">
<dl class="flex gap-6 tabular-nums">
<div>
<dt class="muted text-xs font-medium">"Latitude"</dt>
<dd class="font-semibold">{location.latitude}</dd>
</div>
<div>
<dt class="muted text-xs font-medium">"Longitude"</dt>
<dd class="font-semibold">{location.longitude}</dd>
</div>
</dl>
<button
type="button"
class="btn-ghost"
on:click=move |_| editing_location.update(|e| *e = !*e)
>
<Icon icon=IconName::Pencil class="size-4" />
"Modifier"
</button>
</div>
}
})}
<Show when=move || !has_location || editing_location.get()>
<LocationForm
save_location
latitude=latitude.clone()
longitude=longitude.clone()
/>
</Show>
</Card>
<Card title="Apparence" icon=IconName::Sun>
<ThemePicker update_theme current=user.theme />
</Card>
}
})
}}
</Transition>
</Page>
}
}
#[component]
fn LocationForm(
save_location: ServerAction<SaveLocation>,
latitude: String,
longitude: String,
) -> impl IntoView {
let value = save_location.value();
view! {
<ActionForm action=save_location attr:class="mt-4 flex flex-col gap-3 border-t border-slate-100 pt-4 first:mt-0 first:border-0 first:pt-0 dark:border-slate-800">
<p class="muted text-sm">
"Coordonnées en degrés décimaux, par exemple celles affichées par un clic droit dans une carte en ligne."
</p>
<ErrorBanner message=general_error_of(value) />
<div class="grid gap-3 sm:grid-cols-[1fr_1fr_auto] sm:items-start">
<Field
label="Latitude"
name="latitude"
kind="number"
step="0.00001"
min="-90"
max="90"
inputmode="decimal"
placeholder="45.76404"
value=latitude
error=field_error_of(value, "latitude")
/>
<Field
label="Longitude"
name="longitude"
kind="number"
step="0.00001"
min="-180"
max="180"
inputmode="decimal"
placeholder="4.83566"
value=longitude
error=field_error_of(value, "longitude")
/>
<SubmitButton pending=save_location.pending() class="sm:mt-[26px]">
"Enregistrer"
</SubmitButton>
</div>
</ActionForm>
}
}
/// Choix du thème : trois tuiles ; le choix est enregistré dès le clic.
#[component]
fn ThemePicker(update_theme: ServerAction<UpdateTheme>, current: Theme) -> impl IntoView {
let form = NodeRef::<html::Form>::new();
view! {
<ActionForm action=update_theme node_ref=form>
<fieldset class="grid grid-cols-3 gap-3">
<legend class="sr-only">"Thème"</legend>
{Theme::ALL
.into_iter()
.map(|theme| {
let icon = match theme {
Theme::System => IconName::Monitor,
Theme::Light => IconName::Sun,
Theme::Dark => IconName::Moon,
};
view! {
<label class="flex cursor-pointer flex-col items-center gap-2 rounded-xl border-2 border-slate-200 p-3 text-sm font-medium transition hover:border-slate-300 has-[:checked]:border-blue-600 has-[:checked]:bg-blue-50 has-[:checked]:text-blue-700 has-[:focus-visible]:outline-2 has-[:focus-visible]:outline-blue-600 dark:border-slate-700 dark:hover:border-slate-600 dark:has-[:checked]:border-blue-500 dark:has-[:checked]:bg-blue-500/10 dark:has-[:checked]:text-blue-300">
<input
class="sr-only"
type="radio"
name="theme"
value=theme.as_str()
checked=theme == current
on:change=move |_| {
if let Some(form) = form.get() {
let _ = form.request_submit();
}
}
/>
<Icon icon class="size-6" />
{theme.label()}
</label>
}
})
.collect_view()}
</fieldset>
// Sans JavaScript, le choix s'enregistre avec ce bouton.
<noscript>
<button type="submit" class="btn-primary mt-3">"Enregistrer"</button>
</noscript>
</ActionForm>
<div class="mt-3 empty:hidden">
<ErrorBanner message=general_error_of(update_theme.value()) />
</div>
}
}
+474
View File
@@ -0,0 +1,474 @@
//! Pages Pluviométrie (graphique) et liste des mesures.
use chrono::{Datelike, Months, NaiveDate};
use leptos::prelude::*;
use leptos_router::components::A;
use crate::{
app::Protected,
chart::{Column, ColumnChart, Series},
components::{AddRainfallForm, LastRainfalls, format_long_date, format_number},
errors::{error_for_field, error_message, general_error},
icons::{Icon, IconName},
rainfall::{
self, AddRainfall, DeleteRainfall, GraphPoint, PAGE_SIZE, Period, Rainfall, UpdateRainfall,
graph::{month_name, month_short},
},
ui::{Card, ErrorBanner, FieldError, Loading, Page, field_error_of, general_error_of},
};
fn iso(date: NaiveDate) -> String {
date.format("%Y-%m-%d").to_string()
}
#[component]
pub fn RainfallGraphPage() -> impl IntoView {
view! { <Protected render=|_| view! { <RainfallGraph /> } /> }
}
/// Raccourcis de période : libellé et (début, regroupement) à partir d'aujourd'hui.
fn presets(today: NaiveDate) -> [(&'static str, NaiveDate, Period); 4] {
[
(
"30 jours",
today.checked_sub_months(Months::new(1)).unwrap_or(today),
Period::Day,
),
(
"12 semaines",
today - chrono::Duration::weeks(12),
Period::Week,
),
(
"12 mois",
today
.checked_sub_months(Months::new(11))
.unwrap_or(today)
.with_day(1)
.unwrap_or(today),
Period::Month,
),
(
"Années",
NaiveDate::from_ymd_opt(today.year() - 9, 1, 1).unwrap_or(today),
Period::Year,
),
]
}
#[component]
fn RainfallGraph() -> impl IntoView {
let add = ServerAction::<AddRainfall>::new();
let reload = Signal::derive(move || add.version().get());
// Par défaut : le dernier mois, jour par jour.
let today = rainfall::today();
let start = RwSignal::new(iso(presets(today)[0].1));
let end = RwSignal::new(iso(today));
let period = RwSignal::new(Period::Day);
let graph = Resource::new(
move || (start.get(), end.get(), period.get(), reload.get()),
|(start, end, period, _)| rainfall::graph_data(start, end, period.as_str().to_string()),
);
let pending = RwSignal::new(false);
let error = move || graph.get().and_then(Result::err);
let field_error = move |field: &'static str| {
Signal::derive(move || error().and_then(|e| error_for_field(&e, field)))
};
let segment = "rounded-md px-3 py-1.5 text-sm font-medium transition cursor-pointer";
let segment_on = "bg-white text-slate-900 shadow-sm dark:bg-slate-700 dark:text-white";
let segment_off =
"text-slate-600 hover:text-slate-900 dark:text-slate-400 dark:hover:text-white";
view! {
<Page title="Pluviométrie" subtitle="Cumuls de pluie sur la période choisie">
<Card>
<div class="flex flex-col gap-4">
// Raccourcis.
<div class="flex flex-wrap gap-2">
{presets(today)
.into_iter()
.map(|(label, from, p)| {
let from = iso(from);
let to = iso(today);
let active = {
let (from, to) = (from.clone(), to.clone());
Memo::new(move |_| start.get() == from && end.get() == to && period.get() == p)
};
view! {
<button
type="button"
aria-pressed=move || active.get().to_string()
class=move || {
if active.get() {
"cursor-pointer rounded-full border border-blue-600 bg-blue-600 px-3 py-1 text-sm font-medium text-white transition"
} else {
"cursor-pointer rounded-full border border-slate-300 px-3 py-1 text-sm font-medium transition hover:bg-slate-100 dark:border-slate-700 dark:hover:bg-slate-800"
}
}
on:click=move |_| {
start.set(from.clone());
end.set(to.clone());
period.set(p);
}
>
{label}
</button>
}
})
.collect_view()}
</div>
<div class="flex flex-col gap-3 md:flex-row md:items-end">
<div class="grid flex-1 grid-cols-2 gap-3 md:max-w-sm">
<label class="flex flex-col gap-1.5 text-sm font-medium text-slate-700 dark:text-slate-300">
"Du"
<input
class="input"
type="date"
prop:value=move || start.get()
on:change=move |ev| start.set(event_target_value(&ev))
/>
</label>
<label class="flex flex-col gap-1.5 text-sm font-medium text-slate-700 dark:text-slate-300">
"Au"
<input
class="input"
type="date"
prop:value=move || end.get()
on:change=move |ev| end.set(event_target_value(&ev))
/>
</label>
</div>
// Regroupement : contrôle segmenté.
<div
class="inline-flex self-start rounded-lg bg-slate-100 p-1 md:self-auto dark:bg-slate-800"
role="radiogroup"
aria-label="Regroupement"
>
{Period::ALL
.into_iter()
.map(|p| {
view! {
<button
type="button"
role="radio"
aria-checked=move || (period.get() == p).to_string()
class=move || {
format!(
"{segment} {}",
if period.get() == p { segment_on } else { segment_off },
)
}
on:click=move |_| period.set(p)
>
{p.label()}
</button>
}
})
.collect_view()}
</div>
</div>
<Transition>
<FieldError message=field_error("start") />
<FieldError message=field_error("end") />
<ErrorBanner message=Signal::derive(move || error().and_then(|e| general_error(&e))) />
</Transition>
</div>
</Card>
<Card>
<Transition fallback=|| view! { <Loading height="h-72" /> } set_pending=pending>
{move || {
graph
.get()
.map(|result| {
let points = result.unwrap_or_default();
let period = period.get_untracked();
view! { <GraphView points period pending /> }
})
}}
</Transition>
</Card>
<div class="grid gap-5 md:grid-cols-2 md:items-start">
<AddRainfallForm add />
<LastRainfalls reload />
</div>
</Page>
}
}
/// Libellé court de l'axe ; le libellé complet reste dans l'infobulle.
fn axis_label(point: &GraphPoint, period: Period) -> String {
let Ok(start) = NaiveDate::parse_from_str(&point.start, "%Y-%m-%d") else {
return point.label.clone();
};
match period {
Period::Day => start.format("%d/%m").to_string(),
Period::Week => format!("S{}", start.iso_week().week()),
Period::Month => format!("{} {}", month_short(start.month()), start.format("%y")),
Period::Year => start.year().to_string(),
}
}
#[component]
fn GraphView(points: Vec<GraphPoint>, period: Period, pending: RwSignal<bool>) -> impl IntoView {
let total: i64 = points.iter().map(|p| p.value).sum();
let days: u32 = points.iter().map(|p| p.days).sum();
let rainy = points.iter().filter(|p| p.value > 0).count();
let columns = points
.iter()
.map(|p| Column {
label: axis_label(p, period),
title: Some(if p.days > 1 {
format!("{} ({} jours)", p.label, p.days)
} else {
p.label.clone()
}),
values: vec![Some(p.value)],
})
.collect::<Vec<_>>();
let series = vec![Series {
name: "Pluie".into(),
color: "bg-chart-1",
}];
view! {
<div class="mb-2 flex flex-wrap items-baseline justify-between gap-2">
<div>
<span class="text-3xl font-semibold tracking-tight">{format_number(total)}</span>
<span class="muted ml-1 font-medium">"mm"</span>
</div>
<p class="muted text-sm">
{format!("sur {days} jour{}", if days > 1 { "s" } else { "" })}
{(points.len() > 1).then(|| format!(" · {rainy} période{} avec pluie", if rainy > 1 { "s" } else { "" }))}
</p>
</div>
<ColumnChart series columns loading=pending />
}
}
/// Regroupe des mesures (déjà triées par date décroissante) par mois : (« Octobre 2026 », mesures).
fn group_by_month(items: Vec<Rainfall>) -> Vec<(String, Vec<Rainfall>)> {
let mut groups: Vec<(String, Vec<Rainfall>)> = Vec::new();
for item in items {
let title = NaiveDate::parse_from_str(&item.date, "%Y-%m-%d")
.map(|d| format!("{} {}", month_name(d.month()), d.year()))
.unwrap_or_default();
match groups.last_mut() {
Some((last, group)) if *last == title => group.push(item),
_ => groups.push((title, vec![item])),
}
}
groups
}
#[component]
pub fn RainfallIndexPage() -> impl IntoView {
view! { <Protected render=|_| view! { <RainfallIndex /> } /> }
}
#[component]
fn RainfallIndex() -> impl IntoView {
let delete = ServerAction::<DeleteRainfall>::new();
let update = ServerAction::<UpdateRainfall>::new();
// Nombre de mesures affichées ; « Afficher plus » en ajoute une page.
let limit = RwSignal::new(PAGE_SIZE);
let editing = RwSignal::new(None::<i64>);
let list = Resource::new(
move || (limit.get(), delete.version().get(), update.version().get()),
|(limit, ..)| rainfall::list_rainfalls(limit),
);
// Referme l'édition une fois la modification enregistrée.
Effect::new(move |_| {
if matches!(update.value().get(), Some(Ok(()))) {
editing.set(None);
}
});
view! {
<Page title="Toutes les mesures">
<A href="/pluviometrie" attr:class="btn-ghost -mt-3 self-start">
<Icon icon=IconName::ArrowRight class="size-4 rotate-180" />
"Retour au graphique"
</A>
<ErrorBanner message=general_error_of(delete.value()) />
<Transition fallback=|| view! { <Loading height="h-96" /> }>
{move || {
list.get()
.map(|result| match result {
Ok(page) if page.items.is_empty() => {
view! {
<Card>
<p class="muted py-8 text-center">"Aucune mesure enregistrée."</p>
</Card>
}
.into_any()
}
Ok(page) => {
let has_more = (page.items.len() as i64) < page.total;
let shown = page.items.len();
view! {
<div class="surface overflow-hidden">
<ul class="divide-y divide-slate-100 dark:divide-slate-800">
{group_by_month(page.items)
.into_iter()
.map(|(title, items)| {
view! {
<li class="muted bg-slate-50 px-4 py-1.5 text-xs font-semibold tracking-wide uppercase dark:bg-slate-800/50">
{title}
</li>
{items
.into_iter()
.map(|rainfall| view! { <RainfallRow rainfall editing update delete /> })
.collect_view()}
}
})
.collect_view()}
</ul>
<div class="flex items-center justify-between gap-3 border-t border-slate-100 px-4 py-3 text-sm dark:border-slate-800">
<span class="muted">{format!("{shown} sur {} mesures", page.total)}</span>
{has_more
.then(|| {
view! {
<button
type="button"
class="btn-ghost"
on:click=move |_| limit.update(|l| *l += PAGE_SIZE)
>
"Afficher plus"
<Icon icon=IconName::ChevronDown class="size-4" />
</button>
}
})}
</div>
</div>
}
.into_any()
}
Err(e) => view! { <ErrorBanner message=Some(error_message(&e)) /> }.into_any(),
})
}}
</Transition>
</Page>
}
}
/// Ligne de la liste : affichage, ou formulaire d'édition en place.
#[component]
fn RainfallRow(
rainfall: Rainfall,
editing: RwSignal<Option<i64>>,
update: ServerAction<UpdateRainfall>,
delete: ServerAction<DeleteRainfall>,
) -> impl IntoView {
let id = rainfall.id;
let is_editing = move || editing.get() == Some(id);
let icon_button = "flex size-9 cursor-pointer items-center justify-center rounded-lg text-slate-500 transition hover:bg-slate-100 hover:text-slate-900 dark:text-slate-400 dark:hover:bg-slate-800 dark:hover:text-white";
view! {
<li class="px-4 py-3">
<Show
when=is_editing
fallback={
let rainfall = rainfall.clone();
move || {
view! {
<div class="flex items-center gap-3">
<div class="min-w-0 flex-1">
<div class="font-medium first-letter:uppercase">{format_long_date(&rainfall.date)}</div>
</div>
<span class="rounded-full bg-blue-50 px-2.5 py-0.5 text-sm font-semibold text-blue-700 tabular-nums dark:bg-blue-500/10 dark:text-blue-300">
{rainfall.value} " mm"
</span>
<div class="flex">
<button
type="button"
class=icon_button
title="Modifier"
aria-label="Modifier"
on:click=move |_| {
update.value().set(None);
editing.set(Some(id));
}
>
<Icon icon=IconName::Pencil class="size-4" />
</button>
<ActionForm action=delete>
<input type="hidden" name="id" value=id />
<button
type="submit"
class=format!("{icon_button} hover:!bg-red-50 hover:!text-red-600 dark:hover:!bg-red-500/10 dark:hover:!text-red-400")
title="Supprimer"
aria-label="Supprimer"
>
<Icon icon=IconName::Trash class="size-4" />
</button>
</ActionForm>
</div>
</div>
}
}
}
>
<EditRainfallForm id date=rainfall.date.clone() amount=rainfall.value update editing />
</Show>
</li>
}
}
#[component]
fn EditRainfallForm(
id: i64,
date: String,
amount: i64,
update: ServerAction<UpdateRainfall>,
editing: RwSignal<Option<i64>>,
) -> impl IntoView {
let value = update.value();
view! {
<ActionForm action=update attr:class="flex flex-wrap items-start gap-2">
<input type="hidden" name="id" value=id />
<div class="flex min-w-36 flex-1 flex-col gap-1">
<input class="input" type="date" name="date" value=date required aria-label="Date" />
<FieldError message=field_error_of(value, "date") />
</div>
<div class="flex w-24 flex-col gap-1">
<input
class="input"
type="number"
name="value"
min="1"
max="1000"
inputmode="numeric"
value=amount
required
aria-label="Pluie en mm"
/>
<FieldError message=field_error_of(value, "value") />
</div>
<div class="flex gap-1">
<button type="submit" class="btn-primary h-[42px]" disabled=move || update.pending().get()>
<Icon icon=IconName::Check class="size-4" />
<span class="sr-only sm:not-sr-only">"Enregistrer"</span>
</button>
<button
type="button"
class="btn-ghost h-[42px]"
title="Annuler"
on:click=move |_| editing.set(None)
>
<Icon icon=IconName::X class="size-4" />
<span class="sr-only">"Annuler"</span>
</button>
</div>
<div class="w-full empty:hidden">
<ErrorBanner message=general_error_of(value) />
</div>
</ActionForm>
}
}
+210
View File
@@ -0,0 +1,210 @@
//! Page Météo : conditions actuelles et prévisions des jours suivants.
use leptos::prelude::*;
use leptos_router::components::A;
use crate::{
app::Protected,
errors::error_message,
icons::{Icon, IconName},
ui::{Card, ErrorBanner, Loading, Page},
weather::{self, CurrentWeather, DayForecast, Slot},
};
/// Les prévisions sont rechargées toutes les 5 minutes tant que la page est ouverte.
const REFRESH_SECONDS: u64 = 5 * 60;
fn icon_src(icon: &str) -> String {
format!("/images/icons/{icon}.svg")
}
fn degrees(value: f64) -> String {
format!("{:.0}°", value)
}
#[component]
pub fn WeatherPage() -> impl IntoView {
view! {
<Protected render=|user| {
if user.has_location() {
view! { <Weather /> }.into_any()
} else {
view! {
<Page title="Météo">
<Card>
<div class="flex flex-col items-center gap-3 py-8 text-center">
<span class="flex size-12 items-center justify-center rounded-full bg-blue-50 text-blue-600 dark:bg-blue-500/10 dark:text-blue-400">
<Icon icon=IconName::MapPin class="size-6" />
</span>
<p class="font-medium">"Aucun emplacement défini"</p>
<p class="muted max-w-sm text-sm">
"Indiquez les coordonnées de votre pluviomètre pour afficher les prévisions."
</p>
<A href="/profile" attr:class="btn-primary mt-2">
"Définir l'emplacement"
</A>
</div>
</Card>
</Page>
}
.into_any()
}
} />
}
}
#[component]
fn Weather() -> impl IntoView {
let tick = RwSignal::new(0u32);
let forecast = Resource::new(move || tick.get(), |_| weather::get_weather());
let pending = RwSignal::new(false);
// Côté client uniquement (les effets ne s'exécutent pas pendant le rendu serveur).
Effect::new(move |_| {
if let Ok(handle) = set_interval_with_handle(
move || tick.update(|t| *t += 1),
std::time::Duration::from_secs(REFRESH_SECONDS),
) {
on_cleanup(move || handle.clear());
}
});
view! {
<Page title="Météo" subtitle="Prévisions à 5 jours pour votre emplacement">
<Transition
fallback=|| {
view! {
<Loading height="h-48" />
<Loading height="h-80" />
}
}
set_pending=pending
>
{move || {
forecast
.get()
.map(|result| match result {
Ok(view) => {
// Bornes de la semaine, pour situer la plage de chaque jour.
let low = view.days.iter().map(|d| d.min).fold(f64::INFINITY, f64::min);
let high = view.days.iter().map(|d| d.max).fold(f64::NEG_INFINITY, f64::max);
view! {
{view.current.map(|current| view! { <CurrentCard current pending /> })}
<section class="surface overflow-hidden">
<h2 class="flex items-center gap-2.5 px-4 pt-4 pb-2 font-semibold sm:px-5">
<span class="flex size-8 items-center justify-center rounded-lg bg-blue-50 text-blue-600 dark:bg-blue-500/10 dark:text-blue-400">
<Icon icon=IconName::Calendar class="size-4" />
</span>
"Prochains jours"
</h2>
<ul class="divide-y divide-slate-100 dark:divide-slate-800">
{view
.days
.into_iter()
.map(|day| view! { <DayRow day low high /> })
.collect_view()}
</ul>
</section>
}
.into_any()
}
Err(e) => view! { <ErrorBanner message=Some(error_message(&e)) /> }.into_any(),
})
}}
</Transition>
</Page>
}
}
#[component]
fn CurrentCard(current: CurrentWeather, pending: RwSignal<bool>) -> impl IntoView {
view! {
<section
class="relative overflow-hidden rounded-2xl bg-gradient-to-br from-sky-500 via-blue-600 to-indigo-700 p-6 text-white shadow-lg sm:p-8"
class=("animate-pulse", move || pending.get())
>
// Halo décoratif.
<div class="pointer-events-none absolute -top-16 -right-16 size-64 rounded-full bg-white/10 blur-2xl"></div>
<div class="relative flex items-center justify-between gap-4">
<div class="flex flex-col gap-1">
<span class="text-sm font-medium text-white/80">"Maintenant"</span>
<span class="text-7xl font-semibold tracking-tighter sm:text-8xl">{degrees(current.temp)}</span>
<span class="text-lg font-medium first-letter:uppercase">{current.description.clone()}</span>
<span class="mt-1 text-sm text-white/80">
"Max. " {degrees(current.temp_max)} " · Min. " {degrees(current.temp_min)}
</span>
</div>
<img
class="size-28 drop-shadow-xl sm:size-40"
src=icon_src(&current.icon)
alt=""
width="160"
height="160"
/>
</div>
</section>
}
}
#[component]
fn DayRow(day: DayForecast, low: f64, high: f64) -> impl IntoView {
let open = RwSignal::new(false);
let slots_id = format!("slots-{}", day.date);
// Position de la plage du jour dans celle de la semaine, en pourcentages.
let span = (high - low).max(1.0);
let left = (day.min - low) / span * 100.0;
let width = ((day.max - day.min) / span * 100.0).max(4.0);
view! {
<li>
<button
type="button"
class="flex w-full cursor-pointer items-center gap-3 px-4 py-3 text-left transition hover:bg-slate-50 sm:gap-4 sm:px-5 dark:hover:bg-slate-800/50"
aria-expanded=move || open.get().to_string()
aria-controls=slots_id.clone()
on:click=move |_| open.update(|o| *o = !*o)
>
<div class="w-24 shrink-0 sm:w-32">
<div class="font-medium first-letter:uppercase">{day.weekday.clone()}</div>
<div class="muted text-xs">{day.date_fr.clone()}</div>
</div>
<img class="size-10 shrink-0" src=icon_src(&day.icon) alt="" width="40" height="40" />
<span class="muted hidden min-w-0 flex-1 truncate text-sm first-letter:uppercase sm:block">
{day.description.clone()}
</span>
<div class="flex flex-1 items-center gap-2 tabular-nums sm:w-56 sm:flex-none">
<span class="muted w-8 text-right text-sm">{degrees(day.min)}</span>
<div class="relative h-1.5 flex-1 rounded-full bg-slate-100 dark:bg-slate-800">
<div
class="absolute inset-y-0 rounded-full bg-gradient-to-r from-sky-400 to-amber-400"
style=format!("left: {left:.1}%; width: {width:.1}%")
></div>
</div>
<span class="w-8 text-sm font-semibold">{degrees(day.max)}</span>
</div>
<span class="text-slate-400 transition-transform" class=("rotate-180", move || open.get())>
<Icon icon=IconName::ChevronDown class="size-4" />
</span>
</button>
<ul
id=slots_id
class="flex gap-2 overflow-x-auto px-4 pb-4 sm:px-5"
class=("hidden", move || !open.get())
>
{day.slots.into_iter().map(|slot| view! { <SlotItem item=slot /> }).collect_view()}
</ul>
</li>
}
}
#[component]
fn SlotItem(item: Slot) -> impl IntoView {
view! {
<li class="flex w-24 shrink-0 flex-col items-center gap-1 rounded-xl bg-slate-50 px-2 py-3 text-center dark:bg-slate-800/60">
<span class="muted text-xs font-medium">{format!("{} h", item.hour)}</span>
<img class="size-10" src=icon_src(&item.icon) alt="" width="40" height="40" />
<span class="font-semibold tabular-nums">{format!("{:.1}°", item.temp)}</span>
<span class="muted line-clamp-2 text-[11px] leading-tight">{item.description}</span>
</li>
}
}
+77
View File
@@ -0,0 +1,77 @@
//! Apparence choisie par l'utilisateur (thème clair / sombre).
use leptos::prelude::*;
use serde::{Deserialize, Serialize};
#[cfg(feature = "ssr")]
use crate::server;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum Theme {
/// Suit le réglage clair / sombre du système.
#[default]
System,
Light,
Dark,
}
impl Theme {
pub const ALL: [Theme; 3] = [Theme::System, Theme::Light, Theme::Dark];
/// Valeur stockée en base et envoyée par le formulaire.
pub fn as_str(self) -> &'static str {
match self {
Theme::System => "system",
Theme::Light => "light",
Theme::Dark => "dark",
}
}
pub fn parse(value: &str) -> Option<Theme> {
Theme::ALL.into_iter().find(|theme| theme.as_str() == value)
}
pub fn label(self) -> &'static str {
match self {
Theme::System => "Automatique",
Theme::Light => "Clair",
Theme::Dark => "Sombre",
}
}
/// Valeur de l'attribut `data-theme` de `<html>` ; `None` pour « automatique ».
pub fn html_attr(self) -> Option<&'static str> {
match self {
Theme::System => None,
other => Some(other.as_str()),
}
}
}
#[server]
pub async fn update_theme(theme: String) -> Result<(), ServerFnError> {
let user_id = server::require_user_id().await?;
let theme = Theme::parse(&theme).ok_or_else(|| ServerFnError::new("Apparence invalide."))?;
sqlx::query("UPDATE users SET theme = ?1, updated_at = CURRENT_TIMESTAMP WHERE id = ?2")
.bind(theme.as_str())
.bind(user_id)
.execute(&server::pool()?)
.await
.map_err(server::internal_error)?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn theme_round_trips() {
for theme in Theme::ALL {
assert_eq!(Theme::parse(theme.as_str()), Some(theme));
}
assert_eq!(Theme::parse("auto"), None);
assert_eq!(Theme::System.html_attr(), None);
assert_eq!(Theme::Dark.html_attr(), Some("dark"));
}
}
+258
View File
@@ -0,0 +1,258 @@
//! Mesures de pluviométrie : saisie, liste, graphique et cumuls mensuels.
pub mod graph;
use chrono::NaiveDate;
use leptos::prelude::*;
use serde::{Deserialize, Serialize};
pub use graph::{GraphPoint, MonthlySummary, Period};
use crate::errors::field_error;
#[cfg(feature = "ssr")]
use crate::server;
/// Taille d'une page de la liste des mesures (comme le `paginate(15)` de Laravel).
pub const PAGE_SIZE: i64 = 15;
pub const VALUE_MIN: i64 = 1;
pub const VALUE_MAX: i64 = 1000;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Rainfall {
pub id: i64,
/// AAAA-MM-JJ
pub date: String,
/// Hauteur d'eau en mm.
pub value: i64,
}
impl Rainfall {
/// Date au format français (JJ/MM/AAAA).
pub fn date_fr(&self) -> String {
format_date_fr(&self.date)
}
}
pub fn format_date_fr(date: &str) -> String {
NaiveDate::parse_from_str(date, "%Y-%m-%d")
.map(|d| d.format("%d/%m/%Y").to_string())
.unwrap_or_else(|_| date.to_string())
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RainfallPage {
pub items: Vec<Rainfall>,
pub total: i64,
}
/// Date du jour (fuseau du serveur côté SSR, du navigateur côté client).
pub fn today() -> NaiveDate {
chrono::Local::now().date_naive()
}
/// Lit une date `AAAA-MM-JJ` (format des `<input type="date">`).
pub fn parse_date(field: &str, value: &str) -> Result<NaiveDate, ServerFnError> {
NaiveDate::parse_from_str(value.trim(), "%Y-%m-%d")
.ok()
.filter(|d| (1900..=2200).contains(&chrono::Datelike::year(d)))
.ok_or_else(|| field_error(field, "Veuillez saisir une date valide."))
}
/// Lit une hauteur d'eau entière entre 1 et 1000 mm.
pub fn parse_value(value: &str) -> Result<i64, ServerFnError> {
let message = format!("La mesure doit être un nombre entier entre {VALUE_MIN} et {VALUE_MAX}.");
let number: i64 = value
.trim()
.parse()
.map_err(|_| field_error("value", message.clone()))?;
if !(VALUE_MIN..=VALUE_MAX).contains(&number) {
return Err(field_error("value", message));
}
Ok(number)
}
#[server]
pub async fn add_rainfall(date: String, value: String) -> Result<(), ServerFnError> {
let user_id = server::require_user_id().await?;
let date = parse_date("date", &date)?;
let value = parse_value(&value)?;
sqlx::query("INSERT INTO rainfalls (user_id, date, value) VALUES (?1, ?2, ?3)")
.bind(user_id)
.bind(date.format("%Y-%m-%d").to_string())
.bind(value)
.execute(&server::pool()?)
.await
.map_err(server::internal_error)?;
Ok(())
}
#[server]
pub async fn update_rainfall(id: i64, date: String, value: String) -> Result<(), ServerFnError> {
let user_id = server::require_user_id().await?;
let date = parse_date("date", &date)?;
let value = parse_value(&value)?;
let done = sqlx::query(
"UPDATE rainfalls SET date = ?1, value = ?2, updated_at = CURRENT_TIMESTAMP \
WHERE id = ?3 AND user_id = ?4",
)
.bind(date.format("%Y-%m-%d").to_string())
.bind(value)
.bind(id)
.bind(user_id)
.execute(&server::pool()?)
.await
.map_err(server::internal_error)?;
if done.rows_affected() == 0 {
return Err(ServerFnError::new("Mesure introuvable."));
}
Ok(())
}
#[server]
pub async fn delete_rainfall(id: i64) -> Result<(), ServerFnError> {
let user_id = server::require_user_id().await?;
sqlx::query("DELETE FROM rainfalls WHERE id = ?1 AND user_id = ?2")
.bind(id)
.bind(user_id)
.execute(&server::pool()?)
.await
.map_err(server::internal_error)?;
Ok(())
}
/// Les `limit` mesures les plus récentes, et le nombre total de mesures.
#[server]
pub async fn list_rainfalls(limit: i64) -> Result<RainfallPage, ServerFnError> {
let user_id = server::require_user_id().await?;
let pool = server::pool()?;
let items = sqlx::query_as::<_, (i64, String, i64)>(
"SELECT id, date, value FROM rainfalls WHERE user_id = ?1 ORDER BY date DESC, id DESC LIMIT ?2",
)
.bind(user_id)
.bind(limit.clamp(1, 10_000))
.fetch_all(&pool)
.await
.map_err(server::internal_error)?
.into_iter()
.map(|(id, date, value)| Rainfall { id, date, value })
.collect();
let total = sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM rainfalls WHERE user_id = ?1")
.bind(user_id)
.fetch_one(&pool)
.await
.map_err(server::internal_error)?;
Ok(RainfallPage { items, total })
}
/// Cumuls à afficher dans le graphique de la page Pluviométrie.
#[server]
pub async fn graph_data(
start: String,
end: String,
period: String,
) -> Result<Vec<GraphPoint>, ServerFnError> {
use std::collections::HashMap;
let user_id = server::require_user_id().await?;
let start = parse_date("start", &start)?;
let end = parse_date("end", &end)?;
let period =
Period::parse(&period).ok_or_else(|| field_error("period", "Période invalide."))?;
if end < start {
return Err(field_error(
"end",
"La date de fin doit être postérieure à la date de début.",
));
}
if (end - start).num_days() > period.max_days() {
return Err(field_error(
"start",
"Intervalle trop long pour ce regroupement : choisissez une période plus courte ou un regroupement plus large.",
));
}
let rows = sqlx::query_as::<_, (String, i64)>(
"SELECT date, SUM(value) FROM rainfalls \
WHERE user_id = ?1 AND date BETWEEN ?2 AND ?3 GROUP BY date",
)
.bind(user_id)
.bind(start.format("%Y-%m-%d").to_string())
.bind(end.format("%Y-%m-%d").to_string())
.fetch_all(&server::pool()?)
.await
.map_err(server::internal_error)?;
let daily: HashMap<NaiveDate, i64> = rows
.into_iter()
.filter_map(|(date, sum)| Some((NaiveDate::parse_from_str(&date, "%Y-%m-%d").ok()?, sum)))
.collect();
Ok(graph::group(start, end, period, &daily))
}
/// Cumuls mensuels de l'année en cours et de la précédente (page d'accueil).
#[server]
pub async fn last_months() -> Result<MonthlySummary, ServerFnError> {
use chrono::Datelike;
use std::collections::HashMap;
let user_id = server::require_user_id().await?;
let pool = server::pool()?;
let today = today();
let rows = sqlx::query_as::<_, (String, i64)>(
"SELECT substr(date, 1, 7) AS month, SUM(value) FROM rainfalls \
WHERE user_id = ?1 AND date >= ?2 GROUP BY month",
)
.bind(user_id)
.bind(format!("{}-01-01", today.year() - 1))
.fetch_all(&pool)
.await
.map_err(server::internal_error)?;
let sums: HashMap<(i32, u32), i64> = rows
.into_iter()
.filter_map(|(month, sum)| {
let (year, month) = month.split_once('-')?;
Some(((year.parse().ok()?, month.parse().ok()?), sum))
})
.collect();
let first_year = sqlx::query_scalar::<_, Option<String>>(
"SELECT MIN(date) FROM rainfalls WHERE user_id = ?1",
)
.bind(user_id)
.fetch_one(&pool)
.await
.map_err(server::internal_error)?
.and_then(|date| date.get(..4)?.parse().ok());
Ok(graph::monthly_summary(today, &sums, first_year))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn values_must_be_between_1_and_1000() {
assert_eq!(parse_value("1").unwrap(), 1);
assert_eq!(parse_value(" 1000 ").unwrap(), 1000);
for value in ["0", "1001", "-3", "2.5", "", "abc"] {
assert!(parse_value(value).is_err(), "{value:?}");
}
}
#[test]
fn dates_are_parsed() {
assert_eq!(
parse_date("date", "2023-02-28").unwrap(),
NaiveDate::from_ymd_opt(2023, 2, 28).unwrap()
);
for value in ["2023-02-30", "28/02/2023", "", "0001-01-01"] {
assert!(parse_date("date", value).is_err(), "{value:?}");
}
}
#[test]
fn french_dates() {
assert_eq!(format_date_fr("2023-02-08"), "08/02/2023");
}
}
+353
View File
@@ -0,0 +1,353 @@
//! Regroupement des mesures par jour / semaine / mois / année (fonctions pures, testées).
//!
//! Port de `RainfallController::graphValue`, `Rainfall::getDateKey` et
//! `Rainfall::getDateKeyData` de lara-bermite.
use chrono::{Datelike, NaiveDate};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
pub const MONTHS: [&str; 12] = [
"Janvier",
"Février",
"Mars",
"Avril",
"Mai",
"Juin",
"Juillet",
"Août",
"Septembre",
"Octobre",
"Novembre",
"Décembre",
];
/// Abréviations usuelles (juin et juillet restent distincts).
pub const MONTHS_SHORT: [&str; 12] = [
"janv.", "févr.", "mars", "avr.", "mai", "juin", "juil.", "août", "sept.", "oct.", "nov.",
"déc.",
];
pub fn month_short(month: u32) -> &'static str {
MONTHS_SHORT[(month as usize).saturating_sub(1).min(11)]
}
pub fn month_name(month: u32) -> &'static str {
MONTHS[(month as usize).saturating_sub(1).min(11)]
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum Period {
#[default]
Day,
Week,
Month,
Year,
}
impl Period {
pub const ALL: [Period; 4] = [Period::Day, Period::Week, Period::Month, Period::Year];
pub fn as_str(self) -> &'static str {
match self {
Period::Day => "day",
Period::Week => "week",
Period::Month => "month",
Period::Year => "year",
}
}
pub fn parse(value: &str) -> Option<Period> {
Period::ALL.into_iter().find(|p| p.as_str() == value)
}
pub fn label(self) -> &'static str {
match self {
Period::Day => "Jour",
Period::Week => "Semaine",
Period::Month => "Mois",
Period::Year => "Année",
}
}
/// Nombre maximal de jours affichables pour ce regroupement (lisibilité du graphique).
pub fn max_days(self) -> i64 {
match self {
Period::Day => 366 * 2,
Period::Week => 366 * 10,
Period::Month | Period::Year => 366 * 100,
}
}
/// Clé identifiant le groupe auquel appartient `date`.
fn key(self, date: NaiveDate) -> (i32, u32) {
match self {
Period::Day => (date.year(), date.ordinal()),
Period::Week => {
let week = date.iso_week();
(week.year(), week.week())
}
Period::Month => (date.year(), date.month()),
Period::Year => (date.year(), 0),
}
}
fn label_for(self, date: NaiveDate) -> String {
match self {
Period::Day => date.format("%d/%m/%Y").to_string(),
Period::Week => format!("semaine {}", date.iso_week().week()),
Period::Month => format!("{} {}", month_name(date.month()), date.year()),
Period::Year => date.year().to_string(),
}
}
}
/// Une barre du graphique.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct GraphPoint {
/// Premier jour du groupe compris dans l'intervalle demandé (AAAA-MM-JJ).
pub start: String,
/// Nombre de jours du groupe compris dans l'intervalle demandé.
pub days: u32,
pub label: String,
/// Cumul des mesures du groupe, en mm.
pub value: i64,
}
/// Regroupe les cumuls journaliers `daily` sur l'intervalle `[start, end]` (bornes incluses).
/// Chaque groupe de l'intervalle apparaît, même sans mesure (valeur 0).
pub fn group(
start: NaiveDate,
end: NaiveDate,
period: Period,
daily: &HashMap<NaiveDate, i64>,
) -> Vec<GraphPoint> {
let mut points: Vec<GraphPoint> = Vec::new();
let mut current_key = None;
for date in start.iter_days().take_while(|d| *d <= end) {
let key = period.key(date);
if current_key != Some(key) {
current_key = Some(key);
points.push(GraphPoint {
start: date.format("%Y-%m-%d").to_string(),
days: 0,
label: period.label_for(date),
value: 0,
});
}
let point = points.last_mut().expect("un groupe vient d'être créé");
point.days += 1;
point.value += daily.get(&date).copied().unwrap_or(0);
}
points
}
/// Une ligne du tableau « Précipitations des derniers mois ».
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MonthRow {
pub month: u32,
pub label: String,
/// Cumul de l'année en cours ; `None` pour les mois pas encore commencés.
pub current: Option<i64>,
pub previous: i64,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MonthlySummary {
pub current_year: i32,
pub rows: Vec<MonthRow>,
pub total_current: i64,
pub total_previous: i64,
/// Cumul de l'an dernier sur les mêmes mois (janvier au mois en cours inclus).
pub total_previous_to_date: i64,
/// Année de la plus ancienne mesure.
pub first_year: Option<i32>,
}
/// Port de `RainfallController::lastMonths` : de janvier de l'an dernier au mois en cours.
/// `sums` associe (année, mois) au cumul du mois.
pub fn monthly_summary(
today: NaiveDate,
sums: &HashMap<(i32, u32), i64>,
first_year: Option<i32>,
) -> MonthlySummary {
let year = today.year();
let rows: Vec<MonthRow> = (1..=12)
.map(|month| MonthRow {
month,
label: month_name(month).to_string(),
current: (month <= today.month())
.then(|| sums.get(&(year, month)).copied().unwrap_or(0)),
previous: sums.get(&(year - 1, month)).copied().unwrap_or(0),
})
.collect();
MonthlySummary {
current_year: year,
total_current: rows.iter().filter_map(|r| r.current).sum(),
total_previous: rows.iter().map(|r| r.previous).sum(),
total_previous_to_date: rows
.iter()
.filter(|r| r.current.is_some())
.map(|r| r.previous)
.sum(),
rows,
first_year,
}
}
#[cfg(test)]
mod tests {
use super::*;
fn d(s: &str) -> NaiveDate {
NaiveDate::parse_from_str(s, "%Y-%m-%d").unwrap()
}
fn sample() -> HashMap<NaiveDate, i64> {
HashMap::from([
(d("2022-11-20"), 4),
(d("2023-01-01"), 3),
(d("2023-01-02"), 5),
(d("2023-01-20"), 7),
(d("2023-02-01"), 2),
(d("2023-02-06"), 1),
(d("2023-03-31"), 10),
])
}
#[test]
fn by_day() {
let points = group(d("2023-01-01"), d("2023-01-31"), Period::Day, &sample());
assert_eq!(points.len(), 31);
assert_eq!(
points[0],
GraphPoint {
start: "2023-01-01".into(),
days: 1,
label: "01/01/2023".into(),
value: 3
}
);
assert_eq!(
points[1],
GraphPoint {
start: "2023-01-02".into(),
days: 1,
label: "02/01/2023".into(),
value: 5
}
);
assert_eq!(points[2].value, 0);
}
#[test]
fn by_week_uses_iso_weeks() {
// Le 1er février 2023 est un mercredi : la première semaine ne compte que 5 jours.
let points = group(d("2023-02-01"), d("2023-02-28"), Period::Week, &sample());
assert_eq!(
points[0],
GraphPoint {
start: "2023-02-01".into(),
days: 5,
label: "semaine 5".into(),
value: 2
}
);
assert_eq!(
points[1],
GraphPoint {
start: "2023-02-06".into(),
days: 7,
label: "semaine 6".into(),
value: 1
}
);
assert_eq!(points.iter().map(|p| p.days).sum::<u32>(), 28);
}
#[test]
fn by_month() {
let points = group(d("2023-01-15"), d("2023-04-10"), Period::Month, &sample());
assert_eq!(
points[0],
GraphPoint {
start: "2023-01-15".into(),
days: 17,
label: "Janvier 2023".into(),
value: 7
}
);
assert_eq!(
points[1],
GraphPoint {
start: "2023-02-01".into(),
days: 28,
label: "Février 2023".into(),
value: 3
}
);
assert_eq!(
points[2],
GraphPoint {
start: "2023-03-01".into(),
days: 31,
label: "Mars 2023".into(),
value: 10
}
);
assert_eq!(points[3].days, 10);
}
#[test]
fn by_year() {
let points = group(d("2022-11-15"), d("2024-12-31"), Period::Year, &sample());
assert_eq!(
points[0],
GraphPoint {
start: "2022-11-15".into(),
days: 47,
label: "2022".into(),
value: 4
}
);
assert_eq!(points[1].start, "2023-01-01");
assert_eq!(points[1].days, 365);
assert_eq!(points[1].value, 28);
// 2024 est bissextile.
assert_eq!(points[2].days, 366);
}
#[test]
fn empty_when_end_before_start() {
assert!(group(d("2023-02-01"), d("2023-01-01"), Period::Day, &sample()).is_empty());
}
#[test]
fn monthly_summary_covers_last_and_current_year() {
let sums = HashMap::from([
((2023, 1), 15),
((2023, 3), 10),
((2022, 1), 6),
((2022, 12), 8),
]);
let summary = monthly_summary(d("2023-03-14"), &sums, Some(2021));
assert_eq!(summary.current_year, 2023);
assert_eq!(summary.rows.len(), 12);
assert_eq!(
summary.rows[0],
MonthRow {
month: 1,
label: "Janvier".into(),
current: Some(15),
previous: 6
}
);
assert_eq!(summary.rows[1].current, Some(0));
assert_eq!(summary.rows[3].current, None, "avril n'a pas commencé");
assert_eq!(summary.rows[11].previous, 8);
assert_eq!(summary.total_current, 25);
assert_eq!(summary.total_previous, 14);
assert_eq!(summary.total_previous_to_date, 6);
assert_eq!(summary.first_year, Some(2021));
}
}
+246
View File
@@ -0,0 +1,246 @@
//! Code exécuté uniquement côté serveur : configuration, base de données, mots de passe, session.
use argon2::{
Argon2,
password_hash::{
PasswordHash, PasswordHasher, PasswordVerifier, SaltString,
rand_core::{OsRng, RngCore},
},
};
use leptos::prelude::*;
use sha2::{Digest, Sha256};
use sqlx::{
SqlitePool,
sqlite::{SqliteConnectOptions, SqlitePoolOptions},
};
use std::{error::Error, fmt::Display, str::FromStr, sync::Arc, sync::LazyLock};
use tower_sessions::Session;
use crate::weather::WeatherCache;
/// Clé sous laquelle l'identifiant de l'utilisateur est stocké dans la session.
pub const USER_ID_KEY: &str = "user_id";
/// Réglages lus dans l'environnement (fichier `.env` au besoin).
#[derive(Clone, Debug)]
pub struct Config {
/// URL publique du site, sans `/` final : sert au lien de réinitialisation.
pub app_url: String,
pub open_weather_map_api_key: Option<String>,
pub smtp: Option<SmtpConfig>,
pub mail_from: String,
pub registration_enabled: bool,
}
#[derive(Clone, Debug)]
pub struct SmtpConfig {
pub host: String,
pub port: u16,
pub username: String,
pub password: String,
}
impl Config {
pub fn from_env() -> Config {
let var = |name: &str| std::env::var(name).ok().filter(|v| !v.trim().is_empty());
let smtp = var("SMTP_HOST").map(|host| SmtpConfig {
host,
port: var("SMTP_PORT").and_then(|p| p.parse().ok()).unwrap_or(465),
username: var("SMTP_USERNAME").unwrap_or_default(),
password: var("SMTP_PASSWORD").unwrap_or_default(),
});
Config {
app_url: var("APP_URL")
.unwrap_or_else(|| "http://127.0.0.1:3004".into())
.trim_end_matches('/')
.to_string(),
open_weather_map_api_key: var("OPEN_WEATHER_MAP_API_KEY"),
smtp,
mail_from: var("MAIL_FROM").unwrap_or_else(|| "Bermite <bermite@localhost>".into()),
registration_enabled: var("REGISTRATION_ENABLED").is_some_and(|v| v == "true"),
}
}
}
/// Tout ce que les server functions trouvent dans leur contexte.
#[derive(Clone)]
pub struct AppContext {
pub pool: SqlitePool,
pub config: Arc<Config>,
pub http: reqwest::Client,
pub weather_cache: WeatherCache,
}
/// Ouvre le pool SQLite (en créant le fichier au besoin) et applique les migrations.
pub async fn connect_db(url: &str) -> Result<SqlitePool, Box<dyn Error>> {
let options = SqliteConnectOptions::from_str(url)?
.create_if_missing(true)
.foreign_keys(true);
let pool = SqlitePoolOptions::new()
.max_connections(5)
.connect_with(options)
.await?;
sqlx::migrate!().run(&pool).await?;
Ok(pool)
}
fn context() -> Result<AppContext, ServerFnError> {
use_context::<AppContext>().ok_or_else(|| internal_error("AppContext absent du contexte"))
}
/// Pool SQLite fourni en contexte par `main`.
pub fn pool() -> Result<SqlitePool, ServerFnError> {
Ok(context()?.pool)
}
pub fn config() -> Result<Arc<Config>, ServerFnError> {
Ok(context()?.config)
}
pub fn http() -> Result<reqwest::Client, ServerFnError> {
Ok(context()?.http)
}
pub fn weather_cache() -> Result<WeatherCache, ServerFnError> {
Ok(context()?.weather_cache)
}
/// Session de la requête en cours.
pub async fn session() -> Result<Session, ServerFnError> {
leptos_axum::extract::<Session>()
.await
.map_err(internal_error)
}
/// Identifiant de l'utilisateur connecté, ou une erreur s'il n'y a pas de session.
///
/// À appeler en tête de toute server function qui touche à des données personnelles,
/// puis à utiliser dans un `WHERE user_id = ?` : c'est ce qui empêche un utilisateur
/// de lire ou modifier les données d'un autre.
pub async fn require_user_id() -> Result<i64, ServerFnError> {
session()
.await?
.get::<i64>(USER_ID_KEY)
.await
.map_err(internal_error)?
.ok_or_else(|| ServerFnError::new("Vous devez être connecté."))
}
/// Journalise l'erreur réelle et renvoie au client un message générique,
/// pour ne jamais exposer de détails internes (SQL, chemins, etc.).
pub fn internal_error(error: impl Display) -> ServerFnError {
leptos::logging::error!("erreur interne : {error}");
ServerFnError::new("Une erreur interne est survenue.")
}
/// Hache un mot de passe avec Argon2id (sel aléatoire, paramètres par défaut).
///
/// Le calcul est volontairement coûteux : il est déporté sur un thread bloquant
/// pour ne pas geler le runtime async.
pub async fn hash_password(password: String) -> Result<String, ServerFnError> {
tokio::task::spawn_blocking(move || hash_password_sync(&password))
.await
.map_err(internal_error)?
.map_err(internal_error)
}
fn hash_password_sync(password: &str) -> Result<String, String> {
let salt = SaltString::generate(&mut OsRng);
Argon2::default()
.hash_password(password.as_bytes(), &salt)
.map(|hash| hash.to_string())
.map_err(|e| e.to_string())
}
/// Hash factice, vérifié quand l'utilisateur n'existe pas : le temps de réponse
/// est ainsi le même que pour un mauvais mot de passe, ce qui empêche de deviner
/// quelles adresses ont un compte en mesurant la latence.
static DUMMY_HASH: LazyLock<String> = LazyLock::new(|| {
hash_password_sync("mot-de-passe-factice")
.expect("le hachage du hash factice ne peut pas échouer")
});
/// Les comptes importés de Laravel ont un hash bcrypt (`$2y$…`).
pub fn is_legacy_hash(hash: &str) -> bool {
hash.starts_with("$2y$") || hash.starts_with("$2b$") || hash.starts_with("$2a$")
}
/// Vérifie un mot de passe contre un hash Argon2 ou bcrypt. `stored_hash` vaut `None`
/// si l'utilisateur n'existe pas : le calcul est alors fait contre un hash factice et
/// le résultat est toujours `false`.
pub async fn verify_password(password: String, stored_hash: Option<String>) -> bool {
tokio::task::spawn_blocking(move || {
let user_exists = stored_hash.is_some();
let hash = stored_hash.as_deref().unwrap_or(DUMMY_HASH.as_str());
let valid = if is_legacy_hash(hash) {
bcrypt::verify(&password, hash).unwrap_or(false)
} else {
PasswordHash::new(hash).is_ok_and(|parsed| {
Argon2::default()
.verify_password(password.as_bytes(), &parsed)
.is_ok()
})
};
valid && user_exists
})
.await
.unwrap_or(false)
}
/// Jeton aléatoire (256 bits, en hexadécimal) pour les liens de réinitialisation.
pub fn random_token() -> String {
let mut bytes = [0u8; 32];
OsRng.fill_bytes(&mut bytes);
hex::encode(bytes)
}
/// Empreinte stockée en base à la place du jeton : une fuite de la base ne permet
/// pas de réinitialiser les mots de passe.
pub fn token_hash(token: &str) -> String {
hex::encode(Sha256::digest(token.as_bytes()))
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn correct_password_is_accepted() {
let hash = hash_password("Correct-horse-1".into()).await.unwrap();
assert!(hash.starts_with("$argon2id$"));
assert!(verify_password("Correct-horse-1".into(), Some(hash)).await);
}
#[tokio::test]
async fn wrong_password_is_rejected() {
let hash = hash_password("Correct-horse-1".into()).await.unwrap();
assert!(!verify_password("wrong".into(), Some(hash)).await);
}
#[tokio::test]
async fn unknown_user_is_always_rejected() {
assert!(!verify_password("mot-de-passe-factice".into(), None).await);
}
#[tokio::test]
async fn laravel_bcrypt_hashes_are_accepted() {
// Laravel produit des hash `$2y$` ; on en fabrique un équivalent.
let hash = bcrypt::hash_with_result("Secret123", 4)
.unwrap()
.format_for_version(bcrypt::Version::TwoY);
assert!(hash.starts_with("$2y$"));
assert!(is_legacy_hash(&hash));
assert!(verify_password("Secret123".into(), Some(hash.clone())).await);
assert!(!verify_password("secret123".into(), Some(hash)).await);
}
#[test]
fn tokens_are_random_and_hashed() {
let a = random_token();
let b = random_token();
assert_eq!(a.len(), 64);
assert_ne!(a, b);
assert_eq!(token_hash(&a), token_hash(&a));
assert_ne!(token_hash(&a), a);
}
}
+251
View File
@@ -0,0 +1,251 @@
//! Petits composants d'interface réutilisables (Tailwind CSS).
// Faux positif provoqué par `#[component]` sur les props `optional, into`.
#![allow(clippy::extra_unused_lifetimes)]
use leptos::prelude::*;
use crate::{
errors::{error_for_field, general_error},
icons::{Icon, IconName},
};
/// Valeur d'une `ServerAction` (`action.value()`) : `None` tant qu'elle n'a pas été lancée.
pub trait ActionValue<T>:
Get<Value = Option<Result<T, ServerFnError>>> + Send + Sync + 'static
{
}
impl<T, S> ActionValue<T> for S where
S: Get<Value = Option<Result<T, ServerFnError>>> + Send + Sync + 'static
{
}
/// Erreur d'une action concernant le champ `field`.
pub fn field_error_of<T>(value: impl ActionValue<T>, field: &'static str) -> Signal<Option<String>>
where
T: Clone + Send + Sync + 'static,
{
Signal::derive(move || match value.get() {
Some(Err(e)) => error_for_field(&e, field),
_ => None,
})
}
/// Erreur d'une action qui ne concerne aucun champ en particulier.
pub fn general_error_of<T>(value: impl ActionValue<T>) -> Signal<Option<String>>
where
T: Clone + Send + Sync + 'static,
{
Signal::derive(move || match value.get() {
Some(Err(e)) => general_error(&e),
_ => None,
})
}
/// L'action a-t-elle réussi (dernier résultat) ?
pub fn succeeded<T>(value: impl ActionValue<T>) -> Signal<bool>
where
T: Clone + Send + Sync + 'static,
{
Signal::derive(move || matches!(value.get(), Some(Ok(_))))
}
/// Mise en page d'une page : largeur maximale, marges, titre et sous-titre facultatifs.
#[component]
pub fn Page(
#[prop(optional, into)] title: Option<String>,
#[prop(optional, into)] subtitle: Option<String>,
children: Children,
) -> impl IntoView {
view! {
<div class="mx-auto flex w-full max-w-5xl flex-col gap-5 px-4 py-6 sm:px-6 sm:py-8">
{title
.map(|title| {
view! {
<div>
<h1 class="text-2xl font-bold tracking-tight sm:text-3xl">{title}</h1>
{subtitle.map(|subtitle| view! { <p class="muted mt-1">{subtitle}</p> })}
</div>
}
})}
{children()}
</div>
}
}
/// Carte : surface blanche arrondie, avec un titre et une icône facultatifs.
#[component]
pub fn Card(
#[prop(optional)] title: Option<&'static str>,
#[prop(optional)] icon: Option<IconName>,
#[prop(optional, into)] class: String,
children: Children,
) -> impl IntoView {
view! {
<section class=format!("surface p-4 sm:p-5 {class}")>
{title
.map(|title| {
view! {
<h2 class="mb-4 flex items-center gap-2.5 font-semibold">
{icon
.map(|icon| {
view! {
<span class="flex size-8 items-center justify-center rounded-lg bg-blue-50 text-blue-600 dark:bg-blue-500/10 dark:text-blue-400">
<Icon icon class="size-4" />
</span>
}
})}
{title}
</h2>
}
})}
{children()}
</section>
}
}
/// Chiffre clé : libellé, valeur, unité et détail facultatif.
#[component]
pub fn StatTile(
#[prop(into)] label: String,
#[prop(into)] value: String,
#[prop(optional)] unit: Option<&'static str>,
#[prop(optional, into)] detail: Option<String>,
#[prop(optional)] icon: Option<IconName>,
) -> impl IntoView {
view! {
<div class="surface flex flex-col gap-1 p-4">
<div class="muted flex items-center gap-1.5 text-sm font-medium">
{icon.map(|icon| view! { <Icon icon class="size-4" /> })}
{label}
</div>
<div class="text-2xl font-semibold tracking-tight sm:text-3xl">
{value}
{unit.map(|unit| view! { <span class="muted ml-1 text-base font-medium">{unit}</span> })}
</div>
{detail.map(|detail| view! { <div class="muted text-sm">{detail}</div> })}
</div>
}
}
/// Champ de formulaire : libellé, `<input>` et message d'erreur éventuel.
#[component]
pub fn Field(
#[prop(optional)] label: Option<&'static str>,
name: &'static str,
#[prop(default = "text")] kind: &'static str,
#[prop(optional, into)] value: Option<String>,
#[prop(optional)] placeholder: Option<&'static str>,
#[prop(optional)] autocomplete: Option<&'static str>,
#[prop(optional)] step: Option<&'static str>,
#[prop(optional)] min: Option<&'static str>,
#[prop(optional)] max: Option<&'static str>,
#[prop(optional)] inputmode: Option<&'static str>,
#[prop(default = true)] required: bool,
#[prop(optional)] autofocus: bool,
#[prop(optional, into)] error: Signal<Option<String>>,
) -> impl IntoView {
let id = format!("field-{name}");
let error_id = format!("{id}-error");
view! {
<div class="flex flex-col gap-1.5">
{label
.map(|label| {
view! {
<label for=id.clone() class="text-sm font-medium text-slate-700 dark:text-slate-300">
{label}
</label>
}
})}
<input
id=id
class="input"
class=("!border-red-500", move || error.with(Option::is_some))
type=kind
name=name
value=value
placeholder=placeholder
autocomplete=autocomplete
step=step
min=min
max=max
inputmode=inputmode
required=required
autofocus=autofocus
aria-invalid=move || error.with(Option::is_some).to_string()
aria-describedby=error_id.clone()
/>
<FieldError id=error_id message=error />
</div>
}
}
/// Message d'erreur sous un champ.
#[component]
pub fn FieldError(
#[prop(optional, into)] id: String,
#[prop(into)] message: Signal<Option<String>>,
) -> impl IntoView {
view! {
<p id=id class="text-sm text-red-600 empty:hidden dark:text-red-400" role="alert">
{move || message.get()}
</p>
}
}
/// Bandeau d'erreur générale.
#[component]
pub fn ErrorBanner(#[prop(into)] message: Signal<Option<String>>) -> impl IntoView {
move || {
message.get().map(|message| {
view! {
<div
class="rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700 dark:border-red-500/30 dark:bg-red-500/10 dark:text-red-300"
role="alert"
>
{message}
</div>
}
})
}
}
/// Bandeau de confirmation.
#[component]
pub fn SuccessBanner(children: Children) -> impl IntoView {
view! {
<div
class="flex items-start gap-2 rounded-lg border border-emerald-200 bg-emerald-50 px-3 py-2 text-sm text-emerald-800 dark:border-emerald-500/30 dark:bg-emerald-500/10 dark:text-emerald-300"
role="status"
>
<Icon icon=IconName::Check class="mt-0.5 size-4" />
<span>{children()}</span>
</div>
}
}
/// Bouton de validation, désactivé pendant l'envoi.
#[component]
pub fn SubmitButton(
#[prop(into)] pending: Signal<bool>,
#[prop(optional, into)] class: String,
children: Children,
) -> impl IntoView {
view! {
<button type="submit" class=format!("btn-primary {class}") disabled=move || pending.get()>
{children()}
</button>
}
}
/// Bloc grisé animé affiché pendant un chargement.
#[component]
pub fn Loading(#[prop(default = "h-32")] height: &'static str) -> impl IntoView {
view! {
<div
class=format!("w-full animate-pulse rounded-2xl bg-slate-200/70 dark:bg-slate-800/70 {height}")
role="status"
aria-label="Chargement"
></div>
}
}
+382
View File
@@ -0,0 +1,382 @@
//! Prévisions météo OpenWeatherMap (5 jours, pas de 3 heures).
//!
//! Le serveur interroge l'API (avec un cache de 5 minutes par emplacement, comme le
//! `Cache::remember` de lara-bermite) puis prépare directement ce que la page affiche :
//! la météo du moment et un résumé par jour (port de la logique de `Weather.tsx`).
use chrono::{DateTime, Datelike, NaiveDate, Timelike, Weekday};
use leptos::prelude::*;
use serde::{Deserialize, Serialize};
#[cfg(feature = "ssr")]
use crate::server;
/// Icônes disponibles dans `public/images/icons`.
const ICONS: [&str; 7] = ["01d", "02d", "03d", "03n", "04d", "09d", "10d"];
/// Nom de l'icône à afficher : celle d'OpenWeatherMap si on l'a, sa version « jour »
/// sinon, et une icône générique en dernier recours.
pub fn icon_name(icon: &str) -> String {
if ICONS.contains(&icon) {
return icon.to_string();
}
let day = icon.replace('n', "d");
if ICONS.contains(&day.as_str()) {
day
} else {
"weather".to_string()
}
}
pub fn weekday_fr(weekday: Weekday) -> &'static str {
match weekday {
Weekday::Mon => "lundi",
Weekday::Tue => "mardi",
Weekday::Wed => "mercredi",
Weekday::Thu => "jeudi",
Weekday::Fri => "vendredi",
Weekday::Sat => "samedi",
Weekday::Sun => "dimanche",
}
}
// ---- Réponse de l'API (https://openweathermap.org/forecast5) ----
#[derive(Clone, Debug, Deserialize)]
pub struct Forecast {
pub list: Vec<ForecastItem>,
#[serde(default)]
pub city: Option<City>,
}
#[derive(Clone, Debug, Deserialize)]
pub struct City {
/// Décalage horaire en secondes par rapport à UTC.
#[serde(default)]
pub timezone: i64,
}
#[derive(Clone, Debug, Deserialize)]
pub struct ForecastItem {
pub dt: i64,
pub main: ForecastMain,
pub weather: Vec<WeatherTag>,
}
#[derive(Clone, Debug, Deserialize)]
pub struct ForecastMain {
pub temp: f64,
pub temp_min: f64,
pub temp_max: f64,
}
#[derive(Clone, Debug, Deserialize)]
pub struct WeatherTag {
pub main: String,
pub description: String,
pub icon: String,
}
// ---- Ce que la page affiche ----
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct WeatherView {
pub current: Option<CurrentWeather>,
pub days: Vec<DayForecast>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CurrentWeather {
pub temp: f64,
/// Minimum et maximum prévus pour la journée.
pub temp_min: f64,
pub temp_max: f64,
pub main: String,
pub description: String,
pub icon: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DayForecast {
/// AAAA-MM-JJ
pub date: String,
pub weekday: String,
/// JJ/MM/AAAA
pub date_fr: String,
pub main: String,
pub description: String,
pub icon: String,
pub min: f64,
pub max: f64,
pub slots: Vec<Slot>,
}
/// Prévision d'une tranche de 3 heures.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Slot {
pub hour: u32,
pub temp: f64,
pub description: String,
pub icon: String,
}
/// Prépare l'affichage à partir de la réponse de l'API. `now` est un timestamp UNIX.
pub fn summarize(forecast: &Forecast, now: i64) -> WeatherView {
let offset = forecast.city.as_ref().map_or(0, |c| c.timezone);
let local = |ts: i64| {
DateTime::from_timestamp(ts + offset, 0)
.unwrap_or_default()
.naive_utc()
};
let today = local(now).date();
let items: Vec<_> = forecast
.list
.iter()
.filter_map(|item| Some((local(item.dt), item, item.weather.first()?)))
.collect();
let current = items.first().map(|(_, first, tag)| {
let today_items = items.iter().filter(|(time, ..)| time.date() == today);
CurrentWeather {
temp: first.main.temp,
temp_min: today_items
.clone()
.map(|(_, i, _)| i.main.temp_min)
.fold(first.main.temp_min, f64::min),
temp_max: today_items
.map(|(_, i, _)| i.main.temp_max)
.fold(first.main.temp_max, f64::max),
main: tag.main.clone(),
description: tag.description.clone(),
icon: icon_name(&tag.icon),
}
});
// Regroupement par jour, dans l'ordre chronologique, sans le jour même.
let mut groups: Vec<(NaiveDate, Vec<_>)> = Vec::new();
for entry in items.iter().filter(|(time, ..)| time.date() != today) {
match groups.last_mut() {
Some((date, entries)) if *date == entry.0.date() => entries.push(entry),
_ => groups.push((entry.0.date(), vec![entry])),
}
}
let days = groups
.into_iter()
.map(|(date, entries)| {
// Temps dominant : le plus fréquent de la journée (le premier rencontré en cas d'égalité).
let mut counts: Vec<(&str, usize)> = Vec::new();
for (_, _, tag) in &entries {
match counts.iter_mut().find(|(main, _)| *main == tag.main) {
Some((_, count)) => *count += 1,
None => counts.push((&tag.main, 1)),
}
}
let dominant = counts
.iter()
.fold(None::<(&str, usize)>, |best, &(main, count)| match best {
Some((_, best_count)) if best_count >= count => best,
_ => Some((main, count)),
})
.map(|(main, _)| main)
.unwrap_or_default();
let tag = entries
.iter()
.map(|(_, _, tag)| tag)
.find(|tag| tag.main == dominant)
.expect("le temps dominant vient de la liste");
DayForecast {
date: date.format("%Y-%m-%d").to_string(),
weekday: weekday_fr(date.weekday()).to_string(),
date_fr: date.format("%d/%m/%Y").to_string(),
main: tag.main.clone(),
description: tag.description.clone(),
icon: icon_name(&tag.icon.replace('n', "d")),
min: entries
.iter()
.map(|(_, i, _)| i.main.temp_min)
.fold(f64::INFINITY, f64::min),
max: entries
.iter()
.map(|(_, i, _)| i.main.temp_max)
.fold(f64::NEG_INFINITY, f64::max),
slots: entries
.iter()
.map(|(time, item, tag)| Slot {
hour: time.hour(),
temp: item.main.temp,
description: tag.description.clone(),
icon: icon_name(&tag.icon.replace('n', "d")),
})
.collect(),
}
})
.collect();
WeatherView { current, days }
}
/// Réponses de l'API mises en cache, par emplacement.
#[cfg(feature = "ssr")]
pub type WeatherCache = std::sync::Arc<
tokio::sync::Mutex<
std::collections::HashMap<i64, (std::time::Instant, std::sync::Arc<Forecast>)>,
>,
>;
#[cfg(feature = "ssr")]
const CACHE_TTL: std::time::Duration = std::time::Duration::from_secs(5 * 60);
#[server]
pub async fn get_weather() -> Result<WeatherView, ServerFnError> {
use std::{sync::Arc, time::Instant};
let user_id = server::require_user_id().await?;
let locations = crate::location::user_locations(&server::pool()?, user_id).await?;
let Some(location) = locations.first() else {
return Err(ServerFnError::new(
"Coordonnées non renseignées dans le profil.",
));
};
let cache = server::weather_cache()?;
let cached = cache
.lock()
.await
.get(&location.id)
.filter(|(at, _)| at.elapsed() < CACHE_TTL)
.map(|(_, forecast)| forecast.clone());
let forecast = match cached {
Some(forecast) => forecast,
None => {
let config = server::config()?;
let Some(api_key) = &config.open_weather_map_api_key else {
return Err(server::internal_error(
"OPEN_WEATHER_MAP_API_KEY non configurée",
));
};
let response = server::http()?
.get("https://api.openweathermap.org/data/2.5/forecast")
.query(&[
("lat", location.latitude.to_string()),
("lon", location.longitude.to_string()),
("appid", api_key.clone()),
("units", "metric".into()),
("lang", "fr".into()),
])
.send()
.await
.and_then(|r| r.error_for_status());
let forecast: Forecast = match response {
Ok(response) => response.json().await.map_err(server::internal_error)?,
Err(e) => {
// Sans `e.url()` : l'URL contient la clé d'API.
leptos::logging::error!("OpenWeatherMap injoignable : {}", e.without_url());
return Err(ServerFnError::new("Impossible de récupérer la météo."));
}
};
let forecast = Arc::new(forecast);
cache
.lock()
.await
.insert(location.id, (Instant::now(), forecast.clone()));
forecast
}
};
Ok(summarize(&forecast, chrono::Utc::now().timestamp()))
}
#[cfg(test)]
mod tests {
use super::*;
fn item(dt: i64, temp: f64, main: &str, icon: &str) -> ForecastItem {
ForecastItem {
dt,
main: ForecastMain {
temp,
temp_min: temp - 1.0,
temp_max: temp + 1.0,
},
weather: vec![WeatherTag {
main: main.into(),
description: main.to_lowercase(),
icon: icon.into(),
}],
}
}
// 2023-06-01T00:00:00Z
const DAY1: i64 = 1_685_577_600;
const H: i64 = 3600;
#[test]
fn icons_fall_back_to_day_then_generic() {
assert_eq!(icon_name("03n"), "03n");
assert_eq!(icon_name("01n"), "01d");
assert_eq!(icon_name("13d"), "weather");
}
#[test]
fn summary_splits_today_and_next_days() {
let forecast = Forecast {
city: Some(City { timezone: 2 * H }),
list: vec![
item(DAY1 + 12 * H, 20.0, "Clear", "01d"),
item(DAY1 + 15 * H, 24.0, "Clouds", "03d"),
item(DAY1 + 23 * H, 15.0, "Rain", "10n"), // 1er juin 23 h UTC = 2 juin 1 h locale
item(DAY1 + 26 * H, 14.0, "Rain", "10d"),
item(DAY1 + 29 * H, 18.0, "Clear", "01d"),
],
};
let view = summarize(&forecast, DAY1 + 11 * H);
let current = view.current.unwrap();
assert_eq!(current.temp, 20.0);
assert_eq!(current.temp_min, 19.0);
assert_eq!(current.temp_max, 25.0);
assert_eq!(current.icon, "01d");
assert_eq!(view.days.len(), 1);
let day = &view.days[0];
assert_eq!(day.date, "2023-06-02");
assert_eq!(day.weekday, "vendredi");
assert_eq!(day.main, "Rain");
assert_eq!(day.icon, "10d");
assert_eq!(day.min, 13.0);
assert_eq!(day.max, 19.0);
assert_eq!(
day.slots.iter().map(|s| s.hour).collect::<Vec<_>>(),
[1, 4, 7]
);
}
#[test]
fn ties_keep_the_first_weather() {
let forecast = Forecast {
city: None,
list: vec![
item(DAY1, 10.0, "Clear", "01d"),
item(DAY1 + 30 * H, 10.0, "Clouds", "04d"),
item(DAY1 + 33 * H, 10.0, "Rain", "09d"),
],
};
let view = summarize(&forecast, DAY1);
assert_eq!(view.days[0].main, "Clouds");
}
#[cfg(feature = "ssr")]
#[test]
fn parses_api_response() {
let json = r#"{"cod":"200","list":[{"dt":1685620800,"main":{"temp":21.5,"feels_like":21,"temp_min":20.1,"temp_max":22.3,"pressure":1015,"humidity":50},
"weather":[{"id":800,"main":"Clear","description":"ciel dégagé","icon":"01d"}],"dt_txt":"2023-06-01 12:00:00"}],
"city":{"id":1,"name":"X","timezone":7200}}"#;
let forecast: Forecast = serde_json::from_str(json).unwrap();
assert_eq!(forecast.list.len(), 1);
assert_eq!(forecast.city.unwrap().timezone, 7200);
}
}
+83
View File
@@ -0,0 +1,83 @@
@import "tailwindcss";
/* Les vues Leptos vivent dans `src`. */
@source "../src";
/* Variante `dark:` à trois états, pilotée par l'attribut `data-theme` de <html> :
- data-theme="dark" : sombre forcé ;
- data-theme="light" : clair forcé ;
- sans attribut : suit le réglage du système (prefers-color-scheme). */
@custom-variant dark {
&:where([data-theme="dark"], [data-theme="dark"] *) {
@slot;
}
@media (prefers-color-scheme: dark) {
&:where(:not([data-theme="light"], [data-theme="light"] *)) {
@slot;
}
}
}
@theme {
--font-sans: "Figtree", ui-sans-serif, system-ui, sans-serif;
/* Séries des graphiques (palette validée en clair et en sombre, daltonisme compris). */
--color-chart-1: #2a78d6;
--color-chart-2: #eb6834;
}
@layer base {
:root {
color-scheme: light dark;
}
:root[data-theme="light"] {
color-scheme: light;
}
:root[data-theme="dark"] {
color-scheme: dark;
}
/* Teintes des séries recalées pour le fond sombre. */
:root[data-theme="dark"] {
--color-chart-1: #3987e5;
--color-chart-2: #d95926;
}
@media (prefers-color-scheme: dark) {
:root:where(:not([data-theme="light"])) {
--color-chart-1: #3987e5;
--color-chart-2: #d95926;
}
}
input[type="date"]::-webkit-calendar-picker-indicator {
cursor: pointer;
opacity: 0.6;
}
input[type="date"]::-webkit-calendar-picker-indicator:hover {
opacity: 1;
}
}
/* Bouton principal. */
@utility btn-primary {
@apply inline-flex cursor-pointer items-center justify-center gap-2 rounded-lg bg-blue-600 px-4 py-2 font-semibold text-white shadow-sm transition hover:bg-blue-700 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-600 active:scale-[0.98] disabled:cursor-wait disabled:opacity-60;
}
/* Bouton discret (actions secondaires). */
@utility btn-ghost {
@apply inline-flex cursor-pointer items-center justify-center gap-1.5 rounded-lg px-3 py-1.5 text-sm font-medium text-slate-600 transition hover:bg-slate-100 hover:text-slate-900 focus-visible:outline-2 focus-visible:outline-blue-600 dark:text-slate-300 dark:hover:bg-slate-800 dark:hover:text-white;
}
@utility input {
@apply w-full rounded-lg border border-slate-300 bg-white px-3 py-2 text-slate-900 shadow-xs transition placeholder:text-slate-400 focus:border-blue-500 focus:ring-3 focus:ring-blue-500/20 focus:outline-none dark:border-slate-700 dark:bg-slate-800 dark:text-white;
}
/* Surface des cartes. */
@utility surface {
@apply rounded-2xl border border-slate-200 bg-white shadow-sm dark:border-slate-800 dark:bg-slate-900;
}
/* Texte secondaire. */
@utility muted {
@apply text-slate-500 dark:text-slate-400;
}