Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9aa81a22fe | ||
|
|
6c593b0201 | ||
|
|
f3f5f0cee1 |
No files matched your search
Generated
+1
@@ -1397,6 +1397,7 @@ dependencies = [
|
|||||||
"console_error_panic_hook",
|
"console_error_panic_hook",
|
||||||
"dotenvy",
|
"dotenvy",
|
||||||
"hex",
|
"hex",
|
||||||
|
"js-sys",
|
||||||
"leptos",
|
"leptos",
|
||||||
"leptos_axum",
|
"leptos_axum",
|
||||||
"leptos_meta",
|
"leptos_meta",
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ hex = { version = "0.4", optional = true }
|
|||||||
dotenvy = { version = "0.15", optional = true }
|
dotenvy = { version = "0.15", optional = true }
|
||||||
serde = { version = "1", features = ["derive"] }
|
serde = { version = "1", features = ["derive"] }
|
||||||
wasm-bindgen = { version = "=0.2.128", optional = true }
|
wasm-bindgen = { version = "=0.2.128", optional = true }
|
||||||
|
js-sys = { version = "0.3", optional = true }
|
||||||
web-sys = { version = "0.3", features = ["CloseEvent", "Document", "Location", "MessageEvent", "VisibilityState", "WebSocket", "Window"], optional = true }
|
web-sys = { version = "0.3", features = ["CloseEvent", "Document", "Location", "MessageEvent", "VisibilityState", "WebSocket", "Window"], optional = true }
|
||||||
send_wrapper = { version = "0.6", optional = true }
|
send_wrapper = { version = "0.6", optional = true }
|
||||||
console_error_panic_hook = { version = "0.1", optional = true }
|
console_error_panic_hook = { version = "0.1", optional = true }
|
||||||
@@ -30,6 +31,7 @@ hydrate = [
|
|||||||
"leptos/hydrate",
|
"leptos/hydrate",
|
||||||
"dep:console_error_panic_hook",
|
"dep:console_error_panic_hook",
|
||||||
"dep:wasm-bindgen",
|
"dep:wasm-bindgen",
|
||||||
|
"dep:js-sys",
|
||||||
"dep:web-sys",
|
"dep:web-sys",
|
||||||
"dep:send_wrapper",
|
"dep:send_wrapper",
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -0,0 +1,4 @@
|
|||||||
|
ALTER TABLE users ADD COLUMN is_admin INTEGER NOT NULL DEFAULT 0;
|
||||||
|
|
||||||
|
-- The first account to register administers the others.
|
||||||
|
UPDATE users SET is_admin = 1 WHERE id = (SELECT MIN(id) FROM users);
|
||||||
+203
-61
@@ -1,7 +1,7 @@
|
|||||||
use leptos::prelude::*;
|
use leptos::prelude::*;
|
||||||
use leptos::server_fn::codec::Json;
|
use leptos::server_fn::codec::Json;
|
||||||
|
|
||||||
use crate::model::{Item, ItemInput, ListColor, Member, ShoppingList, Suggestion, User};
|
use crate::model::{Account, Item, ItemOp, ListColor, Member, ShoppingList, Suggestion, SyncReport, User};
|
||||||
|
|
||||||
pub const NOT_LOGGED_IN: &str = "Session expirée, reconnecte-toi.";
|
pub const NOT_LOGGED_IN: &str = "Session expirée, reconnecte-toi.";
|
||||||
|
|
||||||
@@ -29,6 +29,20 @@ mod server {
|
|||||||
.ok_or_else(|| ServerFnError::new(super::NOT_LOGGED_IN))
|
.ok_or_else(|| ServerFnError::new(super::NOT_LOGGED_IN))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub async fn require_admin(pool: &SqlitePool) -> Result<User, ServerFnError> {
|
||||||
|
let user = require_user(pool).await?;
|
||||||
|
if !user.is_admin {
|
||||||
|
return Err(ServerFnError::new("Réservé aux administrateurs."));
|
||||||
|
}
|
||||||
|
Ok(user)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sign-ups follow `REGISTRATION_ENABLED`, but stay open until the first
|
||||||
|
/// account (the admin) exists.
|
||||||
|
pub async fn registration_open(pool: &SqlitePool) -> Result<bool, ServerFnError> {
|
||||||
|
Ok(crate::auth::registration_enabled() || !crate::db::has_users(pool).await.map_err(db_err)?)
|
||||||
|
}
|
||||||
|
|
||||||
fn not_found() -> ServerFnError {
|
fn not_found() -> ServerFnError {
|
||||||
ServerFnError::new("Liste introuvable.")
|
ServerFnError::new("Liste introuvable.")
|
||||||
}
|
}
|
||||||
@@ -48,16 +62,6 @@ mod server {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Fails unless the item belongs to a list the user can access; returns that list.
|
|
||||||
pub async fn require_item(pool: &SqlitePool, user: &User, item_id: i64) -> Result<i64, ServerFnError> {
|
|
||||||
let list_id = crate::db::item_list_id(pool, item_id)
|
|
||||||
.await
|
|
||||||
.map_err(db_err)?
|
|
||||||
.ok_or_else(|| ServerFnError::new("Article introuvable."))?;
|
|
||||||
require_list(pool, user, list_id).await?;
|
|
||||||
Ok(list_id)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Everyone who can see the list, to pass to [`notify`] once it changed.
|
/// Everyone who can see the list, to pass to [`notify`] once it changed.
|
||||||
pub async fn audience(pool: &SqlitePool, list_id: i64) -> Result<Vec<i64>, ServerFnError> {
|
pub async fn audience(pool: &SqlitePool, list_id: i64) -> Result<Vec<i64>, ServerFnError> {
|
||||||
crate::db::list_audience(pool, list_id).await.map_err(db_err)
|
crate::db::list_audience(pool, list_id).await.map_err(db_err)
|
||||||
@@ -76,6 +80,13 @@ mod server {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn message(err: ServerFnError) -> String {
|
||||||
|
match err {
|
||||||
|
ServerFnError::ServerError(msg) => msg,
|
||||||
|
err => err.to_string(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub fn clean_name(name: &str, max: usize) -> Result<String, ServerFnError> {
|
pub fn clean_name(name: &str, max: usize) -> Result<String, ServerFnError> {
|
||||||
let name = name.trim();
|
let name = name.trim();
|
||||||
if name.is_empty() || name.chars().count() > max {
|
if name.is_empty() || name.chars().count() > max {
|
||||||
@@ -96,6 +107,29 @@ mod server {
|
|||||||
Ok(email)
|
Ok(email)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn check_password(password: &str) -> Result<(), ServerFnError> {
|
||||||
|
if !(8..=128).contains(&password.chars().count()) {
|
||||||
|
return Err(ServerFnError::new("Le mot de passe doit faire au moins 8 caractères."));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn hash(password: String) -> Result<String, ServerFnError> {
|
||||||
|
blocking(move || crate::auth::hash_password(&password))
|
||||||
|
.await?
|
||||||
|
.map_err(|_| ServerFnError::new("Erreur interne"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Maps a duplicate email to a readable error.
|
||||||
|
pub fn email_err(err: sqlx::Error) -> ServerFnError {
|
||||||
|
match err {
|
||||||
|
sqlx::Error::Database(err) if err.is_unique_violation() => {
|
||||||
|
ServerFnError::new("Un compte existe déjà avec cet email.")
|
||||||
|
}
|
||||||
|
err => db_err(err),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn blocking<T: Send + 'static>(f: impl FnOnce() -> T + Send + 'static) -> Result<T, ServerFnError> {
|
pub async fn blocking<T: Send + 'static>(f: impl FnOnce() -> T + Send + 'static) -> Result<T, ServerFnError> {
|
||||||
tokio::task::spawn_blocking(f)
|
tokio::task::spawn_blocking(f)
|
||||||
.await
|
.await
|
||||||
@@ -113,32 +147,23 @@ pub async fn get_me() -> Result<Option<User>, ServerFnError> {
|
|||||||
|
|
||||||
#[server]
|
#[server]
|
||||||
pub async fn registration_enabled() -> Result<bool, ServerFnError> {
|
pub async fn registration_enabled() -> Result<bool, ServerFnError> {
|
||||||
Ok(crate::auth::registration_enabled())
|
use server::*;
|
||||||
|
registration_open(&pool()?).await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[server]
|
#[server]
|
||||||
pub async fn register(name: String, email: String, password: String) -> Result<(), ServerFnError> {
|
pub async fn register(name: String, email: String, password: String) -> Result<(), ServerFnError> {
|
||||||
use server::*;
|
use server::*;
|
||||||
if !crate::auth::registration_enabled() {
|
let pool = pool()?;
|
||||||
|
if !registration_open(&pool).await? {
|
||||||
return Err(ServerFnError::new("Les inscriptions sont fermées."));
|
return Err(ServerFnError::new("Les inscriptions sont fermées."));
|
||||||
}
|
}
|
||||||
let pool = pool()?;
|
|
||||||
let name = clean_name(&name, 40)?;
|
let name = clean_name(&name, 40)?;
|
||||||
let email = clean_email(&email)?;
|
let email = clean_email(&email)?;
|
||||||
if !(8..=128).contains(&password.chars().count()) {
|
check_password(&password)?;
|
||||||
return Err(ServerFnError::new("Le mot de passe doit faire au moins 8 caractères."));
|
|
||||||
}
|
|
||||||
|
|
||||||
let hash = blocking(move || crate::auth::hash_password(&password))
|
let hash = hash(password).await?;
|
||||||
.await?
|
let user_id = crate::db::register(&pool, &email, &name, &hash).await.map_err(email_err)?;
|
||||||
.map_err(|_| ServerFnError::new("Erreur interne"))?;
|
|
||||||
let user_id = match crate::db::register(&pool, &email, &name, &hash).await {
|
|
||||||
Ok(id) => id,
|
|
||||||
Err(sqlx::Error::Database(err)) if err.is_unique_violation() => {
|
|
||||||
return Err(ServerFnError::new("Un compte existe déjà avec cet email."));
|
|
||||||
}
|
|
||||||
Err(err) => return Err(db_err(err)),
|
|
||||||
};
|
|
||||||
crate::auth::start_session(&pool, user_id).await.map_err(db_err)?;
|
crate::auth::start_session(&pool, user_id).await.map_err(db_err)?;
|
||||||
leptos_axum::redirect("/");
|
leptos_axum::redirect("/");
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -170,6 +195,89 @@ pub async fn logout() -> Result<(), ServerFnError> {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- Administration ---------------------------------------------------------
|
||||||
|
|
||||||
|
#[server]
|
||||||
|
pub async fn get_accounts() -> Result<Vec<Account>, ServerFnError> {
|
||||||
|
use server::*;
|
||||||
|
let pool = pool()?;
|
||||||
|
require_admin(&pool).await?;
|
||||||
|
crate::db::accounts(&pool).await.map_err(db_err)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Creates an account even when sign-ups are closed.
|
||||||
|
#[server]
|
||||||
|
pub async fn create_account(name: String, email: String, password: String, is_admin: bool) -> Result<(), ServerFnError> {
|
||||||
|
use server::*;
|
||||||
|
let pool = pool()?;
|
||||||
|
require_admin(&pool).await?;
|
||||||
|
let name = clean_name(&name, 40)?;
|
||||||
|
let email = clean_email(&email)?;
|
||||||
|
check_password(&password)?;
|
||||||
|
|
||||||
|
let hash = hash(password).await?;
|
||||||
|
let id = crate::db::register(&pool, &email, &name, &hash).await.map_err(email_err)?;
|
||||||
|
if is_admin {
|
||||||
|
crate::db::update_user(&pool, id, &name, &email, true).await.map_err(db_err)?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An empty `password` keeps the current one.
|
||||||
|
#[server]
|
||||||
|
pub async fn update_account(
|
||||||
|
id: i64,
|
||||||
|
name: String,
|
||||||
|
email: String,
|
||||||
|
password: String,
|
||||||
|
is_admin: bool,
|
||||||
|
) -> Result<(), ServerFnError> {
|
||||||
|
use server::*;
|
||||||
|
let pool = pool()?;
|
||||||
|
let admin = require_admin(&pool).await?;
|
||||||
|
if id == admin.id && !is_admin {
|
||||||
|
return Err(ServerFnError::new("Tu ne peux pas retirer tes propres droits d'administration."));
|
||||||
|
}
|
||||||
|
let name = clean_name(&name, 40)?;
|
||||||
|
let email = clean_email(&email)?;
|
||||||
|
if !password.is_empty() {
|
||||||
|
check_password(&password)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
crate::db::update_user(&pool, id, &name, &email, is_admin).await.map_err(email_err)?;
|
||||||
|
if !password.is_empty() {
|
||||||
|
let hash = hash(password).await?;
|
||||||
|
crate::db::set_password(&pool, id, &hash).await.map_err(db_err)?;
|
||||||
|
if id == admin.id {
|
||||||
|
// set_password signed every session out, this one included.
|
||||||
|
crate::auth::start_session(&pool, id).await.map_err(db_err)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Deletes the account and the lists it owns.
|
||||||
|
#[server]
|
||||||
|
pub async fn delete_account(id: i64) -> Result<(), ServerFnError> {
|
||||||
|
use server::*;
|
||||||
|
let pool = pool()?;
|
||||||
|
let admin = require_admin(&pool).await?;
|
||||||
|
if id == admin.id {
|
||||||
|
return Err(ServerFnError::new("Tu ne peux pas supprimer ton propre compte."));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Members of the lists it owns or shares see them change.
|
||||||
|
let mut users = Vec::new();
|
||||||
|
for list in crate::db::lists(&pool, id).await.map_err(db_err)? {
|
||||||
|
users.extend(audience(&pool, list.id).await?);
|
||||||
|
}
|
||||||
|
crate::db::delete_user(&pool, id).await.map_err(db_err)?;
|
||||||
|
users.sort_unstable();
|
||||||
|
users.dedup();
|
||||||
|
notify(users);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
// --- Lists ------------------------------------------------------------------
|
// --- Lists ------------------------------------------------------------------
|
||||||
|
|
||||||
#[server]
|
#[server]
|
||||||
@@ -268,47 +376,81 @@ pub async fn get_items(list_id: i64) -> Result<Vec<Item>, ServerFnError> {
|
|||||||
crate::db::items(&pool, list_id).await.map_err(db_err)
|
crate::db::items(&pool, list_id).await.map_err(db_err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Applies a batch of item changes queued by the browser. Changes to items
|
||||||
|
/// deleted meanwhile are dropped; invalid ones are skipped and reported.
|
||||||
#[server(input = Json)]
|
#[server(input = Json)]
|
||||||
pub async fn add_item(list_id: i64, input: ItemInput) -> Result<i64, ServerFnError> {
|
pub async fn sync_items(ops: Vec<ItemOp>) -> Result<SyncReport, ServerFnError> {
|
||||||
|
use crate::model::ItemInput;
|
||||||
use server::*;
|
use server::*;
|
||||||
let pool = pool()?;
|
let pool = pool()?;
|
||||||
let user = require_user(&pool).await?;
|
let user = require_user(&pool).await?;
|
||||||
require_list(&pool, &user, list_id).await?;
|
|
||||||
let input = ItemInput { name: clean_name(&input.name, 60)?, ..input };
|
|
||||||
let id = crate::db::add_item(&pool, user.id, list_id, &input).await.map_err(db_err)?;
|
|
||||||
notify_list(&pool, list_id).await?;
|
|
||||||
Ok(id)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[server(input = Json)]
|
// Lists checked so far, and whether the user can access them.
|
||||||
pub async fn update_item(id: i64, input: ItemInput) -> Result<(), ServerFnError> {
|
let mut access: Vec<(i64, bool)> = Vec::new();
|
||||||
use server::*;
|
// Temporary ids added in this batch, with their list.
|
||||||
let pool = pool()?;
|
let mut added: Vec<(i64, i64)> = Vec::new();
|
||||||
let user = require_user(&pool).await?;
|
let mut accepted = Vec::with_capacity(ops.len());
|
||||||
let list_id = require_item(&pool, &user, id).await?;
|
let mut rejected = None;
|
||||||
let input = ItemInput { name: clean_name(&input.name, 60)?, ..input };
|
for op in ops {
|
||||||
crate::db::update_item(&pool, id, &input).await.map_err(db_err)?;
|
let list_id = match &op {
|
||||||
notify_list(&pool, list_id).await
|
ItemOp::Add { id, list_id, .. } if *id < 0 => Some(*list_id),
|
||||||
}
|
ItemOp::Add { .. } => None,
|
||||||
|
op if op.id() < 0 => added.iter().find(|&&(temp, _)| temp == op.id()).map(|&(_, list)| list),
|
||||||
|
op => crate::db::item_list_id(&pool, op.id()).await.map_err(db_err)?,
|
||||||
|
};
|
||||||
|
let Some(list_id) = list_id else { continue };
|
||||||
|
let allowed = match access.iter().find(|&&(list, _)| list == list_id) {
|
||||||
|
Some(&(_, allowed)) => allowed,
|
||||||
|
None => {
|
||||||
|
let allowed = crate::db::list_role(&pool, user.id, list_id).await.map_err(db_err)?.is_some();
|
||||||
|
access.push((list_id, allowed));
|
||||||
|
allowed
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if !allowed {
|
||||||
|
if matches!(op, ItemOp::Add { .. }) {
|
||||||
|
rejected.get_or_insert_with(|| "Liste introuvable.".to_owned());
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
#[server]
|
let op = match op {
|
||||||
pub async fn delete_item(id: i64) -> Result<(), ServerFnError> {
|
ItemOp::Add { id, list_id, input } => match clean_name(&input.name, 60) {
|
||||||
use server::*;
|
Ok(name) => ItemOp::Add { id, list_id, input: ItemInput { name, ..input } },
|
||||||
let pool = pool()?;
|
Err(err) => {
|
||||||
let user = require_user(&pool).await?;
|
rejected.get_or_insert(message(err));
|
||||||
let list_id = require_item(&pool, &user, id).await?;
|
continue;
|
||||||
crate::db::delete_item(&pool, id).await.map_err(db_err)?;
|
}
|
||||||
notify_list(&pool, list_id).await
|
},
|
||||||
}
|
ItemOp::Update { id, input } => match clean_name(&input.name, 60) {
|
||||||
|
Ok(name) => ItemOp::Update { id, input: ItemInput { name, ..input } },
|
||||||
|
Err(err) => {
|
||||||
|
rejected.get_or_insert(message(err));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
op => op,
|
||||||
|
};
|
||||||
|
if let ItemOp::Add { id, list_id, .. } = op {
|
||||||
|
added.push((id, list_id));
|
||||||
|
}
|
||||||
|
accepted.push(op);
|
||||||
|
}
|
||||||
|
|
||||||
#[server]
|
if accepted.is_empty() {
|
||||||
pub async fn set_checked(id: i64, checked: bool) -> Result<(), ServerFnError> {
|
return Ok(SyncReport { created: Vec::new(), rejected });
|
||||||
use server::*;
|
}
|
||||||
let pool = pool()?;
|
let created = crate::db::apply_item_ops(&pool, user.id, &accepted).await.map_err(db_err)?;
|
||||||
let user = require_user(&pool).await?;
|
let mut users = Vec::new();
|
||||||
let list_id = require_item(&pool, &user, id).await?;
|
for &(list_id, allowed) in &access {
|
||||||
crate::db::set_checked(&pool, id, checked).await.map_err(db_err)?;
|
if allowed {
|
||||||
notify_list(&pool, list_id).await
|
users.extend(audience(&pool, list_id).await?);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
users.sort_unstable();
|
||||||
|
users.dedup();
|
||||||
|
notify(users);
|
||||||
|
Ok(SyncReport { created, rejected })
|
||||||
}
|
}
|
||||||
|
|
||||||
#[server]
|
#[server]
|
||||||
|
|||||||
+15
-3
@@ -97,7 +97,7 @@ fn AuthLayout(title: &'static str, children: Children) -> impl IntoView {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[component]
|
#[component]
|
||||||
fn FormError(#[prop(into)] error: Signal<Option<String>>) -> impl IntoView {
|
pub fn FormError(#[prop(into)] error: Signal<Option<String>>) -> impl IntoView {
|
||||||
move || {
|
move || {
|
||||||
error.get().map(|msg| {
|
error.get().map(|msg| {
|
||||||
view! {
|
view! {
|
||||||
@@ -207,7 +207,7 @@ pub fn RegisterPage() -> impl IntoView {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[component]
|
#[component]
|
||||||
fn Field(label: &'static str, children: Children) -> impl IntoView {
|
pub fn Field(label: &'static str, children: Children) -> impl IntoView {
|
||||||
view! {
|
view! {
|
||||||
<label class="flex flex-col gap-1.5">
|
<label class="flex flex-col gap-1.5">
|
||||||
<span class="font-mono text-xs tracking-[0.2em] text-ink/60 uppercase">{label}</span>
|
<span class="font-mono text-xs tracking-[0.2em] text-ink/60 uppercase">{label}</span>
|
||||||
@@ -241,7 +241,19 @@ pub fn AccountSheet(user: User) -> impl IntoView {
|
|||||||
<Show when=move || ctx.account_open.get()>
|
<Show when=move || ctx.account_open.get()>
|
||||||
<Sheet title=user.with_value(|u| u.name.clone()) on_close=close>
|
<Sheet title=user.with_value(|u| u.name.clone()) on_close=close>
|
||||||
<p class="mt-1 text-ink/70">{user.with_value(|u| u.email.clone())}</p>
|
<p class="mt-1 text-ink/70">{user.with_value(|u| u.email.clone())}</p>
|
||||||
<ActionForm action=auth.logout attr:class="mt-6">
|
{user
|
||||||
|
.with_value(|u| u.is_admin)
|
||||||
|
.then(|| {
|
||||||
|
view! {
|
||||||
|
<A
|
||||||
|
href="/admin"
|
||||||
|
attr:class="mt-6 block w-full rounded-2xl border-2 border-ink bg-lime px-4 py-3 text-center font-semibold"
|
||||||
|
>
|
||||||
|
"Gérer les utilisateurs"
|
||||||
|
</A>
|
||||||
|
}
|
||||||
|
})}
|
||||||
|
<ActionForm action=auth.logout attr:class="mt-3">
|
||||||
<button
|
<button
|
||||||
type="submit"
|
type="submit"
|
||||||
class="w-full rounded-2xl border-2 border-ink px-4 py-3 font-semibold"
|
class="w-full rounded-2xl border-2 border-ink px-4 py-3 font-semibold"
|
||||||
|
|||||||
@@ -0,0 +1,310 @@
|
|||||||
|
use leptos::ev;
|
||||||
|
use leptos::prelude::*;
|
||||||
|
use leptos::task::spawn_local;
|
||||||
|
use leptos_router::components::A;
|
||||||
|
|
||||||
|
use super::account::{Auth, Field, FormError, RequireUser};
|
||||||
|
use super::error_message;
|
||||||
|
use super::sheets::Sheet;
|
||||||
|
use crate::api::{create_account, delete_account, get_accounts, update_account};
|
||||||
|
use crate::model::{Account, User};
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
enum AccountEditor {
|
||||||
|
New,
|
||||||
|
Edit(User),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[component]
|
||||||
|
pub fn AdminPage() -> impl IntoView {
|
||||||
|
view! { <RequireUser render=|user| view! { <AdminView me=user /> } /> }
|
||||||
|
}
|
||||||
|
|
||||||
|
#[component]
|
||||||
|
fn AdminView(me: User) -> impl IntoView {
|
||||||
|
if !me.is_admin {
|
||||||
|
return view! {
|
||||||
|
<AdminLayout>
|
||||||
|
<section class="ticket relative mt-6 bg-paper px-5 pt-6 pb-8">
|
||||||
|
<p class="text-lg text-ink/70">"Cette page est réservée aux administrateurs."</p>
|
||||||
|
</section>
|
||||||
|
</AdminLayout>
|
||||||
|
}
|
||||||
|
.into_any();
|
||||||
|
}
|
||||||
|
|
||||||
|
let version = RwSignal::new(0);
|
||||||
|
let editor = RwSignal::new(None::<AccountEditor>);
|
||||||
|
let accounts = Resource::new(move || version.get(), |_| get_accounts());
|
||||||
|
let me_id = me.id;
|
||||||
|
|
||||||
|
view! {
|
||||||
|
<AdminLayout>
|
||||||
|
<section class="ticket relative mt-6 bg-paper px-5 pt-6 pb-8">
|
||||||
|
<p class="font-mono text-sm tracking-[0.2em] text-ink/60 uppercase">"Lisette · Comptes"</p>
|
||||||
|
<h2 class="mt-1 font-display text-[1.7rem] leading-tight font-bold tracking-tight">
|
||||||
|
"Utilisateurs"
|
||||||
|
</h2>
|
||||||
|
<Transition fallback=|| view! { <p class="mt-4 text-ink/50">"…"</p> }>
|
||||||
|
{move || Suspend::new(async move {
|
||||||
|
match accounts.await {
|
||||||
|
Ok(accounts) => view! { <AccountRows accounts me_id editor /> }.into_any(),
|
||||||
|
Err(err) => {
|
||||||
|
view! { <p class="mt-4 font-medium">{error_message(err)}</p> }.into_any()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})}
|
||||||
|
</Transition>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<button
|
||||||
|
class="tile-shadow fixed right-[max(1rem,calc(50vw-14rem+1rem))] bottom-[max(1.25rem,env(safe-area-inset-bottom))] z-10 rounded-2xl border-2 border-ink bg-pink px-6 py-4 font-display text-xl font-bold active:translate-y-1 active:shadow-none"
|
||||||
|
on:click=move |_| editor.set(Some(AccountEditor::New))
|
||||||
|
>
|
||||||
|
"+ compte"
|
||||||
|
</button>
|
||||||
|
</AdminLayout>
|
||||||
|
|
||||||
|
{move || {
|
||||||
|
editor
|
||||||
|
.get()
|
||||||
|
.map(|current| {
|
||||||
|
view! {
|
||||||
|
<AccountForm
|
||||||
|
editor=current
|
||||||
|
me_id
|
||||||
|
on_close=move || editor.set(None)
|
||||||
|
on_saved=move || version.update(|v| *v += 1)
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}}
|
||||||
|
}
|
||||||
|
.into_any()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[component]
|
||||||
|
fn AdminLayout(children: Children) -> impl IntoView {
|
||||||
|
view! {
|
||||||
|
<main class="mx-auto flex min-h-dvh max-w-md flex-col px-4 pt-[max(1.5rem,env(safe-area-inset-top))] pb-32">
|
||||||
|
<header class="flex items-start justify-between gap-4">
|
||||||
|
<h1 class="font-display text-5xl leading-[0.9] font-extrabold tracking-tight">"admin"</h1>
|
||||||
|
<A
|
||||||
|
href="/"
|
||||||
|
attr:class="shrink-0 rounded-2xl border-2 border-ink bg-paper px-4 py-3 font-semibold"
|
||||||
|
>
|
||||||
|
"← mes listes"
|
||||||
|
</A>
|
||||||
|
</header>
|
||||||
|
{children()}
|
||||||
|
</main>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[component]
|
||||||
|
fn AccountRows(
|
||||||
|
accounts: Vec<Account>,
|
||||||
|
me_id: i64,
|
||||||
|
editor: RwSignal<Option<AccountEditor>>,
|
||||||
|
) -> impl IntoView {
|
||||||
|
view! {
|
||||||
|
<p class="mt-1 text-lg text-ink/70">
|
||||||
|
{match accounts.len() {
|
||||||
|
1 => "1 compte.".to_owned(),
|
||||||
|
n => format!("{n} comptes."),
|
||||||
|
}}
|
||||||
|
</p>
|
||||||
|
<ul class="mt-5 flex flex-col gap-2">
|
||||||
|
{accounts
|
||||||
|
.into_iter()
|
||||||
|
.map(|Account { user, created_at }| {
|
||||||
|
let is_me = user.id == me_id;
|
||||||
|
let edited = user.clone();
|
||||||
|
view! {
|
||||||
|
<li>
|
||||||
|
<button
|
||||||
|
class="flex w-full items-center justify-between gap-3 rounded-xl bg-mist px-3 py-2 text-left active:bg-ink/10"
|
||||||
|
on:click=move |_| editor.set(Some(AccountEditor::Edit(edited.clone())))
|
||||||
|
>
|
||||||
|
<div class="min-w-0">
|
||||||
|
<p class="truncate font-semibold">
|
||||||
|
{user.name.clone()}
|
||||||
|
{is_me.then_some(" (toi)")}
|
||||||
|
</p>
|
||||||
|
<p class="truncate text-sm text-ink/60">{user.email.clone()}</p>
|
||||||
|
<p class="text-sm text-ink/50">{format!("Inscrit·e le {}", french_date(&created_at))}</p>
|
||||||
|
</div>
|
||||||
|
{user
|
||||||
|
.is_admin
|
||||||
|
.then(|| {
|
||||||
|
view! {
|
||||||
|
<span class="shrink-0 rounded-lg border-2 border-ink bg-lime px-2 py-0.5 font-mono text-xs uppercase">
|
||||||
|
"admin"
|
||||||
|
</span>
|
||||||
|
}
|
||||||
|
})}
|
||||||
|
</button>
|
||||||
|
</li>
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect_view()}
|
||||||
|
</ul>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[component]
|
||||||
|
fn AccountForm(
|
||||||
|
editor: AccountEditor,
|
||||||
|
me_id: i64,
|
||||||
|
on_close: impl Fn() + Copy + Send + Sync + 'static,
|
||||||
|
on_saved: impl Fn() + Copy + Send + Sync + 'static,
|
||||||
|
) -> impl IntoView {
|
||||||
|
let auth = expect_context::<Auth>();
|
||||||
|
let existing = match editor {
|
||||||
|
AccountEditor::Edit(user) => Some(user),
|
||||||
|
AccountEditor::New => None,
|
||||||
|
};
|
||||||
|
let user_id = existing.as_ref().map(|u| u.id);
|
||||||
|
let is_me = user_id == Some(me_id);
|
||||||
|
let name = RwSignal::new(
|
||||||
|
existing
|
||||||
|
.as_ref()
|
||||||
|
.map(|u| u.name.clone())
|
||||||
|
.unwrap_or_default(),
|
||||||
|
);
|
||||||
|
let email = RwSignal::new(
|
||||||
|
existing
|
||||||
|
.as_ref()
|
||||||
|
.map(|u| u.email.clone())
|
||||||
|
.unwrap_or_default(),
|
||||||
|
);
|
||||||
|
let password = RwSignal::new(String::new());
|
||||||
|
let is_admin = RwSignal::new(existing.as_ref().is_some_and(|u| u.is_admin));
|
||||||
|
let error = RwSignal::new(None::<String>);
|
||||||
|
let pending = RwSignal::new(false);
|
||||||
|
|
||||||
|
let run = move |call: std::pin::Pin<Box<dyn Future<Output = Result<(), ServerFnError>>>>| {
|
||||||
|
pending.set(true);
|
||||||
|
spawn_local(async move {
|
||||||
|
let result = call.await;
|
||||||
|
pending.set(false);
|
||||||
|
match result {
|
||||||
|
Ok(()) => {
|
||||||
|
if is_me {
|
||||||
|
// Name shown on the avatar.
|
||||||
|
auth.me.refetch();
|
||||||
|
}
|
||||||
|
on_saved();
|
||||||
|
on_close();
|
||||||
|
}
|
||||||
|
Err(err) => error.set(Some(error_message(err))),
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
let submit = move |ev: ev::SubmitEvent| {
|
||||||
|
ev.prevent_default();
|
||||||
|
let (name, email, password, is_admin) =
|
||||||
|
(name.get(), email.get(), password.get(), is_admin.get());
|
||||||
|
run(match user_id {
|
||||||
|
Some(id) => Box::pin(update_account(id, name, email, password, is_admin)),
|
||||||
|
None => Box::pin(create_account(name, email, password, is_admin)),
|
||||||
|
});
|
||||||
|
};
|
||||||
|
let delete = move |_| {
|
||||||
|
let Some(id) = user_id else { return };
|
||||||
|
let confirmed = window()
|
||||||
|
.confirm_with_message("Supprimer ce compte et toutes les listes qu'il possède ?")
|
||||||
|
.unwrap_or(false);
|
||||||
|
if confirmed {
|
||||||
|
run(Box::pin(delete_account(id)));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let title = if user_id.is_some() {
|
||||||
|
"Modifier le compte"
|
||||||
|
} else {
|
||||||
|
"Nouveau compte"
|
||||||
|
};
|
||||||
|
let password_label = if user_id.is_some() {
|
||||||
|
"Nouveau mot de passe (facultatif)"
|
||||||
|
} else {
|
||||||
|
"Mot de passe (8 caractères min.)"
|
||||||
|
};
|
||||||
|
|
||||||
|
view! {
|
||||||
|
<Sheet title=title.to_owned() on_close>
|
||||||
|
<form class="mt-4 flex flex-col gap-4" on:submit=submit>
|
||||||
|
<FormError error=error />
|
||||||
|
<Field label="Prénom ou pseudo">
|
||||||
|
<input class="field" required maxlength="40" autocomplete="off" bind:value=name />
|
||||||
|
</Field>
|
||||||
|
<Field label="Email">
|
||||||
|
<input class="field" type="email" required autocomplete="off" bind:value=email />
|
||||||
|
</Field>
|
||||||
|
<Field label=password_label>
|
||||||
|
<input
|
||||||
|
class="field"
|
||||||
|
type="password"
|
||||||
|
required=user_id.is_none()
|
||||||
|
minlength="8"
|
||||||
|
maxlength="128"
|
||||||
|
autocomplete="new-password"
|
||||||
|
bind:value=password
|
||||||
|
/>
|
||||||
|
</Field>
|
||||||
|
<label class="flex items-center gap-3 font-medium">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
class="size-6 accent-ink"
|
||||||
|
disabled=is_me
|
||||||
|
bind:checked=is_admin
|
||||||
|
/>
|
||||||
|
"Administrateur"
|
||||||
|
</label>
|
||||||
|
|
||||||
|
<div class="mt-2 flex gap-3">
|
||||||
|
{(user_id.is_some() && !is_me)
|
||||||
|
.then(|| {
|
||||||
|
view! {
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="rounded-2xl border-2 border-ink px-4 py-3 font-semibold"
|
||||||
|
disabled=move || pending.get()
|
||||||
|
on:click=delete
|
||||||
|
>
|
||||||
|
"Supprimer"
|
||||||
|
</button>
|
||||||
|
}
|
||||||
|
})}
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
class="tile-shadow flex-1 rounded-2xl border-2 border-ink bg-pink px-4 py-3 font-display text-lg font-bold active:translate-y-1 active:shadow-none disabled:opacity-60"
|
||||||
|
disabled=move || pending.get()
|
||||||
|
>
|
||||||
|
{if user_id.is_some() { "Enregistrer" } else { "Créer" }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</Sheet>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// "2026-10-07" → "07/10/2026".
|
||||||
|
fn french_date(iso: &str) -> String {
|
||||||
|
match iso.split('-').collect::<Vec<_>>().as_slice() {
|
||||||
|
[y, m, d] => format!("{d}/{m}/{y}"),
|
||||||
|
_ => iso.to_owned(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::french_date;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn formats_french_date() {
|
||||||
|
assert_eq!(french_date("2026-10-07"), "07/10/2026");
|
||||||
|
assert_eq!(french_date("garbage"), "garbage");
|
||||||
|
}
|
||||||
|
}
|
||||||
+51
-50
@@ -1,10 +1,12 @@
|
|||||||
mod account;
|
mod account;
|
||||||
|
mod admin;
|
||||||
mod icons;
|
mod icons;
|
||||||
mod live;
|
mod live;
|
||||||
mod sheets;
|
mod sheets;
|
||||||
|
mod sync;
|
||||||
mod tiles;
|
mod tiles;
|
||||||
|
mod transition;
|
||||||
|
|
||||||
use std::collections::HashMap;
|
|
||||||
use std::future::Future;
|
use std::future::Future;
|
||||||
|
|
||||||
use leptos::prelude::*;
|
use leptos::prelude::*;
|
||||||
@@ -15,9 +17,11 @@ use leptos_router::hooks::use_params_map;
|
|||||||
use leptos_router::path;
|
use leptos_router::path;
|
||||||
|
|
||||||
use crate::api::{get_items, get_lists, get_suggestions};
|
use crate::api::{get_items, get_lists, get_suggestions};
|
||||||
use crate::model::{Item, ShoppingList, Suggestion, User};
|
use crate::model::{Item, ItemOp, ShoppingList, Suggestion, User};
|
||||||
use account::{AccountSheet, Auth, LoginPage, RegisterPage, RequireUser};
|
use account::{AccountSheet, Auth, LoginPage, RegisterPage, RequireUser};
|
||||||
|
use admin::AdminPage;
|
||||||
use sheets::{ItemEditor, ItemSheet, ListEditor, ListSheet};
|
use sheets::{ItemEditor, ItemSheet, ListEditor, ListSheet};
|
||||||
|
use sync::Sync;
|
||||||
use tiles::{BasketTile, ItemTile, SuggestionTile};
|
use tiles::{BasketTile, ItemTile, SuggestionTile};
|
||||||
|
|
||||||
pub fn shell(options: LeptosOptions) -> impl IntoView {
|
pub fn shell(options: LeptosOptions) -> impl IntoView {
|
||||||
@@ -72,6 +76,7 @@ pub fn App() -> impl IntoView {
|
|||||||
<Route path=path!("/l/:id") view=ListsPage />
|
<Route path=path!("/l/:id") view=ListsPage />
|
||||||
<Route path=path!("/connexion") view=LoginPage />
|
<Route path=path!("/connexion") view=LoginPage />
|
||||||
<Route path=path!("/inscription") view=RegisterPage />
|
<Route path=path!("/inscription") view=RegisterPage />
|
||||||
|
<Route path=path!("/admin") view=AdminPage />
|
||||||
</Routes>
|
</Routes>
|
||||||
</Router>
|
</Router>
|
||||||
}
|
}
|
||||||
@@ -83,9 +88,8 @@ pub struct Ctx {
|
|||||||
/// Bumped after every mutation so resources refetch.
|
/// Bumped after every mutation so resources refetch.
|
||||||
refresh: RwSignal<u32>,
|
refresh: RwSignal<u32>,
|
||||||
error: RwSignal<Option<String>>,
|
error: RwSignal<Option<String>>,
|
||||||
/// Checked state applied before fresh data shows it, with the number of
|
/// Item changes waiting to be saved.
|
||||||
/// calls still in flight for that item.
|
sync: Sync,
|
||||||
optimistic: RwSignal<HashMap<i64, (bool, u32)>>,
|
|
||||||
item_editor: RwSignal<Option<ItemEditor>>,
|
item_editor: RwSignal<Option<ItemEditor>>,
|
||||||
list_editor: RwSignal<Option<ListEditor>>,
|
list_editor: RwSignal<Option<ListEditor>>,
|
||||||
account_open: RwSignal<bool>,
|
account_open: RwSignal<bool>,
|
||||||
@@ -120,27 +124,15 @@ impl Ctx {
|
|||||||
self.error.set(Some(msg));
|
self.error.set(Some(msg));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Shows the item change at once and saves it in the background.
|
||||||
|
fn change(self, op: ItemOp) {
|
||||||
|
self.sync.push(self, op);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Moves the item between the list and the basket, with an animation.
|
||||||
fn toggle(self, item: &Item) {
|
fn toggle(self, item: &Item) {
|
||||||
let (id, checked) = (item.id, !item.checked);
|
let op = ItemOp::SetChecked { id: item.id, checked: !item.checked };
|
||||||
self.optimistic.update(|map| {
|
transition::animate(move || self.change(op));
|
||||||
let in_flight = map.get(&id).map_or(0, |&(_, n)| n);
|
|
||||||
map.insert(id, (checked, in_flight + 1));
|
|
||||||
});
|
|
||||||
spawn_local(async move {
|
|
||||||
match crate::api::set_checked(id, checked).await {
|
|
||||||
Ok(()) => self.optimistic.update_untracked(|map| {
|
|
||||||
if let Some((_, in_flight)) = map.get_mut(&id) {
|
|
||||||
*in_flight -= 1;
|
|
||||||
}
|
|
||||||
}),
|
|
||||||
Err(err) => {
|
|
||||||
self.optimistic.update(|map| {
|
|
||||||
map.remove(&id);
|
|
||||||
});
|
|
||||||
self.report(err);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -161,7 +153,7 @@ fn ListsView(user: User) -> impl IntoView {
|
|||||||
let ctx = Ctx {
|
let ctx = Ctx {
|
||||||
refresh: RwSignal::new(0),
|
refresh: RwSignal::new(0),
|
||||||
error: RwSignal::new(None),
|
error: RwSignal::new(None),
|
||||||
optimistic: RwSignal::new(HashMap::new()),
|
sync: Sync::new(),
|
||||||
item_editor: RwSignal::new(None),
|
item_editor: RwSignal::new(None),
|
||||||
list_editor: RwSignal::new(None),
|
list_editor: RwSignal::new(None),
|
||||||
account_open: RwSignal::new(false),
|
account_open: RwSignal::new(false),
|
||||||
@@ -170,6 +162,7 @@ fn ListsView(user: User) -> impl IntoView {
|
|||||||
};
|
};
|
||||||
provide_context(ctx);
|
provide_context(ctx);
|
||||||
live::subscribe(ctx.refresh);
|
live::subscribe(ctx.refresh);
|
||||||
|
ctx.sync.flush_on_hide(ctx);
|
||||||
|
|
||||||
let params = use_params_map();
|
let params = use_params_map();
|
||||||
let active_id = Memo::new(move |_| {
|
let active_id = Memo::new(move |_| {
|
||||||
@@ -182,10 +175,14 @@ fn ListsView(user: User) -> impl IntoView {
|
|||||||
let lists = Resource::new(move || ctx.refresh.get(), |_| get_lists());
|
let lists = Resource::new(move || ctx.refresh.get(), |_| get_lists());
|
||||||
let items = Resource::new(
|
let items = Resource::new(
|
||||||
move || (active_id.get(), ctx.refresh.get()),
|
move || (active_id.get(), ctx.refresh.get()),
|
||||||
|(id, _)| async move {
|
move |(id, _)| {
|
||||||
|
// What the data will include, to drop the changes it shows.
|
||||||
|
let saved = ctx.sync.saved();
|
||||||
|
async move {
|
||||||
match id {
|
match id {
|
||||||
Some(id) => get_items(id).await,
|
Some(id) => get_items(id).await.map(|items| (items, saved)),
|
||||||
None => Ok(Vec::new()),
|
None => Ok((Vec::new(), saved)),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
@@ -215,6 +212,11 @@ fn ListsView(user: User) -> impl IntoView {
|
|||||||
</header>
|
</header>
|
||||||
|
|
||||||
<ErrorBanner />
|
<ErrorBanner />
|
||||||
|
<Show when=move || ctx.sync.offline()>
|
||||||
|
<p class="mt-4 rounded-2xl bg-paper/70 px-4 py-3 font-medium text-ink/70">
|
||||||
|
"Réseau indisponible : tes changements partiront dès que possible."
|
||||||
|
</p>
|
||||||
|
</Show>
|
||||||
|
|
||||||
<Transition fallback=|| view! { <TicketSkeleton /> }>
|
<Transition fallback=|| view! { <TicketSkeleton /> }>
|
||||||
<ErrorBoundary fallback=|errors| {
|
<ErrorBoundary fallback=|errors| {
|
||||||
@@ -229,10 +231,10 @@ fn ListsView(user: User) -> impl IntoView {
|
|||||||
}>
|
}>
|
||||||
{move || Suspend::new(async move {
|
{move || Suspend::new(async move {
|
||||||
let lists = lists.await?;
|
let lists = lists.await?;
|
||||||
let items = items.await?;
|
let (items, saved) = items.await?;
|
||||||
let suggestions = suggestions.await?;
|
let suggestions = suggestions.await?;
|
||||||
Ok::<_, ServerFnError>(view! {
|
Ok::<_, ServerFnError>(view! {
|
||||||
<ListsContent lists items suggestions active_id=active_id.get() />
|
<ListsContent lists items saved suggestions active_id=active_id.get() />
|
||||||
})
|
})
|
||||||
})}
|
})}
|
||||||
</ErrorBoundary>
|
</ErrorBoundary>
|
||||||
@@ -249,6 +251,8 @@ fn ListsView(user: User) -> impl IntoView {
|
|||||||
fn ListsContent(
|
fn ListsContent(
|
||||||
lists: Vec<ShoppingList>,
|
lists: Vec<ShoppingList>,
|
||||||
items: Vec<Item>,
|
items: Vec<Item>,
|
||||||
|
/// Batches of changes saved when `items` was fetched.
|
||||||
|
saved: u32,
|
||||||
suggestions: Vec<Suggestion>,
|
suggestions: Vec<Suggestion>,
|
||||||
active_id: Option<i64>,
|
active_id: Option<i64>,
|
||||||
) -> impl IntoView {
|
) -> impl IntoView {
|
||||||
@@ -272,29 +276,27 @@ fn ListsContent(
|
|||||||
.into_any();
|
.into_any();
|
||||||
};
|
};
|
||||||
|
|
||||||
// Fresh data includes every confirmed toggle: only keep pending ones, so
|
ctx.sync.settle(saved);
|
||||||
// changes made by others since are not masked.
|
|
||||||
ctx.optimistic
|
|
||||||
.update_untracked(|map| map.retain(|_, &mut (_, in_flight)| in_flight > 0));
|
|
||||||
|
|
||||||
// Items with pending checkbox changes applied, by category then name.
|
// Items with unsaved changes applied, by category then name.
|
||||||
let mut items = items;
|
|
||||||
items.sort_by_cached_key(Item::sort_key);
|
|
||||||
let items = StoredValue::new(items);
|
let items = StoredValue::new(items);
|
||||||
let current = Memo::new(move |_| {
|
let current = Memo::new(move |_| {
|
||||||
let optimistic = ctx.optimistic.get();
|
let mut items = items.with_value(|items| ctx.sync.apply(active_id, items));
|
||||||
items.with_value(|items| {
|
items.sort_by_cached_key(Item::sort_key);
|
||||||
items
|
items
|
||||||
|
});
|
||||||
|
// Hides a suggestion as soon as it is added.
|
||||||
|
let suggestions = StoredValue::new(suggestions);
|
||||||
|
let suggestions = Memo::new(move |_| {
|
||||||
|
current.with(|items| {
|
||||||
|
suggestions.with_value(|suggestions| {
|
||||||
|
suggestions
|
||||||
.iter()
|
.iter()
|
||||||
|
.filter(|s| !items.iter().any(|i| i.name.to_lowercase() == s.name.to_lowercase()))
|
||||||
.cloned()
|
.cloned()
|
||||||
.map(|mut item| {
|
|
||||||
if let Some(&(checked, _)) = optimistic.get(&item.id) {
|
|
||||||
item.checked = checked;
|
|
||||||
}
|
|
||||||
item
|
|
||||||
})
|
|
||||||
.collect::<Vec<_>>()
|
.collect::<Vec<_>>()
|
||||||
})
|
})
|
||||||
|
})
|
||||||
});
|
});
|
||||||
let to_get = Memo::new(move |_| {
|
let to_get = Memo::new(move |_| {
|
||||||
current.with(|items| {
|
current.with(|items| {
|
||||||
@@ -359,10 +361,9 @@ fn ListsContent(
|
|||||||
<For each=move || to_get.get() key=|item| (item.id, item.quantity.map(|q| q.label()), item.name.clone(), item.icon, item.category) let:item>
|
<For each=move || to_get.get() key=|item| (item.id, item.quantity.map(|q| q.label()), item.name.clone(), item.icon, item.category) let:item>
|
||||||
<ItemTile item />
|
<ItemTile item />
|
||||||
</For>
|
</For>
|
||||||
{suggestions
|
<For each=move || suggestions.get() key=|suggestion| suggestion.name.clone() let:suggestion>
|
||||||
.into_iter()
|
<SuggestionTile suggestion list_id=active_id />
|
||||||
.map(|suggestion| view! { <SuggestionTile suggestion list_id=active_id /> })
|
</For>
|
||||||
.collect_view()}
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<Show when=move || !in_basket.with(Vec::is_empty)>
|
<Show when=move || !in_basket.with(Vec::is_empty)>
|
||||||
|
|||||||
+8
-6
@@ -5,7 +5,7 @@ use leptos_router::hooks::use_navigate;
|
|||||||
use super::Ctx;
|
use super::Ctx;
|
||||||
use super::icons::{IconSvg, icon_label};
|
use super::icons::{IconSvg, icon_label};
|
||||||
use crate::api::get_members;
|
use crate::api::get_members;
|
||||||
use crate::model::{Category, Icon, Item, ItemInput, ListColor, Quantity, ShoppingList, Unit};
|
use crate::model::{Category, Icon, Item, ItemInput, ItemOp, ListColor, Quantity, ShoppingList, Unit};
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
pub enum ItemEditor {
|
pub enum ItemEditor {
|
||||||
@@ -86,14 +86,16 @@ fn ItemForm(editor: ItemEditor, list_id: i64) -> impl IntoView {
|
|||||||
icon: icon.get(),
|
icon: icon.get(),
|
||||||
category: category.get(),
|
category: category.get(),
|
||||||
};
|
};
|
||||||
match item_id {
|
ctx.change(match item_id {
|
||||||
Some(id) => ctx.mutate(crate::api::update_item(id, input), move |_| close()),
|
Some(id) => ItemOp::Update { id, input },
|
||||||
None => ctx.mutate(crate::api::add_item(list_id, input), move |_| close()),
|
None => ItemOp::Add { id: 0, list_id, input },
|
||||||
}
|
});
|
||||||
|
close();
|
||||||
};
|
};
|
||||||
let delete = move |_| {
|
let delete = move |_| {
|
||||||
if let Some(id) = item_id {
|
if let Some(id) = item_id {
|
||||||
ctx.mutate(crate::api::delete_item(id), move |_| close());
|
ctx.change(ItemOp::Delete { id });
|
||||||
|
close();
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
+323
@@ -0,0 +1,323 @@
|
|||||||
|
//! Item changes are shown at once and saved in the background: they wait in a
|
||||||
|
//! queue and leave in batches, one request at a time, so a slow mobile
|
||||||
|
//! connection never holds the interface back.
|
||||||
|
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use leptos::ev;
|
||||||
|
use leptos::prelude::*;
|
||||||
|
use leptos::task::spawn_local;
|
||||||
|
|
||||||
|
use super::Ctx;
|
||||||
|
use crate::model::{Item, ItemOp, SyncReport};
|
||||||
|
|
||||||
|
/// Changes made within this delay leave together.
|
||||||
|
const DEBOUNCE: Duration = Duration::from_millis(400);
|
||||||
|
const MAX_RETRY_DELAY: Duration = Duration::from_secs(30);
|
||||||
|
|
||||||
|
#[derive(Clone, Copy)]
|
||||||
|
pub struct Sync(RwSignal<State>);
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
struct State {
|
||||||
|
/// Changes not sent yet.
|
||||||
|
queue: Vec<ItemOp>,
|
||||||
|
/// Sent changes, shown until data fetched after they were saved has them.
|
||||||
|
sent: Vec<Batch>,
|
||||||
|
/// Batches saved so far.
|
||||||
|
saved: u32,
|
||||||
|
/// Real ids of items added here, by temporary id.
|
||||||
|
ids: Vec<(i64, i64)>,
|
||||||
|
/// Last temporary id handed out.
|
||||||
|
last_temp: i64,
|
||||||
|
/// A flush is planned.
|
||||||
|
scheduled: bool,
|
||||||
|
/// A batch is on its way; the next one waits for its answer.
|
||||||
|
sending: bool,
|
||||||
|
/// Failed attempts since the last batch got through.
|
||||||
|
retries: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Batch {
|
||||||
|
ops: Vec<ItemOp>,
|
||||||
|
/// Value of `saved` once this batch was saved.
|
||||||
|
saved_as: Option<u32>,
|
||||||
|
}
|
||||||
|
|
||||||
|
enum Outcome {
|
||||||
|
Saved(SyncReport),
|
||||||
|
Refused(ServerFnError),
|
||||||
|
Retry(Duration),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Sync {
|
||||||
|
pub fn new() -> Self {
|
||||||
|
Self(RwSignal::new(State::default()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sends what is left when the page is hidden: the phone may freeze it next.
|
||||||
|
pub fn flush_on_hide(self, ctx: Ctx) {
|
||||||
|
let handle = window_event_listener(ev::visibilitychange, move |_| {
|
||||||
|
if document().hidden() {
|
||||||
|
self.flush(ctx);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
on_cleanup(move || handle.remove());
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn push(self, ctx: Ctx, op: ItemOp) {
|
||||||
|
let schedule = self.0.try_update(|state| {
|
||||||
|
state.push(op);
|
||||||
|
!std::mem::replace(&mut state.scheduled, true)
|
||||||
|
});
|
||||||
|
if schedule == Some(true) {
|
||||||
|
set_timeout(move || self.flush(ctx), DEBOUNCE);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Saved batches so far: data fetched from now on includes them.
|
||||||
|
pub fn saved(self) -> u32 {
|
||||||
|
self.0.try_with_untracked(|state| state.saved).unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Forgets saved changes that data fetched when `saved` batches were
|
||||||
|
/// saved already shows, so changes made by others since are not masked.
|
||||||
|
pub fn settle(self, saved: u32) {
|
||||||
|
self.0.try_update_untracked(|state| {
|
||||||
|
state.sent.retain(|batch| batch.saved_as.is_none_or(|n| n > saved));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The list's items with the changes not saved or not fetched yet.
|
||||||
|
pub fn apply(self, list_id: i64, items: &[Item]) -> Vec<Item> {
|
||||||
|
let mut items = items.to_vec();
|
||||||
|
self.0.with(|state| {
|
||||||
|
let ops = state.sent.iter().flat_map(|batch| &batch.ops).chain(&state.queue);
|
||||||
|
for op in ops {
|
||||||
|
apply(&mut items, list_id, op);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
items
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The last attempt failed for lack of network; changes are kept.
|
||||||
|
pub fn offline(self) -> bool {
|
||||||
|
self.0.with(|state| state.retries > 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn flush(self, ctx: Ctx) {
|
||||||
|
let ops = self.0.try_update(|state| {
|
||||||
|
state.scheduled = false;
|
||||||
|
if state.sending || state.queue.is_empty() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let ops = std::mem::take(&mut state.queue);
|
||||||
|
state.sent.push(Batch { ops: ops.clone(), saved_as: None });
|
||||||
|
state.sending = true;
|
||||||
|
Some(ops)
|
||||||
|
});
|
||||||
|
let Some(Some(ops)) = ops else { return };
|
||||||
|
spawn_local(async move {
|
||||||
|
let result = crate::api::sync_items(ops).await;
|
||||||
|
self.answered(ctx, result);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
fn answered(self, ctx: Ctx, result: Result<SyncReport, ServerFnError>) {
|
||||||
|
let outcome = self.0.try_update(|state| {
|
||||||
|
state.sending = false;
|
||||||
|
let mut batch = state.sent.pop().expect("the batch sent is the last one");
|
||||||
|
match result {
|
||||||
|
Ok(report) => {
|
||||||
|
state.saved += 1;
|
||||||
|
batch.saved_as = Some(state.saved);
|
||||||
|
state.sent.push(batch);
|
||||||
|
state.resolve(&report.created);
|
||||||
|
state.retries = 0;
|
||||||
|
Outcome::Saved(report)
|
||||||
|
}
|
||||||
|
// Refused by the server: retrying would not help.
|
||||||
|
Err(err @ ServerFnError::ServerError(_)) => {
|
||||||
|
state.retries = 0;
|
||||||
|
Outcome::Refused(err)
|
||||||
|
}
|
||||||
|
// Not delivered, or the answer was lost: send it again later.
|
||||||
|
Err(_) => {
|
||||||
|
state.queue.splice(0..0, batch.ops);
|
||||||
|
state.retries += 1;
|
||||||
|
let delay = Duration::from_secs(1 << state.retries.min(5)).min(MAX_RETRY_DELAY);
|
||||||
|
Outcome::Retry(delay)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
match outcome {
|
||||||
|
None => {}
|
||||||
|
Some(Outcome::Saved(report)) => {
|
||||||
|
if let Some(msg) = report.rejected {
|
||||||
|
ctx.error.set(Some(msg));
|
||||||
|
}
|
||||||
|
ctx.refresh.update(|n| *n += 1);
|
||||||
|
self.flush(ctx);
|
||||||
|
}
|
||||||
|
Some(Outcome::Refused(err)) => {
|
||||||
|
ctx.report(err);
|
||||||
|
ctx.refresh.update(|n| *n += 1);
|
||||||
|
self.flush(ctx);
|
||||||
|
}
|
||||||
|
Some(Outcome::Retry(delay)) => set_timeout(move || self.flush(ctx), delay),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl State {
|
||||||
|
/// Queues the change, merged with the queued ones for the same item.
|
||||||
|
fn push(&mut self, mut op: ItemOp) {
|
||||||
|
if let ItemOp::Add { id, .. } = &mut op {
|
||||||
|
self.last_temp -= 1;
|
||||||
|
*id = self.last_temp;
|
||||||
|
} else if let Some(&(_, real)) = self.ids.iter().find(|&&(temp, _)| temp == op.id()) {
|
||||||
|
// Still open in an editor from before the item was saved.
|
||||||
|
*op.id_mut() = real;
|
||||||
|
}
|
||||||
|
|
||||||
|
let id = op.id();
|
||||||
|
let queued_add = self.queue.iter().position(|q| matches!(q, ItemOp::Add { id: added, .. } if *added == id));
|
||||||
|
match (op, queued_add) {
|
||||||
|
(ItemOp::Delete { .. }, Some(_)) => self.queue.retain(|q| q.id() != id),
|
||||||
|
(ItemOp::Update { input, .. }, Some(index)) => {
|
||||||
|
if let ItemOp::Add { input: added, .. } = &mut self.queue[index] {
|
||||||
|
*added = input;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
(op @ ItemOp::Delete { .. }, None) => {
|
||||||
|
self.queue.retain(|q| q.id() != id);
|
||||||
|
self.queue.push(op);
|
||||||
|
}
|
||||||
|
(op @ (ItemOp::Update { .. } | ItemOp::SetChecked { .. }), _) => {
|
||||||
|
let same_kind = std::mem::discriminant(&op);
|
||||||
|
self.queue.retain(|q| q.id() != id || std::mem::discriminant(q) != same_kind);
|
||||||
|
self.queue.push(op);
|
||||||
|
}
|
||||||
|
(op, _) => self.queue.push(op),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Swaps temporary ids for the ones the server gave.
|
||||||
|
fn resolve(&mut self, created: &[(i64, i64)]) {
|
||||||
|
let ops = self.queue.iter_mut().chain(self.sent.iter_mut().flat_map(|batch| &mut batch.ops));
|
||||||
|
for op in ops {
|
||||||
|
if let Some(&(_, real)) = created.iter().find(|&&(temp, _)| temp == op.id()) {
|
||||||
|
*op.id_mut() = real;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.ids.extend_from_slice(created);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn apply(items: &mut Vec<Item>, list_id: i64, op: &ItemOp) {
|
||||||
|
fn find(items: &mut [Item], id: i64) -> Option<&mut Item> {
|
||||||
|
items.iter_mut().find(|item| item.id == id)
|
||||||
|
}
|
||||||
|
match op {
|
||||||
|
ItemOp::Add { id, list_id: list, input } => {
|
||||||
|
if *list == list_id && !items.iter().any(|item| item.id == *id) {
|
||||||
|
items.push(Item {
|
||||||
|
id: *id,
|
||||||
|
list_id,
|
||||||
|
name: input.name.clone(),
|
||||||
|
quantity: input.quantity,
|
||||||
|
icon: input.icon,
|
||||||
|
category: input.category,
|
||||||
|
checked: false,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ItemOp::Update { id, input } => {
|
||||||
|
if let Some(item) = find(items, *id) {
|
||||||
|
item.name = input.name.clone();
|
||||||
|
item.quantity = input.quantity;
|
||||||
|
item.icon = input.icon;
|
||||||
|
item.category = input.category;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ItemOp::Delete { id } => items.retain(|item| item.id != *id),
|
||||||
|
ItemOp::SetChecked { id, checked } => {
|
||||||
|
if let Some(item) = find(items, *id) {
|
||||||
|
item.checked = *checked;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::model::{Category, Icon, ItemInput};
|
||||||
|
|
||||||
|
fn input(name: &str) -> ItemInput {
|
||||||
|
ItemInput { name: name.into(), quantity: None, icon: Icon::Basket, category: Category::Autre }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn add(name: &str) -> ItemOp {
|
||||||
|
ItemOp::Add { id: 0, list_id: 1, input: input(name) }
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn merges_queued_changes() {
|
||||||
|
let mut state = State::default();
|
||||||
|
state.push(ItemOp::SetChecked { id: 5, checked: true });
|
||||||
|
state.push(ItemOp::SetChecked { id: 5, checked: false });
|
||||||
|
state.push(add("Pain"));
|
||||||
|
state.push(ItemOp::Update { id: -1, input: input("Pain complet") });
|
||||||
|
assert_eq!(
|
||||||
|
state.queue,
|
||||||
|
[
|
||||||
|
ItemOp::SetChecked { id: 5, checked: false },
|
||||||
|
ItemOp::Add { id: -1, list_id: 1, input: input("Pain complet") },
|
||||||
|
]
|
||||||
|
);
|
||||||
|
|
||||||
|
state.push(ItemOp::Delete { id: -1 });
|
||||||
|
state.push(ItemOp::Delete { id: 5 });
|
||||||
|
assert_eq!(state.queue, [ItemOp::Delete { id: 5 }]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn resolves_temporary_ids() {
|
||||||
|
let mut state = State::default();
|
||||||
|
state.push(add("Pain"));
|
||||||
|
state.sent.push(Batch { ops: std::mem::take(&mut state.queue), saved_as: None });
|
||||||
|
state.push(ItemOp::SetChecked { id: -1, checked: true });
|
||||||
|
state.resolve(&[(-1, 42)]);
|
||||||
|
assert_eq!(state.queue, [ItemOp::SetChecked { id: 42, checked: true }]);
|
||||||
|
assert_eq!(state.sent[0].ops[0].id(), 42);
|
||||||
|
|
||||||
|
// An editor opened on the temporary item.
|
||||||
|
state.push(ItemOp::Delete { id: -1 });
|
||||||
|
assert_eq!(state.queue, [ItemOp::Delete { id: 42 }]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn applies_changes_to_fetched_items() {
|
||||||
|
let item = Item {
|
||||||
|
id: 7,
|
||||||
|
list_id: 1,
|
||||||
|
name: "Lait".into(),
|
||||||
|
quantity: None,
|
||||||
|
icon: Icon::Milk,
|
||||||
|
category: Category::Frais,
|
||||||
|
checked: false,
|
||||||
|
};
|
||||||
|
let mut items = vec![item];
|
||||||
|
apply(&mut items, 1, &ItemOp::SetChecked { id: 7, checked: true });
|
||||||
|
apply(&mut items, 1, &ItemOp::Add { id: -1, list_id: 1, input: input("Pain") });
|
||||||
|
apply(&mut items, 1, &ItemOp::Add { id: -2, list_id: 2, input: input("Ailleurs") });
|
||||||
|
assert!(items[0].checked);
|
||||||
|
assert_eq!(items.len(), 2);
|
||||||
|
|
||||||
|
// Already in the fetched data.
|
||||||
|
apply(&mut items, 1, &ItemOp::Add { id: 7, list_id: 1, input: input("Lait") });
|
||||||
|
apply(&mut items, 1, &ItemOp::Delete { id: -1 });
|
||||||
|
assert_eq!(items.len(), 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
+10
-5
@@ -2,8 +2,9 @@ use leptos::ev;
|
|||||||
use leptos::prelude::*;
|
use leptos::prelude::*;
|
||||||
|
|
||||||
use super::icons::IconSvg;
|
use super::icons::IconSvg;
|
||||||
|
use super::transition;
|
||||||
use super::{Ctx, ItemEditor};
|
use super::{Ctx, ItemEditor};
|
||||||
use crate::model::{Item, ItemInput, Suggestion};
|
use crate::model::{Item, ItemInput, ItemOp, Suggestion};
|
||||||
|
|
||||||
const LONG_PRESS_MS: u64 = 450;
|
const LONG_PRESS_MS: u64 = 450;
|
||||||
|
|
||||||
@@ -44,8 +45,8 @@ pub fn ItemTile(item: Item) -> impl IntoView {
|
|||||||
open_editor();
|
open_editor();
|
||||||
};
|
};
|
||||||
|
|
||||||
let (name, icon, category, badge) = item.with_value(|item| {
|
let (id, name, icon, category, badge) = item.with_value(|item| {
|
||||||
(item.name.clone(), item.icon, item.category, item.quantity.map(|q| q.label()))
|
(item.id, item.name.clone(), item.icon, item.category, item.quantity.map(|q| q.label()))
|
||||||
});
|
});
|
||||||
let aria_label = format!("{name} : mettre dans le panier");
|
let aria_label = format!("{name} : mettre dans le panier");
|
||||||
|
|
||||||
@@ -55,6 +56,7 @@ pub fn ItemTile(item: Item) -> impl IntoView {
|
|||||||
"tile-shadow relative flex aspect-square touch-manipulation flex-col items-center gap-1 rounded-2xl border-2 border-ink p-2 pb-2.5 text-center select-none active:translate-y-1 active:shadow-none [-webkit-touch-callout:none] {}",
|
"tile-shadow relative flex aspect-square touch-manipulation flex-col items-center gap-1 rounded-2xl border-2 border-ink p-2 pb-2.5 text-center select-none active:translate-y-1 active:shadow-none [-webkit-touch-callout:none] {}",
|
||||||
category.tile_class(),
|
category.tile_class(),
|
||||||
)
|
)
|
||||||
|
style:view-transition-name=transition::item_name(id)
|
||||||
aria-label=aria_label
|
aria-label=aria_label
|
||||||
on:click=on_click
|
on:click=on_click
|
||||||
on:contextmenu=on_context_menu
|
on:contextmenu=on_context_menu
|
||||||
@@ -85,15 +87,17 @@ pub fn SuggestionTile(suggestion: Suggestion, list_id: i64) -> impl IntoView {
|
|||||||
let ctx = expect_context::<Ctx>();
|
let ctx = expect_context::<Ctx>();
|
||||||
let Suggestion { name, icon, category } = suggestion;
|
let Suggestion { name, icon, category } = suggestion;
|
||||||
let label = format!("+ {name}");
|
let label = format!("+ {name}");
|
||||||
|
let transition_name = transition::suggestion_name(&name);
|
||||||
|
|
||||||
let add = move |_| {
|
let add = move |_| {
|
||||||
let input = ItemInput { name: name.clone(), quantity: None, icon, category };
|
let input = ItemInput { name: name.clone(), quantity: None, icon, category };
|
||||||
ctx.mutate(crate::api::add_item(list_id, input), |_| ());
|
ctx.change(ItemOp::Add { id: 0, list_id, input });
|
||||||
};
|
};
|
||||||
|
|
||||||
view! {
|
view! {
|
||||||
<button
|
<button
|
||||||
class="relative flex aspect-square flex-col items-center gap-1 rounded-2xl border-2 border-dashed border-ink/35 p-2 pb-2.5 text-center text-ink/55 active:bg-ink/5"
|
class="relative flex aspect-square flex-col items-center gap-1 rounded-2xl border-2 border-dashed border-ink/35 p-2 pb-2.5 text-center text-ink/55 active:bg-ink/5"
|
||||||
|
style:view-transition-name=transition_name
|
||||||
on:click=add
|
on:click=add
|
||||||
>
|
>
|
||||||
<IconSvg icon class="min-h-0 w-full flex-1 opacity-60" />
|
<IconSvg icon class="min-h-0 w-full flex-1 opacity-60" />
|
||||||
@@ -106,13 +110,14 @@ pub fn SuggestionTile(suggestion: Suggestion, list_id: i64) -> impl IntoView {
|
|||||||
#[component]
|
#[component]
|
||||||
pub fn BasketTile(item: Item) -> impl IntoView {
|
pub fn BasketTile(item: Item) -> impl IntoView {
|
||||||
let ctx = expect_context::<Ctx>();
|
let ctx = expect_context::<Ctx>();
|
||||||
let (name, icon) = (item.name.clone(), item.icon);
|
let (id, name, icon) = (item.id, item.name.clone(), item.icon);
|
||||||
let aria_label = format!("{name} : remettre dans la liste");
|
let aria_label = format!("{name} : remettre dans la liste");
|
||||||
let item = StoredValue::new(item);
|
let item = StoredValue::new(item);
|
||||||
|
|
||||||
view! {
|
view! {
|
||||||
<button
|
<button
|
||||||
class="flex aspect-square flex-col items-center gap-0.5 rounded-2xl bg-mist p-1.5 text-center text-ink/45 active:bg-ink/10"
|
class="flex aspect-square flex-col items-center gap-0.5 rounded-2xl bg-mist p-1.5 text-center text-ink/45 active:bg-ink/10"
|
||||||
|
style:view-transition-name=transition::item_name(id)
|
||||||
aria-label=aria_label
|
aria-label=aria_label
|
||||||
on:click=move |_| item.with_value(|item| ctx.toggle(item))
|
on:click=move |_| item.with_value(|item| ctx.toggle(item))
|
||||||
>
|
>
|
||||||
|
|||||||
@@ -0,0 +1,50 @@
|
|||||||
|
//! Animated DOM updates: tiles carrying a `view-transition-name` glide from
|
||||||
|
//! their old place to their new one, even across lists.
|
||||||
|
|
||||||
|
/// Runs `update` inside a view transition, or right away when the browser
|
||||||
|
/// does not support them.
|
||||||
|
pub fn animate(update: impl FnOnce() + 'static) {
|
||||||
|
#[cfg(feature = "hydrate")]
|
||||||
|
browser::animate(update);
|
||||||
|
#[cfg(not(feature = "hydrate"))]
|
||||||
|
update();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `view-transition-name` of an item tile, the same in both lists.
|
||||||
|
pub fn item_name(id: i64) -> String {
|
||||||
|
format!("item-{id}")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `view-transition-name` of a suggestion tile. Product names may contain
|
||||||
|
/// spaces or accents, which are not allowed in an identifier: hex-encode them.
|
||||||
|
pub fn suggestion_name(name: &str) -> String {
|
||||||
|
let hex: String = name.bytes().map(|b| format!("{b:02x}")).collect();
|
||||||
|
format!("suggestion-{hex}")
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "hydrate")]
|
||||||
|
mod browser {
|
||||||
|
use js_sys::{Function, Promise, Reflect};
|
||||||
|
use leptos::prelude::*;
|
||||||
|
use wasm_bindgen::JsCast;
|
||||||
|
use wasm_bindgen::closure::Closure;
|
||||||
|
|
||||||
|
pub fn animate(update: impl FnOnce() + 'static) {
|
||||||
|
let document = document();
|
||||||
|
let start = Reflect::get(&document, &"startViewTransition".into())
|
||||||
|
.ok()
|
||||||
|
.and_then(|start| start.dyn_into::<Function>().ok());
|
||||||
|
let Some(start) = start else {
|
||||||
|
return update();
|
||||||
|
};
|
||||||
|
let callback = Closure::once_into_js(move || {
|
||||||
|
update();
|
||||||
|
// Leptos patches the DOM in a microtask: the new state is
|
||||||
|
// ready by the next timeout.
|
||||||
|
Promise::new(&mut |resolve, _| {
|
||||||
|
let _ = window().set_timeout_with_callback(&resolve);
|
||||||
|
})
|
||||||
|
});
|
||||||
|
let _ = start.call1(&document, &callback);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,7 +3,7 @@ use sqlx::{Row, SqliteConnection};
|
|||||||
use std::str::FromStr;
|
use std::str::FromStr;
|
||||||
|
|
||||||
use crate::model::{
|
use crate::model::{
|
||||||
Category, Icon, Item, ItemInput, ListColor, Member, Quantity, ShoppingList, Suggestion, Unit, User,
|
Account, Category, Icon, Item, ItemInput, ItemOp, ListColor, Member, Quantity, ShoppingList, Suggestion, Unit, User,
|
||||||
};
|
};
|
||||||
|
|
||||||
pub async fn connect(url: &str) -> Result<SqlitePool, sqlx::Error> {
|
pub async fn connect(url: &str) -> Result<SqlitePool, sqlx::Error> {
|
||||||
@@ -61,6 +61,7 @@ fn user_from_row(row: &SqliteRow) -> Result<User, sqlx::Error> {
|
|||||||
id: row.try_get("id")?,
|
id: row.try_get("id")?,
|
||||||
name: row.try_get("name")?,
|
name: row.try_get("name")?,
|
||||||
email: row.try_get("email")?,
|
email: row.try_get("email")?,
|
||||||
|
is_admin: row.try_get("is_admin")?,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -76,11 +77,14 @@ const STARTER_CATALOG: &[(&str, Icon, Category)] = &[
|
|||||||
("Café en grains", Icon::Coffee, Category::Epicerie),
|
("Café en grains", Icon::Coffee, Category::Epicerie),
|
||||||
];
|
];
|
||||||
|
|
||||||
/// Creates the account with a first list and starter suggestions.
|
/// Creates the account with a first list and starter suggestions; the very
|
||||||
/// Fails with a unique violation if the email is taken.
|
/// first account is an admin. Fails with a unique violation if the email is taken.
|
||||||
pub async fn register(pool: &SqlitePool, email: &str, name: &str, password_hash: &str) -> Result<i64, sqlx::Error> {
|
pub async fn register(pool: &SqlitePool, email: &str, name: &str, password_hash: &str) -> Result<i64, sqlx::Error> {
|
||||||
let mut tx = pool.begin().await?;
|
let mut tx = pool.begin().await?;
|
||||||
let user_id: i64 = sqlx::query("INSERT INTO users (email, name, password_hash) VALUES (?, ?, ?) RETURNING id")
|
let user_id: i64 = sqlx::query(
|
||||||
|
"INSERT INTO users (email, name, password_hash, is_admin)
|
||||||
|
VALUES (?, ?, ?, NOT EXISTS (SELECT 1 FROM users)) RETURNING id",
|
||||||
|
)
|
||||||
.bind(email)
|
.bind(email)
|
||||||
.bind(name)
|
.bind(name)
|
||||||
.bind(password_hash)
|
.bind(password_hash)
|
||||||
@@ -113,7 +117,7 @@ pub async fn register(pool: &SqlitePool, email: &str, name: &str, password_hash:
|
|||||||
|
|
||||||
/// The user and their password hash.
|
/// The user and their password hash.
|
||||||
pub async fn user_by_email(pool: &SqlitePool, email: &str) -> Result<Option<(User, String)>, sqlx::Error> {
|
pub async fn user_by_email(pool: &SqlitePool, email: &str) -> Result<Option<(User, String)>, sqlx::Error> {
|
||||||
sqlx::query("SELECT id, name, email, password_hash FROM users WHERE email = ?")
|
sqlx::query("SELECT id, name, email, is_admin, password_hash FROM users WHERE email = ?")
|
||||||
.bind(email)
|
.bind(email)
|
||||||
.fetch_optional(pool)
|
.fetch_optional(pool)
|
||||||
.await?
|
.await?
|
||||||
@@ -136,7 +140,7 @@ pub async fn create_session(pool: &SqlitePool, token_hash: &str, user_id: i64, d
|
|||||||
|
|
||||||
pub async fn user_by_session(pool: &SqlitePool, token_hash: &str) -> Result<Option<User>, sqlx::Error> {
|
pub async fn user_by_session(pool: &SqlitePool, token_hash: &str) -> Result<Option<User>, sqlx::Error> {
|
||||||
sqlx::query(
|
sqlx::query(
|
||||||
"SELECT u.id, u.name, u.email FROM sessions s JOIN users u ON u.id = s.user_id
|
"SELECT u.id, u.name, u.email, u.is_admin FROM sessions s JOIN users u ON u.id = s.user_id
|
||||||
WHERE s.token_hash = ? AND s.expires_at > datetime('now')",
|
WHERE s.token_hash = ? AND s.expires_at > datetime('now')",
|
||||||
)
|
)
|
||||||
.bind(token_hash)
|
.bind(token_hash)
|
||||||
@@ -155,6 +159,57 @@ pub async fn delete_session(pool: &SqlitePool, token_hash: &str) -> Result<(), s
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- Administration ---------------------------------------------------------
|
||||||
|
|
||||||
|
pub async fn has_users(pool: &SqlitePool) -> Result<bool, sqlx::Error> {
|
||||||
|
sqlx::query("SELECT EXISTS (SELECT 1 FROM users) AS has_users")
|
||||||
|
.fetch_one(pool)
|
||||||
|
.await?
|
||||||
|
.try_get("has_users")
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn accounts(pool: &SqlitePool) -> Result<Vec<Account>, sqlx::Error> {
|
||||||
|
sqlx::query("SELECT id, name, email, is_admin, date(created_at) AS created_at FROM users ORDER BY id")
|
||||||
|
.fetch_all(pool)
|
||||||
|
.await?
|
||||||
|
.iter()
|
||||||
|
.map(|row| Ok(Account { user: user_from_row(row)?, created_at: row.try_get("created_at")? }))
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Fails with a unique violation if the email is taken.
|
||||||
|
pub async fn update_user(pool: &SqlitePool, id: i64, name: &str, email: &str, is_admin: bool) -> Result<(), sqlx::Error> {
|
||||||
|
sqlx::query("UPDATE users SET name = ?, email = ?, is_admin = ? WHERE id = ?")
|
||||||
|
.bind(name)
|
||||||
|
.bind(email)
|
||||||
|
.bind(is_admin)
|
||||||
|
.bind(id)
|
||||||
|
.execute(pool)
|
||||||
|
.await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Changes the password and signs the user out everywhere.
|
||||||
|
pub async fn set_password(pool: &SqlitePool, id: i64, password_hash: &str) -> Result<(), sqlx::Error> {
|
||||||
|
let mut tx = pool.begin().await?;
|
||||||
|
sqlx::query("UPDATE users SET password_hash = ? WHERE id = ?")
|
||||||
|
.bind(password_hash)
|
||||||
|
.bind(id)
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
sqlx::query("DELETE FROM sessions WHERE user_id = ?")
|
||||||
|
.bind(id)
|
||||||
|
.execute(&mut *tx)
|
||||||
|
.await?;
|
||||||
|
tx.commit().await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Deletes the account with its sessions, suggestions and the lists it owns.
|
||||||
|
pub async fn delete_user(pool: &SqlitePool, id: i64) -> Result<(), sqlx::Error> {
|
||||||
|
sqlx::query("DELETE FROM users WHERE id = ?").bind(id).execute(pool).await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
// --- Lists & sharing --------------------------------------------------------
|
// --- Lists & sharing --------------------------------------------------------
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
@@ -226,7 +281,7 @@ pub async fn delete_list(pool: &SqlitePool, id: i64) -> Result<(), sqlx::Error>
|
|||||||
|
|
||||||
pub async fn members(pool: &SqlitePool, list_id: i64) -> Result<Vec<Member>, sqlx::Error> {
|
pub async fn members(pool: &SqlitePool, list_id: i64) -> Result<Vec<Member>, sqlx::Error> {
|
||||||
sqlx::query(
|
sqlx::query(
|
||||||
"SELECT u.id, u.name, u.email FROM list_members m JOIN users u ON u.id = m.user_id
|
"SELECT u.id, u.name, u.email, u.is_admin FROM list_members m JOIN users u ON u.id = m.user_id
|
||||||
WHERE m.list_id = ? ORDER BY u.name",
|
WHERE m.list_id = ? ORDER BY u.name",
|
||||||
)
|
)
|
||||||
.bind(list_id)
|
.bind(list_id)
|
||||||
@@ -297,7 +352,7 @@ pub async fn item_list_id(pool: &SqlitePool, item_id: i64) -> Result<Option<i64>
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Remembers the product in the user's catalog so it can be suggested later.
|
/// Remembers the product in the user's catalog so it can be suggested later.
|
||||||
async fn record_in_catalog(pool: &SqlitePool, user_id: i64, input: &ItemInput) -> Result<(), sqlx::Error> {
|
async fn record_in_catalog(conn: &mut SqliteConnection, user_id: i64, input: &ItemInput) -> Result<(), sqlx::Error> {
|
||||||
sqlx::query(
|
sqlx::query(
|
||||||
"INSERT INTO catalog (user_id, name, icon, category, use_count) VALUES (?, ?, ?, ?, 1)
|
"INSERT INTO catalog (user_id, name, icon, category, use_count) VALUES (?, ?, ?, ?, 1)
|
||||||
ON CONFLICT(user_id, name) DO UPDATE SET
|
ON CONFLICT(user_id, name) DO UPDATE SET
|
||||||
@@ -309,12 +364,12 @@ async fn record_in_catalog(pool: &SqlitePool, user_id: i64, input: &ItemInput) -
|
|||||||
.bind(&input.name)
|
.bind(&input.name)
|
||||||
.bind(input.icon.as_str())
|
.bind(input.icon.as_str())
|
||||||
.bind(input.category.as_str())
|
.bind(input.category.as_str())
|
||||||
.execute(pool)
|
.execute(&mut *conn)
|
||||||
.await?;
|
.await?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn add_item(pool: &SqlitePool, user_id: i64, list_id: i64, input: &ItemInput) -> Result<i64, sqlx::Error> {
|
async fn add_item(conn: &mut SqliteConnection, user_id: i64, list_id: i64, input: &ItemInput) -> Result<i64, sqlx::Error> {
|
||||||
let row = sqlx::query(
|
let row = sqlx::query(
|
||||||
"INSERT INTO items (list_id, name, amount, unit, icon, category)
|
"INSERT INTO items (list_id, name, amount, unit, icon, category)
|
||||||
VALUES (?, ?, ?, ?, ?, ?) RETURNING id",
|
VALUES (?, ?, ?, ?, ?, ?) RETURNING id",
|
||||||
@@ -325,13 +380,13 @@ pub async fn add_item(pool: &SqlitePool, user_id: i64, list_id: i64, input: &Ite
|
|||||||
.bind(input.quantity.map(|q| q.unit.as_str()))
|
.bind(input.quantity.map(|q| q.unit.as_str()))
|
||||||
.bind(input.icon.as_str())
|
.bind(input.icon.as_str())
|
||||||
.bind(input.category.as_str())
|
.bind(input.category.as_str())
|
||||||
.fetch_one(pool)
|
.fetch_one(&mut *conn)
|
||||||
.await?;
|
.await?;
|
||||||
record_in_catalog(pool, user_id, input).await?;
|
record_in_catalog(conn, user_id, input).await?;
|
||||||
row.try_get("id")
|
row.try_get("id")
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn update_item(pool: &SqlitePool, id: i64, input: &ItemInput) -> Result<(), sqlx::Error> {
|
async fn update_item(conn: &mut SqliteConnection, id: i64, input: &ItemInput) -> Result<(), sqlx::Error> {
|
||||||
sqlx::query(
|
sqlx::query(
|
||||||
"UPDATE items SET name = ?, amount = ?, unit = ?, icon = ?, category = ? WHERE id = ?",
|
"UPDATE items SET name = ?, amount = ?, unit = ?, icon = ?, category = ? WHERE id = ?",
|
||||||
)
|
)
|
||||||
@@ -341,25 +396,49 @@ pub async fn update_item(pool: &SqlitePool, id: i64, input: &ItemInput) -> Resul
|
|||||||
.bind(input.icon.as_str())
|
.bind(input.icon.as_str())
|
||||||
.bind(input.category.as_str())
|
.bind(input.category.as_str())
|
||||||
.bind(id)
|
.bind(id)
|
||||||
.execute(pool)
|
.execute(conn)
|
||||||
.await?;
|
.await?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn delete_item(pool: &SqlitePool, id: i64) -> Result<(), sqlx::Error> {
|
async fn delete_item(conn: &mut SqliteConnection, id: i64) -> Result<(), sqlx::Error> {
|
||||||
sqlx::query("DELETE FROM items WHERE id = ?").bind(id).execute(pool).await?;
|
sqlx::query("DELETE FROM items WHERE id = ?").bind(id).execute(conn).await?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn set_checked(pool: &SqlitePool, id: i64, checked: bool) -> Result<(), sqlx::Error> {
|
async fn set_checked(conn: &mut SqliteConnection, id: i64, checked: bool) -> Result<(), sqlx::Error> {
|
||||||
sqlx::query("UPDATE items SET checked = ? WHERE id = ?")
|
sqlx::query("UPDATE items SET checked = ? WHERE id = ?")
|
||||||
.bind(checked)
|
.bind(checked)
|
||||||
.bind(id)
|
.bind(id)
|
||||||
.execute(pool)
|
.execute(conn)
|
||||||
.await?;
|
.await?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Applies the changes, in order, in one transaction. Ops may target items
|
||||||
|
/// added earlier in the batch by their temporary id; returns the
|
||||||
|
/// (temporary id, real id) of each added item.
|
||||||
|
pub async fn apply_item_ops(pool: &SqlitePool, user_id: i64, ops: &[ItemOp]) -> Result<Vec<(i64, i64)>, sqlx::Error> {
|
||||||
|
let mut tx = pool.begin().await?;
|
||||||
|
let mut created: Vec<(i64, i64)> = Vec::new();
|
||||||
|
for op in ops {
|
||||||
|
let id = created
|
||||||
|
.iter()
|
||||||
|
.find(|&&(temp, _)| temp == op.id())
|
||||||
|
.map_or(op.id(), |&(_, real)| real);
|
||||||
|
match op {
|
||||||
|
ItemOp::Add { id: temp, list_id, input } => {
|
||||||
|
created.push((*temp, add_item(&mut tx, user_id, *list_id, input).await?));
|
||||||
|
}
|
||||||
|
ItemOp::Update { input, .. } => update_item(&mut tx, id, input).await?,
|
||||||
|
ItemOp::Delete { .. } => delete_item(&mut tx, id).await?,
|
||||||
|
ItemOp::SetChecked { checked, .. } => set_checked(&mut tx, id, *checked).await?,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tx.commit().await?;
|
||||||
|
Ok(created)
|
||||||
|
}
|
||||||
|
|
||||||
/// The user's most used products not already on the list.
|
/// The user's most used products not already on the list.
|
||||||
pub async fn suggestions(pool: &SqlitePool, user_id: i64, list_id: i64, limit: i64) -> Result<Vec<Suggestion>, sqlx::Error> {
|
pub async fn suggestions(pool: &SqlitePool, user_id: i64, list_id: i64, limit: i64) -> Result<Vec<Suggestion>, sqlx::Error> {
|
||||||
sqlx::query(
|
sqlx::query(
|
||||||
@@ -394,6 +473,11 @@ mod tests {
|
|||||||
connect("sqlite::memory:").await.unwrap()
|
connect("sqlite::memory:").await.unwrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The in-memory pool has a single connection: drop it before using the pool.
|
||||||
|
async fn conn(pool: &SqlitePool) -> sqlx::pool::PoolConnection<sqlx::Sqlite> {
|
||||||
|
pool.acquire().await.unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
async fn user(pool: &SqlitePool, email: &str) -> i64 {
|
async fn user(pool: &SqlitePool, email: &str) -> i64 {
|
||||||
register(pool, email, "Test", "hash").await.unwrap()
|
register(pool, email, "Test", "hash").await.unwrap()
|
||||||
}
|
}
|
||||||
@@ -462,28 +546,53 @@ mod tests {
|
|||||||
let me = user(&pool, "a@x.fr").await;
|
let me = user(&pool, "a@x.fr").await;
|
||||||
let list = lists(&pool, me).await.unwrap()[0].id;
|
let list = lists(&pool, me).await.unwrap()[0].id;
|
||||||
|
|
||||||
let id = add_item(&pool, me, list, &input("Avocats")).await.unwrap();
|
let id = add_item(&mut *conn(&pool).await, me, list, &input("Avocats")).await.unwrap();
|
||||||
assert_eq!(item_list_id(&pool, id).await.unwrap(), Some(list));
|
assert_eq!(item_list_id(&pool, id).await.unwrap(), Some(list));
|
||||||
let mut edited = input("Avocats");
|
let mut edited = input("Avocats");
|
||||||
edited.quantity = Some(Quantity { amount: 4.0, unit: Unit::Piece });
|
edited.quantity = Some(Quantity { amount: 4.0, unit: Unit::Piece });
|
||||||
update_item(&pool, id, &edited).await.unwrap();
|
update_item(&mut *conn(&pool).await, id, &edited).await.unwrap();
|
||||||
set_checked(&pool, id, true).await.unwrap();
|
set_checked(&mut *conn(&pool).await, id, true).await.unwrap();
|
||||||
|
|
||||||
let all = items(&pool, list).await.unwrap();
|
let all = items(&pool, list).await.unwrap();
|
||||||
assert_eq!(all.len(), 1);
|
assert_eq!(all.len(), 1);
|
||||||
assert_eq!(all[0].quantity.unwrap().label(), "×4");
|
assert_eq!(all[0].quantity.unwrap().label(), "×4");
|
||||||
assert!(all[0].checked);
|
assert!(all[0].checked);
|
||||||
|
|
||||||
delete_item(&pool, id).await.unwrap();
|
delete_item(&mut *conn(&pool).await, id).await.unwrap();
|
||||||
assert!(items(&pool, list).await.unwrap().is_empty());
|
assert!(items(&pool, list).await.unwrap().is_empty());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn batch_resolves_temporary_ids() {
|
||||||
|
let pool = pool().await;
|
||||||
|
let me = user(&pool, "a@x.fr").await;
|
||||||
|
let list = lists(&pool, me).await.unwrap()[0].id;
|
||||||
|
|
||||||
|
let mut edited = input("Pommes");
|
||||||
|
edited.quantity = None;
|
||||||
|
let ops = [
|
||||||
|
ItemOp::Add { id: -1, list_id: list, input: input("Pommes") },
|
||||||
|
ItemOp::Add { id: -2, list_id: list, input: input("Poires") },
|
||||||
|
ItemOp::Update { id: -1, input: edited },
|
||||||
|
ItemOp::SetChecked { id: -1, checked: true },
|
||||||
|
ItemOp::Delete { id: -2 },
|
||||||
|
];
|
||||||
|
let created = apply_item_ops(&pool, me, &ops).await.unwrap();
|
||||||
|
assert_eq!(created.len(), 2);
|
||||||
|
|
||||||
|
let all = items(&pool, list).await.unwrap();
|
||||||
|
assert_eq!(all.len(), 1);
|
||||||
|
assert_eq!(all[0].id, created[0].1);
|
||||||
|
assert_eq!(all[0].quantity, None);
|
||||||
|
assert!(all[0].checked);
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn suggestions_skip_items_on_list() {
|
async fn suggestions_skip_items_on_list() {
|
||||||
let pool = pool().await;
|
let pool = pool().await;
|
||||||
let me = user(&pool, "a@x.fr").await;
|
let me = user(&pool, "a@x.fr").await;
|
||||||
let list = lists(&pool, me).await.unwrap()[0].id;
|
let list = lists(&pool, me).await.unwrap()[0].id;
|
||||||
add_item(&pool, me, list, &input("beurre")).await.unwrap();
|
add_item(&mut *conn(&pool).await, me, list, &input("beurre")).await.unwrap();
|
||||||
|
|
||||||
let names: Vec<_> = suggestions(&pool, me, list, 3)
|
let names: Vec<_> = suggestions(&pool, me, list, 3)
|
||||||
.await
|
.await
|
||||||
@@ -500,7 +609,7 @@ mod tests {
|
|||||||
let pool = pool().await;
|
let pool = pool().await;
|
||||||
let me = user(&pool, "a@x.fr").await;
|
let me = user(&pool, "a@x.fr").await;
|
||||||
let list = create_list(&pool, me, "Apéro", ListColor::Pink).await.unwrap();
|
let list = create_list(&pool, me, "Apéro", ListColor::Pink).await.unwrap();
|
||||||
add_item(&pool, me, list, &input("Chips")).await.unwrap();
|
add_item(&mut *conn(&pool).await, me, list, &input("Chips")).await.unwrap();
|
||||||
delete_list(&pool, list).await.unwrap();
|
delete_list(&pool, list).await.unwrap();
|
||||||
assert!(items(&pool, list).await.unwrap().is_empty());
|
assert!(items(&pool, list).await.unwrap().is_empty());
|
||||||
}
|
}
|
||||||
|
|||||||
+45
-1
@@ -38,6 +38,8 @@ pub struct User {
|
|||||||
pub id: i64,
|
pub id: i64,
|
||||||
pub name: String,
|
pub name: String,
|
||||||
pub email: String,
|
pub email: String,
|
||||||
|
/// Can see and manage every account.
|
||||||
|
pub is_admin: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl User {
|
impl User {
|
||||||
@@ -53,6 +55,14 @@ impl User {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// An account as listed on the admin page.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||||
|
pub struct Account {
|
||||||
|
pub user: User,
|
||||||
|
/// "2026-10-07".
|
||||||
|
pub created_at: String,
|
||||||
|
}
|
||||||
|
|
||||||
/// Someone a list is shared with.
|
/// Someone a list is shared with.
|
||||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||||
pub struct Member {
|
pub struct Member {
|
||||||
@@ -279,6 +289,40 @@ pub struct ItemInput {
|
|||||||
pub category: Category,
|
pub category: Category,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A change to items, queued in the browser and sent to the server in batches.
|
||||||
|
/// Items added in the browser carry a negative temporary `id` until the
|
||||||
|
/// server gives them a real one.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||||
|
pub enum ItemOp {
|
||||||
|
Add { id: i64, list_id: i64, input: ItemInput },
|
||||||
|
Update { id: i64, input: ItemInput },
|
||||||
|
Delete { id: i64 },
|
||||||
|
SetChecked { id: i64, checked: bool },
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ItemOp {
|
||||||
|
pub fn id(&self) -> i64 {
|
||||||
|
match self {
|
||||||
|
ItemOp::Add { id, .. } | ItemOp::Update { id, .. } | ItemOp::Delete { id } | ItemOp::SetChecked { id, .. } => *id,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn id_mut(&mut self) -> &mut i64 {
|
||||||
|
match self {
|
||||||
|
ItemOp::Add { id, .. } | ItemOp::Update { id, .. } | ItemOp::Delete { id } | ItemOp::SetChecked { id, .. } => id,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the server did with a batch of [`ItemOp`]s.
|
||||||
|
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||||
|
pub struct SyncReport {
|
||||||
|
/// (temporary id, real id) of each item added.
|
||||||
|
pub created: Vec<(i64, i64)>,
|
||||||
|
/// Why some changes were refused, if any; the others were applied.
|
||||||
|
pub rejected: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
@@ -293,7 +337,7 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn initials() {
|
fn initials() {
|
||||||
let user = |name: &str| User { id: 1, name: name.into(), email: String::new() };
|
let user = |name: &str| User { id: 1, name: name.into(), email: String::new(), is_admin: false };
|
||||||
assert_eq!(user("Camille Lefèvre").initials(), "CL");
|
assert_eq!(user("Camille Lefèvre").initials(), "CL");
|
||||||
assert_eq!(user("romain").initials(), "RO");
|
assert_eq!(user("romain").initials(), "RO");
|
||||||
assert_eq!(user("élise").initials(), "ÉL");
|
assert_eq!(user("élise").initials(), "ÉL");
|
||||||
|
|||||||
@@ -55,3 +55,21 @@
|
|||||||
html {
|
html {
|
||||||
-webkit-tap-highlight-color: transparent;
|
-webkit-tap-highlight-color: transparent;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Tiles moving between the list and the basket (see src/app/transition.rs). */
|
||||||
|
::view-transition-group(*) {
|
||||||
|
animation-duration: 320ms;
|
||||||
|
animation-timing-function: cubic-bezier(0.2, 0.8, 0.2, 1);
|
||||||
|
}
|
||||||
|
::view-transition-old(*),
|
||||||
|
::view-transition-new(*) {
|
||||||
|
animation-duration: 200ms;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-reduced-motion: reduce) {
|
||||||
|
::view-transition-group(*),
|
||||||
|
::view-transition-old(*),
|
||||||
|
::view-transition-new(*) {
|
||||||
|
animation: none;
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user