forge
Explore
Log in

Don't you dare go Hollow

A language change re-renders the page in every open tab

Browse files at this commit

514bebad9992e55c907fffe18777427293fe38d8Ahmet Kaan GümüşParent: 00ca6f7
  • feat
    • a language change re-renders the page in every open tab
Show full message
⚡ feat: a language change re-renders the page in every open tab
crates/forge-web/assets/nav.jsmodified+19 -7
@@ -11,6 +11,7 @@
1111 var latest = 0; // id of the newest request; older responses are dropped
1212 var userBusy = 0; // navigations and form posts on the wire (not live refreshes)
1313 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
1415 var liveBusy = false; // a live fetch is on the wire: later changes wait for it, then share one fetch
1516 var inFlight = 0; // requests on the wire, drives aria-busy
1617 var pending = new WeakSet(); // forms with a request on the wire: a second submit is ignored
@@ -393,7 +394,7 @@
393394 if (o.form) { pending.delete(o.form); }
394395 if (o.how === 'live') { liveBusy = false; }
395396 if (user) { userBusy -= 1; }
396- if (liveDirty) { refreshLive(); }
397+ if (liveDirty) { refreshLive(liveForced); }
397398 if (o.form && queued.has(o.form)) { queued.delete(o.form); resend(o.form); }
398399 });
399400 }
@@ -464,12 +465,14 @@
464465 // One EventSource that stays open. The browser reconnects by itself, except when a proxy answers
465466 // with an error: EventSource then closes for good, so it is opened again here after 1, 2, then 3 s.
466467 // `restart()` reconnects at once.
467- function keepOpen(url, onOpen, onError, onTheme) {
468+ function keepOpen(url, onOpen, onError, handlers) {
468469 var es = null, delay = 1000, timer = null;
469470 function connect() {
470471 timer = null;
471472 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+ });
473476 es.onopen = function () { delay = 1000; onOpen(); };
474477 es.onerror = function () {
475478 onError();
@@ -503,7 +506,14 @@
503506 if (value) { root.setAttribute(name, value); } else { root.removeAttribute(name); }
504507 });
505508 }
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+ }
507517 if ('serviceWorker' in navigator) { navigator.serviceWorker.register('/sw.js').catch(function () {}); }
508518
509519 // 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 @@
13511361
13521362 // A change re-renders the current page. It waits while a navigation is on the wire, since that
13531363 // 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; }
13571368 liveDirty = false;
1369+ liveForced = false;
13581370 liveBusy = true;
13591371 var here = new URL(location.href);
13601372 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 @@
1919 //! sends a `theme` event with the appearance attributes when they change, so a tab applies a theme,
2020 //! accent or sidebar change made elsewhere without a reload.
2121
22+use std::collections::VecDeque;
23+
2224 use futures_util::stream;
2325 use topcoat::Result;
2426 use topcoat::context::{Cx, app_context};
@@ -53,9 +55,11 @@ async fn settings_events(cx: &Cx) -> Result<Response> {
5355 /// The appearance of a user's `<html>` as `name=value` pairs joined by `;`. An empty value means
5456 /// the attribute is removed (the automatic theme). It mirrors the attributes `views::shell` sets, so
5557 /// 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)> {
5761 let Some(user) = state.store.user_by_id(user_id).await? else {
58- return Ok(String::new());
62+ return Ok((String::new(), String::new()));
5963 };
6064 let theme = match crate::theme::resolve_preference(&user.theme) {
6165 "auto" => "",
@@ -66,13 +70,14 @@ pub async fn appearance_fingerprint(state: &AppState, user_id: &str) -> Result<S
6670 } else {
6771 "left"
6872 };
69- Ok(format!(
73+ let appearance = format!(
7074 "data-theme={theme};data-accent-light={};data-accent-dark={};data-base-light={};data-base-dark={};data-sidebar={sidebar}",
7175 crate::accent::resolve(&user.accent).id,
7276 crate::accent::resolve(&user.accent_dark).id,
7377 crate::accent::resolve_base(&user.base_light).id,
7478 crate::accent::resolve_base(&user.base_dark).id,
75- ))
79+ );
80+ Ok((appearance, user.language.clone()))
7681 }
7782
7883 /// 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> {
8792 let user_id = user.id;
8893 // Subscribed before the baseline is read, so a change in between is not lost.
8994 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.
9197 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 {
94100 loop {
101+ if let Some(event) = queue.pop_front() {
102+ return Some((Ok(event), (wake, last, queue, state, user_id)));
103+ }
95104 if wake.changed().await.is_err() {
96105 return None;
97106 }
98- let now = match appearance_fingerprint(&state, &user_id).await {
107+ let now = match account_state(&state, &user_id).await {
99108 Ok(now) => now,
100109 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");
102111 return None;
103112 }
104113 };
105114 if now == last {
106115 continue;
107116 }
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;
111125 }
112126 },
113127 );
@@ -272,6 +286,10 @@ mod tests {
272286 .await
273287 .expect("user");
274288 create_session(&store, &owner.id, "owner-token", CSRF).await;
289+ store
290+ .set_ui_prefs(&owner.id, "light", "en")
291+ .await
292+ .expect("prefs");
275293 let router = app_router(state);
276294
277295 let request = Request::builder()
@@ -287,8 +305,9 @@ mod tests {
287305
288306 // A bump that changes no appearance sends nothing; the next change is the theme event.
289307 live.bump(&Topic::Account(owner.id.clone()));
308+ // One change of theme and language: the theme event first, then the language event.
290309 store
291- .set_ui_prefs(&owner.id, "dark", "en")
310+ .set_ui_prefs(&owner.id, "dark", "tr")
292311 .await
293312 .expect("prefs");
294313 live.bump(&Topic::Account(owner.id.clone()));
@@ -296,5 +315,7 @@ mod tests {
296315 let text = String::from_utf8_lossy(&event).into_owned();
297316 assert!(text.starts_with("event: theme\n"), "{text}");
298317 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");
299320 }
300321 }