From 514bebad9992e55c907fffe18777427293fe38d8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Thu, 22 Oct 2026 08:30:20 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9A=A1=20feat:=20a=20language=20change=20re-?= =?UTF-8?q?renders=20the=20page=20in=20every=20open=20tab?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/forge-web/assets/nav.js | 26 +++++++++--- crates/forge-web/src/pages/settings_live.rs | 47 +++++++++++++++------ 2 files changed, 53 insertions(+), 20 deletions(-) diff --git a/crates/forge-web/assets/nav.js b/crates/forge-web/assets/nav.js index 20397bb..99e6140 100644 --- a/crates/forge-web/assets/nav.js +++ b/crates/forge-web/assets/nav.js @@ -11,6 +11,7 @@ var latest = 0; // id of the newest request; older responses are dropped var userBusy = 0; // navigations and form posts on the wire (not live refreshes) var liveDirty = false; // a live change came while a navigation or a live fetch was on the wire + var liveForced = false; // that change re-renders the page even with no stream of its own var liveBusy = false; // a live fetch is on the wire: later changes wait for it, then share one fetch var inFlight = 0; // requests on the wire, drives aria-busy var pending = new WeakSet(); // forms with a request on the wire: a second submit is ignored @@ -393,7 +394,7 @@ if (o.form) { pending.delete(o.form); } if (o.how === 'live') { liveBusy = false; } if (user) { userBusy -= 1; } - if (liveDirty) { refreshLive(); } + if (liveDirty) { refreshLive(liveForced); } if (o.form && queued.has(o.form)) { queued.delete(o.form); resend(o.form); } }); } @@ -464,12 +465,14 @@ // One EventSource that stays open. The browser reconnects by itself, except when a proxy answers // with an error: EventSource then closes for good, so it is opened again here after 1, 2, then 3 s. // `restart()` reconnects at once. - function keepOpen(url, onOpen, onError, onTheme) { + function keepOpen(url, onOpen, onError, handlers) { var es = null, delay = 1000, timer = null; function connect() { timer = null; es = new EventSource(url); - if (onTheme) { es.addEventListener('theme', function (e) { onTheme(e.data); }); } + Object.keys(handlers || {}).forEach(function (name) { + es.addEventListener(name, function (e) { handlers[name](e.data); }); + }); es.onopen = function () { delay = 1000; onOpen(); }; es.onerror = function () { onError(); @@ -503,7 +506,14 @@ if (value) { root.setAttribute(name, value); } else { root.removeAttribute(name); } }); } - if (window.EventSource) { alive = keepOpen('/-/alive', linkBack, linkDown, applyAppearance); } + // A `language` event means the page text changed for this user: the page is re-rendered in place + // (typed text, focus and scroll kept), as for any live change, even on a page with no stream. + if (window.EventSource) { + alive = keepOpen('/-/alive', linkBack, linkDown, { + theme: applyAppearance, + language: function () { refreshLive(true); } + }); + } if ('serviceWorker' in navigator) { navigator.serviceWorker.register('/sw.js').catch(function () {}); } // 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 @@ // A change re-renders the current page. It waits while a navigation is on the wire, since that // response could be superseded: the change is kept and sent after that request completes. - function refreshLive() { - if (!Object.keys(liveStreams).length) { return; } - if (userBusy > 0 || liveBusy) { liveDirty = true; return; } + // `force` re-renders a page that holds no stream of its own (a language change, sent by /-/alive). + function refreshLive(force) { + if (!force && !Object.keys(liveStreams).length) { return; } + if (userBusy > 0 || liveBusy) { liveDirty = true; if (force) { liveForced = true; } return; } liveDirty = false; + liveForced = false; liveBusy = true; var here = new URL(location.href); load({ target: withoutHash(here), dest: here, init: GET_INIT, how: 'live', keep: true, post: false, form: null }); diff --git a/crates/forge-web/src/pages/settings_live.rs b/crates/forge-web/src/pages/settings_live.rs index f95b9c4..c6dc0ce 100644 --- a/crates/forge-web/src/pages/settings_live.rs +++ b/crates/forge-web/src/pages/settings_live.rs @@ -19,6 +19,8 @@ //! sends a `theme` event with the appearance attributes when they change, so a tab applies a theme, //! accent or sidebar change made elsewhere without a reload. +use std::collections::VecDeque; + use futures_util::stream; use topcoat::Result; use topcoat::context::{Cx, app_context}; @@ -53,9 +55,11 @@ async fn settings_events(cx: &Cx) -> Result { /// The appearance of a user's `` as `name=value` pairs joined by `;`. An empty value means /// the attribute is removed (the automatic theme). It mirrors the attributes `views::shell` sets, so /// a tab that applies it shows what a fresh load of the page would show. -pub async fn appearance_fingerprint(state: &AppState, user_id: &str) -> Result { +/// The account state the alive stream compares: the appearance (see below) and the language +/// preference, which changes the page text rather than its attributes. +pub async fn account_state(state: &AppState, user_id: &str) -> Result<(String, String)> { let Some(user) = state.store.user_by_id(user_id).await? else { - return Ok(String::new()); + return Ok((String::new(), String::new())); }; let theme = match crate::theme::resolve_preference(&user.theme) { "auto" => "", @@ -66,13 +70,14 @@ pub async fn appearance_fingerprint(state: &AppState, user_id: &str) -> Result Result { let user_id = user.id; // Subscribed before the baseline is read, so a change in between is not lost. let wake = state.live.subscribe(&Topic::Account(user_id.clone())); - let last = appearance_fingerprint(&state, &user_id).await?; + let last = account_state(&state, &user_id).await?; + // One change can move both the appearance and the language: each gets its event, in that order. let events = stream::unfold( - (wake, last, state, user_id), - |(mut wake, mut last, state, user_id)| async move { + (wake, last, VecDeque::::new(), state, user_id), + |(mut wake, mut last, mut queue, state, user_id)| async move { loop { + if let Some(event) = queue.pop_front() { + return Some((Ok(event), (wake, last, queue, state, user_id))); + } if wake.changed().await.is_err() { return None; } - let now = match appearance_fingerprint(&state, &user_id).await { + let now = match account_state(&state, &user_id).await { Ok(now) => now, Err(e) => { - tracing::error!(error = %e, "live: could not read the appearance"); + tracing::error!(error = %e, "live: could not read the account state"); return None; } }; if now == last { continue; } - last = now.clone(); - let event = Event::new().event("theme").data(now); - return Some((Ok(event), (wake, last, state, user_id))); + if now.0 != last.0 { + queue.push_back(Event::new().event("theme").data(now.0.clone())); + } + if now.1 != last.1 { + // The page text is re-rendered by the client (a soft refresh, see `nav.js`). + queue.push_back(Event::new().event("language").data("1")); + } + last = now; } }, ); @@ -272,6 +286,10 @@ mod tests { .await .expect("user"); create_session(&store, &owner.id, "owner-token", CSRF).await; + store + .set_ui_prefs(&owner.id, "light", "en") + .await + .expect("prefs"); let router = app_router(state); let request = Request::builder() @@ -287,8 +305,9 @@ mod tests { // A bump that changes no appearance sends nothing; the next change is the theme event. live.bump(&Topic::Account(owner.id.clone())); + // One change of theme and language: the theme event first, then the language event. store - .set_ui_prefs(&owner.id, "dark", "en") + .set_ui_prefs(&owner.id, "dark", "tr") .await .expect("prefs"); live.bump(&Topic::Account(owner.id.clone())); @@ -296,5 +315,7 @@ mod tests { let text = String::from_utf8_lossy(&event).into_owned(); assert!(text.starts_with("event: theme\n"), "{text}"); assert!(text.contains("data-theme=dark;"), "{text}"); + let language = frames.next().await.expect("a frame").expect("data"); + assert_eq!(&language[..], b"event: language\ndata: 1\n\n"); } }