Met à jour les listes en direct via WebSocket
Le serveur prévient, sur /ws, le propriétaire et les membres d'une liste dès qu'elle change ; leurs pages rechargent alors leurs données. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
9f3fd5701e
commit
2ade50465e
10 files changed
+359
-38
No files matched your search
+140
@@ -0,0 +1,140 @@
|
||||
//! Live updates (browser side): a WebSocket on `/ws` bumps `refresh` whenever
|
||||
//! someone changes a list this user can see.
|
||||
|
||||
use leptos::prelude::*;
|
||||
|
||||
/// Listens for changes until the calling component is unmounted.
|
||||
#[cfg_attr(not(feature = "hydrate"), allow(unused_variables))]
|
||||
pub fn subscribe(refresh: RwSignal<u32>) {
|
||||
#[cfg(feature = "hydrate")]
|
||||
browser::subscribe(refresh);
|
||||
}
|
||||
|
||||
#[cfg(feature = "hydrate")]
|
||||
mod browser {
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
use std::time::Duration;
|
||||
|
||||
use leptos::prelude::*;
|
||||
use send_wrapper::SendWrapper;
|
||||
use wasm_bindgen::JsCast;
|
||||
use wasm_bindgen::closure::Closure;
|
||||
use web_sys::{VisibilityState, WebSocket};
|
||||
|
||||
const MAX_DELAY: Duration = Duration::from_secs(30);
|
||||
|
||||
type Handler = Closure<dyn FnMut(web_sys::Event)>;
|
||||
|
||||
#[derive(Default)]
|
||||
struct Live {
|
||||
socket: Option<WebSocket>,
|
||||
/// Kept alive as long as the socket that calls them.
|
||||
handlers: Vec<Handler>,
|
||||
/// Failed attempts since the last successful connection.
|
||||
retries: u32,
|
||||
stopped: bool,
|
||||
}
|
||||
|
||||
pub fn subscribe(refresh: RwSignal<u32>) {
|
||||
let live = Rc::new(RefCell::new(Live::default()));
|
||||
connect(&live, refresh);
|
||||
|
||||
// Phones freeze background tabs and may silently drop the socket:
|
||||
// catch up whenever the page comes back.
|
||||
let on_visible: Handler = Closure::new(move |_| {
|
||||
if document().visibility_state() == VisibilityState::Visible {
|
||||
bump(refresh);
|
||||
}
|
||||
});
|
||||
_ = document()
|
||||
.add_event_listener_with_callback("visibilitychange", on_visible.as_ref().unchecked_ref());
|
||||
|
||||
let cleanup = SendWrapper::new((live, on_visible));
|
||||
on_cleanup(move || {
|
||||
let (live, on_visible) = cleanup.take();
|
||||
_ = document().remove_event_listener_with_callback(
|
||||
"visibilitychange",
|
||||
on_visible.as_ref().unchecked_ref(),
|
||||
);
|
||||
let mut live = live.borrow_mut();
|
||||
live.stopped = true;
|
||||
if let Some(socket) = live.socket.take() {
|
||||
detach(&socket);
|
||||
_ = socket.close();
|
||||
}
|
||||
live.handlers.clear();
|
||||
});
|
||||
}
|
||||
|
||||
fn connect(live: &Rc<RefCell<Live>>, refresh: RwSignal<u32>) {
|
||||
let location = window().location();
|
||||
let scheme = match location.protocol().as_deref() {
|
||||
Ok("https:") => "wss",
|
||||
_ => "ws",
|
||||
};
|
||||
let host = location.host().unwrap_or_default();
|
||||
let Ok(socket) = WebSocket::new(&format!("{scheme}://{host}/ws")) else {
|
||||
retry_later(live, refresh);
|
||||
return;
|
||||
};
|
||||
|
||||
let on_open: Handler = {
|
||||
let live = Rc::clone(live);
|
||||
Closure::new(move |_| {
|
||||
// After a reconnection, changes made meanwhile were missed.
|
||||
if std::mem::take(&mut live.borrow_mut().retries) > 0 {
|
||||
bump(refresh);
|
||||
}
|
||||
})
|
||||
};
|
||||
let on_message: Handler = Closure::new(move |_| bump(refresh));
|
||||
let on_close: Handler = {
|
||||
let live = Rc::clone(live);
|
||||
Closure::new(move |_| retry_later(&live, refresh))
|
||||
};
|
||||
socket.set_onopen(Some(on_open.as_ref().unchecked_ref()));
|
||||
socket.set_onmessage(Some(on_message.as_ref().unchecked_ref()));
|
||||
socket.set_onclose(Some(on_close.as_ref().unchecked_ref()));
|
||||
|
||||
let mut state = live.borrow_mut();
|
||||
state.socket = Some(socket);
|
||||
// The previous socket's handlers are no longer called by anyone.
|
||||
state.handlers = vec![on_open, on_message, on_close];
|
||||
}
|
||||
|
||||
/// Reconnects with exponential backoff: 1 s, 2 s, 4 s… up to 30 s.
|
||||
fn retry_later(live: &Rc<RefCell<Live>>, refresh: RwSignal<u32>) {
|
||||
let delay = {
|
||||
let mut state = live.borrow_mut();
|
||||
if state.stopped {
|
||||
return;
|
||||
}
|
||||
if let Some(socket) = state.socket.take() {
|
||||
detach(&socket);
|
||||
}
|
||||
let delay = Duration::from_secs(1 << state.retries.min(5)).min(MAX_DELAY);
|
||||
state.retries += 1;
|
||||
delay
|
||||
};
|
||||
let live = Rc::clone(live);
|
||||
set_timeout(
|
||||
move || {
|
||||
if !live.borrow().stopped {
|
||||
connect(&live, refresh);
|
||||
}
|
||||
},
|
||||
delay,
|
||||
);
|
||||
}
|
||||
|
||||
fn detach(socket: &WebSocket) {
|
||||
socket.set_onopen(None);
|
||||
socket.set_onmessage(None);
|
||||
socket.set_onclose(None);
|
||||
}
|
||||
|
||||
fn bump(refresh: RwSignal<u32>) {
|
||||
refresh.try_update(|n| *n += 1);
|
||||
}
|
||||
}
|
||||
+25
-9
@@ -1,5 +1,6 @@
|
||||
mod account;
|
||||
mod icons;
|
||||
mod live;
|
||||
mod sheets;
|
||||
mod tiles;
|
||||
|
||||
@@ -82,8 +83,9 @@ pub struct Ctx {
|
||||
/// Bumped after every mutation so resources refetch.
|
||||
refresh: RwSignal<u32>,
|
||||
error: RwSignal<Option<String>>,
|
||||
/// Checked state applied before the server confirms it.
|
||||
optimistic: RwSignal<HashMap<i64, bool>>,
|
||||
/// 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_editor: RwSignal<Option<ItemEditor>>,
|
||||
list_editor: RwSignal<Option<ListEditor>>,
|
||||
account_open: RwSignal<bool>,
|
||||
@@ -121,14 +123,22 @@ impl Ctx {
|
||||
fn toggle(self, item: &Item) {
|
||||
let (id, checked) = (item.id, !item.checked);
|
||||
self.optimistic.update(|map| {
|
||||
map.insert(id, checked);
|
||||
let in_flight = map.get(&id).map_or(0, |&(_, n)| n);
|
||||
map.insert(id, (checked, in_flight + 1));
|
||||
});
|
||||
spawn_local(async move {
|
||||
if let Err(err) = crate::api::set_checked(id, checked).await {
|
||||
self.optimistic.update(|map| {
|
||||
map.remove(&id);
|
||||
});
|
||||
self.report(err);
|
||||
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);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -159,6 +169,7 @@ fn ListsView(user: User) -> impl IntoView {
|
||||
auth: expect_context::<Auth>(),
|
||||
};
|
||||
provide_context(ctx);
|
||||
live::subscribe(ctx.refresh);
|
||||
|
||||
let params = use_params_map();
|
||||
let active_id = Memo::new(move |_| {
|
||||
@@ -261,6 +272,11 @@ 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));
|
||||
|
||||
// Items with pending checkbox changes applied, by category then name.
|
||||
let mut items = items;
|
||||
items.sort_by_cached_key(Item::sort_key);
|
||||
@@ -272,7 +288,7 @@ fn ListsContent(
|
||||
.iter()
|
||||
.cloned()
|
||||
.map(|mut item| {
|
||||
if let Some(&checked) = optimistic.get(&item.id) {
|
||||
if let Some(&(checked, _)) = optimistic.get(&item.id) {
|
||||
item.checked = checked;
|
||||
}
|
||||
item
|
||||
|
||||
Reference in new issue
Block a user