A language change re-renders the page in every open tab
Browse files at this commit514bebad9992e55c907fffe18777427293fe38d8Parent: 00ca6f7- feat
- a language change re-renders the page in every open tab
2 changed files +53 -20
crates/forge-web/assets/nav.jsmodified+19 -7
| @@ -11,6 +11,7 @@ | ||
| 11 | 11 | var latest = 0; // id of the newest request; older responses are dropped |
| 12 | 12 | var userBusy = 0; // navigations and form posts on the wire (not live refreshes) |
| 13 | 13 | var liveDirty = false; // a live change came while a navigation or a live fetch was on the wire |
| 14 | + var liveForced = false; // that change re-renders the page even with no stream of its own | |
| 14 | 15 | var liveBusy = false; // a live fetch is on the wire: later changes wait for it, then share one fetch |
| 15 | 16 | var inFlight = 0; // requests on the wire, drives aria-busy |
| 16 | 17 | var pending = new WeakSet(); // forms with a request on the wire: a second submit is ignored |
| @@ -393,7 +394,7 @@ | ||
| 393 | 394 | if (o.form) { pending.delete(o.form); } |
| 394 | 395 | if (o.how === 'live') { liveBusy = false; } |
| 395 | 396 | if (user) { userBusy -= 1; } |
| 396 | - if (liveDirty) { refreshLive(); } | |
| 397 | + if (liveDirty) { refreshLive(liveForced); } | |
| 397 | 398 | if (o.form && queued.has(o.form)) { queued.delete(o.form); resend(o.form); } |
| 398 | 399 | }); |
| 399 | 400 | } |
| @@ -464,12 +465,14 @@ | ||
| 464 | 465 | // One EventSource that stays open. The browser reconnects by itself, except when a proxy answers |
| 465 | 466 | // with an error: EventSource then closes for good, so it is opened again here after 1, 2, then 3 s. |
| 466 | 467 | // `restart()` reconnects at once. |
| 467 | - function keepOpen(url, onOpen, onError, onTheme) { | |
| 468 | + function keepOpen(url, onOpen, onError, handlers) { | |
| 468 | 469 | var es = null, delay = 1000, timer = null; |
| 469 | 470 | function connect() { |
| 470 | 471 | timer = null; |
| 471 | 472 | es = new EventSource(url); |
| 472 | - if (onTheme) { es.addEventListener('theme', function (e) { onTheme(e.data); }); } | |
| 473 | + Object.keys(handlers || {}).forEach(function (name) { | |
| 474 | + es.addEventListener(name, function (e) { handlers[name](e.data); }); | |
| 475 | + }); | |
| 473 | 476 | es.onopen = function () { delay = 1000; onOpen(); }; |
| 474 | 477 | es.onerror = function () { |
| 475 | 478 | onError(); |
| @@ -503,7 +506,14 @@ | ||
| 503 | 506 | if (value) { root.setAttribute(name, value); } else { root.removeAttribute(name); } |
| 504 | 507 | }); |
| 505 | 508 | } |
| 506 | - if (window.EventSource) { alive = keepOpen('/-/alive', linkBack, linkDown, applyAppearance); } | |
| 509 | + // A `language` event means the page text changed for this user: the page is re-rendered in place | |
| 510 | + // (typed text, focus and scroll kept), as for any live change, even on a page with no stream. | |
| 511 | + if (window.EventSource) { | |
| 512 | + alive = keepOpen('/-/alive', linkBack, linkDown, { | |
| 513 | + theme: applyAppearance, | |
| 514 | + language: function () { refreshLive(true); } | |
| 515 | + }); | |
| 516 | + } | |
| 507 | 517 | if ('serviceWorker' in navigator) { navigator.serviceWorker.register('/sw.js').catch(function () {}); } |
| 508 | 518 | |
| 509 | 519 | // The form to send a queued change on: the form itself, or after a swap the one with the same action. |
| @@ -1351,10 +1361,12 @@ | ||
| 1351 | 1361 | |
| 1352 | 1362 | // A change re-renders the current page. It waits while a navigation is on the wire, since that |
| 1353 | 1363 | // response could be superseded: the change is kept and sent after that request completes. |
| 1354 | - function refreshLive() { | |
| 1355 | - if (!Object.keys(liveStreams).length) { return; } | |
| 1356 | - if (userBusy > 0 || liveBusy) { liveDirty = true; return; } | |
| 1364 | + // `force` re-renders a page that holds no stream of its own (a language change, sent by /-/alive). | |
| 1365 | + function refreshLive(force) { | |
| 1366 | + if (!force && !Object.keys(liveStreams).length) { return; } | |
| 1367 | + if (userBusy > 0 || liveBusy) { liveDirty = true; if (force) { liveForced = true; } return; } | |
| 1357 | 1368 | liveDirty = false; |
| 1369 | + liveForced = false; | |
| 1358 | 1370 | liveBusy = true; |
| 1359 | 1371 | var here = new URL(location.href); |
| 1360 | 1372 | load({ target: withoutHash(here), dest: here, init: GET_INIT, how: 'live', keep: true, post: false, form: null }); |
crates/forge-web/src/pages/settings_live.rsmodified+34 -13
| @@ -19,6 +19,8 @@ | ||
| 19 | 19 | //! sends a `theme` event with the appearance attributes when they change, so a tab applies a theme, |
| 20 | 20 | //! accent or sidebar change made elsewhere without a reload. |
| 21 | 21 | |
| 22 | +use std::collections::VecDeque; | |
| 23 | + | |
| 22 | 24 | use futures_util::stream; |
| 23 | 25 | use topcoat::Result; |
| 24 | 26 | use topcoat::context::{Cx, app_context}; |
| @@ -53,9 +55,11 @@ async fn settings_events(cx: &Cx) -> Result<Response> { | ||
| 53 | 55 | /// The appearance of a user's `<html>` as `name=value` pairs joined by `;`. An empty value means |
| 54 | 56 | /// the attribute is removed (the automatic theme). It mirrors the attributes `views::shell` sets, so |
| 55 | 57 | /// a tab that applies it shows what a fresh load of the page would show. |
| 56 | -pub async fn appearance_fingerprint(state: &AppState, user_id: &str) -> Result<String> { | |
| 58 | +/// The account state the alive stream compares: the appearance (see below) and the language | |
| 59 | +/// preference, which changes the page text rather than its attributes. | |
| 60 | +pub async fn account_state(state: &AppState, user_id: &str) -> Result<(String, String)> { | |
| 57 | 61 | let Some(user) = state.store.user_by_id(user_id).await? else { |
| 58 | - return Ok(String::new()); | |
| 62 | + return Ok((String::new(), String::new())); | |
| 59 | 63 | }; |
| 60 | 64 | let theme = match crate::theme::resolve_preference(&user.theme) { |
| 61 | 65 | "auto" => "", |
| @@ -66,13 +70,14 @@ pub async fn appearance_fingerprint(state: &AppState, user_id: &str) -> Result<S | ||
| 66 | 70 | } else { |
| 67 | 71 | "left" |
| 68 | 72 | }; |
| 69 | - Ok(format!( | |
| 73 | + let appearance = format!( | |
| 70 | 74 | "data-theme={theme};data-accent-light={};data-accent-dark={};data-base-light={};data-base-dark={};data-sidebar={sidebar}", |
| 71 | 75 | crate::accent::resolve(&user.accent).id, |
| 72 | 76 | crate::accent::resolve(&user.accent_dark).id, |
| 73 | 77 | crate::accent::resolve_base(&user.base_light).id, |
| 74 | 78 | crate::accent::resolve_base(&user.base_dark).id, |
| 75 | - )) | |
| 79 | + ); | |
| 80 | + Ok((appearance, user.language.clone())) | |
| 76 | 81 | } |
| 77 | 82 | |
| 78 | 83 | /// The response of `GET /-/alive`, the stream every page holds. Anonymous: it only stays open, as |
| @@ -87,27 +92,36 @@ pub async fn alive_response(cx: &Cx) -> Result<Response> { | ||
| 87 | 92 | let user_id = user.id; |
| 88 | 93 | // Subscribed before the baseline is read, so a change in between is not lost. |
| 89 | 94 | let wake = state.live.subscribe(&Topic::Account(user_id.clone())); |
| 90 | - let last = appearance_fingerprint(&state, &user_id).await?; | |
| 95 | + let last = account_state(&state, &user_id).await?; | |
| 96 | + // One change can move both the appearance and the language: each gets its event, in that order. | |
| 91 | 97 | let events = stream::unfold( |
| 92 | - (wake, last, state, user_id), | |
| 93 | - |(mut wake, mut last, state, user_id)| async move { | |
| 98 | + (wake, last, VecDeque::<Event>::new(), state, user_id), | |
| 99 | + |(mut wake, mut last, mut queue, state, user_id)| async move { | |
| 94 | 100 | loop { |
| 101 | + if let Some(event) = queue.pop_front() { | |
| 102 | + return Some((Ok(event), (wake, last, queue, state, user_id))); | |
| 103 | + } | |
| 95 | 104 | if wake.changed().await.is_err() { |
| 96 | 105 | return None; |
| 97 | 106 | } |
| 98 | - let now = match appearance_fingerprint(&state, &user_id).await { | |
| 107 | + let now = match account_state(&state, &user_id).await { | |
| 99 | 108 | Ok(now) => now, |
| 100 | 109 | Err(e) => { |
| 101 | - tracing::error!(error = %e, "live: could not read the appearance"); | |
| 110 | + tracing::error!(error = %e, "live: could not read the account state"); | |
| 102 | 111 | return None; |
| 103 | 112 | } |
| 104 | 113 | }; |
| 105 | 114 | if now == last { |
| 106 | 115 | continue; |
| 107 | 116 | } |
| 108 | - last = now.clone(); | |
| 109 | - let event = Event::new().event("theme").data(now); | |
| 110 | - return Some((Ok(event), (wake, last, state, user_id))); | |
| 117 | + if now.0 != last.0 { | |
| 118 | + queue.push_back(Event::new().event("theme").data(now.0.clone())); | |
| 119 | + } | |
| 120 | + if now.1 != last.1 { | |
| 121 | + // The page text is re-rendered by the client (a soft refresh, see `nav.js`). | |
| 122 | + queue.push_back(Event::new().event("language").data("1")); | |
| 123 | + } | |
| 124 | + last = now; | |
| 111 | 125 | } |
| 112 | 126 | }, |
| 113 | 127 | ); |
| @@ -272,6 +286,10 @@ mod tests { | ||
| 272 | 286 | .await |
| 273 | 287 | .expect("user"); |
| 274 | 288 | create_session(&store, &owner.id, "owner-token", CSRF).await; |
| 289 | + store | |
| 290 | + .set_ui_prefs(&owner.id, "light", "en") | |
| 291 | + .await | |
| 292 | + .expect("prefs"); | |
| 275 | 293 | let router = app_router(state); |
| 276 | 294 | |
| 277 | 295 | let request = Request::builder() |
| @@ -287,8 +305,9 @@ mod tests { | ||
| 287 | 305 | |
| 288 | 306 | // A bump that changes no appearance sends nothing; the next change is the theme event. |
| 289 | 307 | live.bump(&Topic::Account(owner.id.clone())); |
| 308 | + // One change of theme and language: the theme event first, then the language event. | |
| 290 | 309 | store |
| 291 | - .set_ui_prefs(&owner.id, "dark", "en") | |
| 310 | + .set_ui_prefs(&owner.id, "dark", "tr") | |
| 292 | 311 | .await |
| 293 | 312 | .expect("prefs"); |
| 294 | 313 | live.bump(&Topic::Account(owner.id.clone())); |
| @@ -296,5 +315,7 @@ mod tests { | ||
| 296 | 315 | let text = String::from_utf8_lossy(&event).into_owned(); |
| 297 | 316 | assert!(text.starts_with("event: theme\n"), "{text}"); |
| 298 | 317 | assert!(text.contains("data-theme=dark;"), "{text}"); |
| 318 | + let language = frames.next().await.expect("a frame").expect("data"); | |
| 319 | + assert_eq!(&language[..], b"event: language\ndata: 1\n\n"); | |
| 299 | 320 | } |
| 300 | 321 | } |