Enregistre les changements d'articles par lots en arrière-plan

Cocher, ajouter, modifier ou supprimer un article s'affiche aussitôt :
le changement attend dans une file, fusionné avec les précédents, puis
part avec les autres en une seule requête, une à la fois. Le serveur
applique le lot dans une transaction et résout les ids temporaires des
articles ajoutés. Sans réseau, le lot est gardé et renvoyé plus tard.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Romulus21andClaude Opus 5.5 committed 2026-10-16 08:47:25 +02:00
1 parent f3f5f0cee1
commit 6c593b0201
7 files changed
+565 -126

No files matched your search

+50 -55
View File
@@ -3,9 +3,9 @@ mod admin;
mod icons;
mod live;
mod sheets;
mod sync;
mod tiles;
use std::collections::HashMap;
use std::future::Future;
use leptos::prelude::*;
@@ -16,10 +16,11 @@ use leptos_router::hooks::use_params_map;
use leptos_router::path;
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 admin::AdminPage;
use sheets::{ItemEditor, ItemSheet, ListEditor, ListSheet};
use sync::Sync;
use tiles::{BasketTile, ItemTile, SuggestionTile};
pub fn shell(options: LeptosOptions) -> impl IntoView {
@@ -86,9 +87,8 @@ pub struct Ctx {
/// Bumped after every mutation so resources refetch.
refresh: RwSignal<u32>,
error: RwSignal<Option<String>>,
/// Checked state applied before fresh data shows it, with the number of
/// calls still in flight for that item.
optimistic: RwSignal<HashMap<i64, (bool, u32)>>,
/// Item changes waiting to be saved.
sync: Sync,
item_editor: RwSignal<Option<ItemEditor>>,
list_editor: RwSignal<Option<ListEditor>>,
account_open: RwSignal<bool>,
@@ -123,27 +123,13 @@ impl Ctx {
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);
}
fn toggle(self, item: &Item) {
let (id, checked) = (item.id, !item.checked);
self.optimistic.update(|map| {
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);
}
}
});
self.change(ItemOp::SetChecked { id: item.id, checked: !item.checked });
}
}
@@ -164,7 +150,7 @@ fn ListsView(user: User) -> impl IntoView {
let ctx = Ctx {
refresh: RwSignal::new(0),
error: RwSignal::new(None),
optimistic: RwSignal::new(HashMap::new()),
sync: Sync::new(),
item_editor: RwSignal::new(None),
list_editor: RwSignal::new(None),
account_open: RwSignal::new(false),
@@ -173,6 +159,7 @@ fn ListsView(user: User) -> impl IntoView {
};
provide_context(ctx);
live::subscribe(ctx.refresh);
ctx.sync.flush_on_hide(ctx);
let params = use_params_map();
let active_id = Memo::new(move |_| {
@@ -185,10 +172,14 @@ fn ListsView(user: User) -> impl IntoView {
let lists = Resource::new(move || ctx.refresh.get(), |_| get_lists());
let items = Resource::new(
move || (active_id.get(), ctx.refresh.get()),
|(id, _)| async move {
match id {
Some(id) => get_items(id).await,
None => Ok(Vec::new()),
move |(id, _)| {
// What the data will include, to drop the changes it shows.
let saved = ctx.sync.saved();
async move {
match id {
Some(id) => get_items(id).await.map(|items| (items, saved)),
None => Ok((Vec::new(), saved)),
}
}
},
);
@@ -218,6 +209,11 @@ fn ListsView(user: User) -> impl IntoView {
</header>
<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 /> }>
<ErrorBoundary fallback=|errors| {
@@ -232,10 +228,10 @@ fn ListsView(user: User) -> impl IntoView {
}>
{move || Suspend::new(async move {
let lists = lists.await?;
let items = items.await?;
let (items, saved) = items.await?;
let suggestions = suggestions.await?;
Ok::<_, ServerFnError>(view! {
<ListsContent lists items suggestions active_id=active_id.get() />
<ListsContent lists items saved suggestions active_id=active_id.get() />
})
})}
</ErrorBoundary>
@@ -252,6 +248,8 @@ fn ListsView(user: User) -> impl IntoView {
fn ListsContent(
lists: Vec<ShoppingList>,
items: Vec<Item>,
/// Batches of changes saved when `items` was fetched.
saved: u32,
suggestions: Vec<Suggestion>,
active_id: Option<i64>,
) -> impl IntoView {
@@ -275,28 +273,26 @@ fn ListsContent(
.into_any();
};
// Fresh data includes every confirmed toggle: only keep pending ones, so
// changes made by others since are not masked.
ctx.optimistic
.update_untracked(|map| map.retain(|_, &mut (_, in_flight)| in_flight > 0));
ctx.sync.settle(saved);
// Items with pending checkbox changes applied, by category then name.
let mut items = items;
items.sort_by_cached_key(Item::sort_key);
// Items with unsaved changes applied, by category then name.
let items = StoredValue::new(items);
let current = Memo::new(move |_| {
let optimistic = ctx.optimistic.get();
items.with_value(|items| {
items
.iter()
.cloned()
.map(|mut item| {
if let Some(&(checked, _)) = optimistic.get(&item.id) {
item.checked = checked;
}
item
})
.collect::<Vec<_>>()
let mut items = items.with_value(|items| ctx.sync.apply(active_id, items));
items.sort_by_cached_key(Item::sort_key);
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()
.filter(|s| !items.iter().any(|i| i.name.to_lowercase() == s.name.to_lowercase()))
.cloned()
.collect::<Vec<_>>()
})
})
});
let to_get = Memo::new(move |_| {
@@ -362,10 +358,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>
<ItemTile item />
</For>
{suggestions
.into_iter()
.map(|suggestion| view! { <SuggestionTile suggestion list_id=active_id /> })
.collect_view()}
<For each=move || suggestions.get() key=|suggestion| suggestion.name.clone() let:suggestion>
<SuggestionTile suggestion list_id=active_id />
</For>
</div>
<Show when=move || !in_basket.with(Vec::is_empty)>
+8 -6
View File
@@ -5,7 +5,7 @@ use leptos_router::hooks::use_navigate;
use super::Ctx;
use super::icons::{IconSvg, icon_label};
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)]
pub enum ItemEditor {
@@ -86,14 +86,16 @@ fn ItemForm(editor: ItemEditor, list_id: i64) -> impl IntoView {
icon: icon.get(),
category: category.get(),
};
match item_id {
Some(id) => ctx.mutate(crate::api::update_item(id, input), move |_| close()),
None => ctx.mutate(crate::api::add_item(list_id, input), move |_| close()),
}
ctx.change(match item_id {
Some(id) => ItemOp::Update { id, input },
None => ItemOp::Add { id: 0, list_id, input },
});
close();
};
let delete = move |_| {
if let Some(id) = item_id {
ctx.mutate(crate::api::delete_item(id), move |_| close());
ctx.change(ItemOp::Delete { id });
close();
}
};
+323
View File
@@ -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);
}
}
+2 -2
View File
@@ -3,7 +3,7 @@ use leptos::prelude::*;
use super::icons::IconSvg;
use super::{Ctx, ItemEditor};
use crate::model::{Item, ItemInput, Suggestion};
use crate::model::{Item, ItemInput, ItemOp, Suggestion};
const LONG_PRESS_MS: u64 = 450;
@@ -88,7 +88,7 @@ pub fn SuggestionTile(suggestion: Suggestion, list_id: i64) -> impl IntoView {
let add = move |_| {
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! {