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