From 21e0e945b76e2e76795784113005ecf0209dc085 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sat, 5 Sep 2026 07:41:37 +0300 Subject: [PATCH] =?UTF-8?q?Soft=20navigation=20and=20a=20live=20channel=20?= =?UTF-8?q?on=20every=20signed-in=20page=20=E2=80=94=20iz's=20model:=20lin?= =?UTF-8?q?ks=20and=20form=20posts=20swap=20in=20place,=20and=20a=20bare?= =?UTF-8?q?=20tick=20re-fetches=20and=20morphs=20the=20page=20with=20field?= =?UTF-8?q?s=20and=20scroll=20intact?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/im-web/src/admin.rs | 38 +++------- crates/im-web/src/layout.rs | 139 ++++++++++++++++++++++++++++++++++++ crates/im-web/src/live.rs | 20 +++--- crates/im-web/src/pages.rs | 12 ++-- crates/im-web/src/server.rs | 7 +- 5 files changed, 165 insertions(+), 51 deletions(-) diff --git a/crates/im-web/src/admin.rs b/crates/im-web/src/admin.rs index ba911ad..7dcf70f 100644 --- a/crates/im-web/src/admin.rs +++ b/crates/im-web/src/admin.rs @@ -63,35 +63,13 @@ fn confirm_action( r#"
{word}
{title}
{cost}
"# ) } -/// The panel's live wiring, the client half of `live.rs`. One EventSource -/// per tab; a tick re-fetches the page and swaps the panel's body. iz's -/// lesson is honored in miniature: the swap must not throw away what someone -/// is doing, so a focused field suspends the refresh until the next tick, -/// and the morph is one innerHTML swap of the column — small DOM, no diffing -/// library needed. -/// -/// The same script closes an open confirm disclosure on outside click and -/// Escape — the one bit of behavior the no-script markup cannot do itself. -const LIVE_SCRIPT: &str = r#" } } +/// Soft navigation, iz's model cut to im's shape: same-app links and form +/// posts are fetched and swapped in place — no full reload, no white flash, +/// no lost scroll on a save. Session-changing forms (sign-in, enroll, +/// redeem, sign-out) carry `data-hard` and post natively; multipart forms +/// belong to the avatar script above and are left to it. Global listeners +/// live on document/window and survive every swap; the guard makes the +/// re-created script a no-op. +pub async fn soft_nav_script(cx: &Cx) -> Result { + use topcoat::view::Unescaped; + const JS: &str = r#"(function () { + if (window.__imSoft) { return; } + window.__imSoft = true; + var nav = 0; + function step() { nav += 1; return nav; } + + function adopt(doc, preserve) { + document.title = doc.title; + var root = doc.documentElement; + ['lang', 'data-theme', 'data-ui'].forEach(function (a) { + if (root.hasAttribute(a)) { document.documentElement.setAttribute(a, root.getAttribute(a)); } + else { document.documentElement.removeAttribute(a); } + }); + var fields = null; + if (preserve) { + fields = {}; + document.querySelectorAll('input[name], select[name], textarea[name]').forEach(function (f) { + if (f.type === 'password' || f.type === 'file' || f.type === 'hidden') { return; } + fields[f.name] = f.value; + }); + } + document.body.replaceChildren(); + Array.from(doc.body.childNodes).forEach(function (n) { document.body.appendChild(document.importNode(n, true)); }); + document.querySelectorAll('script').forEach(function (old) { + var s = document.createElement('script'); + s.textContent = old.textContent; + old.replaceWith(s); + }); + if (fields) { + document.querySelectorAll('input[name], select[name], textarea[name]').forEach(function (f) { + if (Object.prototype.hasOwnProperty.call(fields, f.name)) { f.value = fields[f.name]; } + }); + } + } + + function swap(html, url, fresh, push) { + var doc = new DOMParser().parseFromString(html, 'text/html'); + if (!doc.body) { location.assign(url); return; } + var x = window.scrollX, y = window.scrollY; + adopt(doc, false); + if (push) { history.pushState(null, '', url); } else { history.replaceState(null, '', url); } + if (fresh) { window.scrollTo(0, 0); } else { window.scrollTo(x, y); } + } + + function go(url, fresh, push) { + var mark = step(); + fetch(url, { headers: { accept: 'text/html' } }) + .then(function (r) { return r.text().then(function (text) { return { text: text, url: r.url }; }); }) + .then(function (res) { if (mark === nav) { swap(res.text, res.url, fresh, push); } }) + .catch(function () { location.assign(url); }); + } + + document.addEventListener('click', function (e) { + if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) { return; } + var a = e.target.closest ? e.target.closest('a') : null; + if (!a || a.target || a.hasAttribute('download') || a.hasAttribute('data-hard')) { return; } + var href = a.getAttribute('href') || ''; + if (href.indexOf('/') !== 0) { return; } + e.preventDefault(); + go(href, true, true); + }, true); + + document.addEventListener('submit', function (e) { + var form = e.target; + if (!form || !form.action || form.hasAttribute('data-hard')) { return; } + if ((form.enctype || '').indexOf('multipart') === 0) { return; } + if ((form.method || 'get').toLowerCase() === 'get') { + e.preventDefault(); + var q = new URLSearchParams(new FormData(form)).toString(); + go(form.action.split('?')[0] + (q ? '?' + q : ''), true, true); + return; + } + e.preventDefault(); + var mark = step(); + var data = new FormData(form); + if (e.submitter && e.submitter.name) { data.append(e.submitter.name, e.submitter.value); } + fetch(form.action, { method: 'POST', headers: { accept: 'text/html' }, body: new URLSearchParams(data) }) + .then(function (r) { return r.text().then(function (text) { return { text: text, url: r.url }; }); }) + .then(function (res) { if (mark === nav) { swap(res.text, res.url, false, false); } }) + .catch(function () { form.submit(); }); + }); + + window.addEventListener('popstate', function () { go(location.pathname + location.search, false, false); }); + + window.__imRefresh = function () { + var active = document.activeElement; + if (active && /^(INPUT|SELECT|TEXTAREA)$/.test(active.tagName)) { return; } + fetch(location.href, { headers: { accept: 'text/html' } }) + .then(function (r) { return r.text(); }) + .then(function (html) { + var doc = new DOMParser().parseFromString(html, 'text/html'); + if (!doc.body) { return; } + var x = window.scrollX, y = window.scrollY; + adopt(doc, true); + window.scrollTo(x, y); + }) + .catch(function () {}); + }; +})();"#; + view! { cx => } +} + +/// The live channel's client, iz's shape: a bare tick says *something* +/// moved; the page re-fetches itself through the ordinary route — where the +/// ordinary gate answers — and morphs with fields and scroll intact. A +/// focused field freezes the refresh mid-typing. Mounted only for a signed-in +/// viewer, so auth screens never reconnect against a 401. +pub async fn live_script(cx: &Cx) -> Result { + use topcoat::view::Unescaped; + const JS: &str = r#"(function () { + if (window.__imLive) { return; } + window.__imLive = true; + var timer = null; + function schedule() { + if (timer) { clearTimeout(timer); } + timer = setTimeout(function () { timer = null; if (window.__imRefresh) { window.__imRefresh(); } }, 200); + } + try { + var src = new EventSource('/live'); + src.onmessage = function () { schedule(); }; + } catch (err) {} +})();"#; + view! { cx => } +} + /// A full document around an already-rendered stage — the same way /// izlek-web's `#[layout]` receives its slot. The viewer stamps the chrome: /// their theme/language/ui when signed in, English/light/instrument when @@ -210,6 +345,10 @@ pub async fn shell(cx: &Cx, title: &str, viewer: Option<&User>, stage: Result) - (stage) + (soft_nav_script(cx).await?) + if viewer.is_some() { + (live_script(cx).await?) + } } diff --git a/crates/im-web/src/live.rs b/crates/im-web/src/live.rs index 111445f..5b31246 100644 --- a/crates/im-web/src/live.rs +++ b/crates/im-web/src/live.rs @@ -1,11 +1,11 @@ -//! The live channel: one long-lived connection per open admin tab, carrying -//! the news that something changed — ported from iz's `live.rs`. +//! The live channel: one long-lived connection per open signed-in tab, +//! carrying the news that something changed — ported from iz's `live.rs`. //! //! What travels here is a bare tick and nothing else — never a row, never a -//! name. The client is told only *that* the panel moved, and re-fetches it -//! through the ordinary route, where the ordinary admin gate answers. The -//! route itself is admin-gated, and the whole panel behind it is admin-only, -//! so there is no per-topic filtering to get wrong. +//! name. The client is told only *that* the page moved, and re-fetches it +//! through the ordinary route, where the ordinary gate answers. Every page +//! behind it needs the same session the stream asked for, so there is no +//! per-topic filtering to get wrong. use std::time::{Duration, Instant}; @@ -36,14 +36,10 @@ const WINDOW: Duration = Duration::from_secs(50 * 60); #[derive(Clone)] pub struct Shutdown(pub tokio::sync::watch::Receiver); -#[route(GET "/admin/live")] +#[route(GET "/live")] async fn live(cx: &Cx) -> topcoat::Result { // Resolved once, here, and never again for the life of this connection. - let Ok(_admin) = server::current_user(cx) - .await - .filter(|user| user.admin) - .ok_or(()) - else { + let Ok(_user) = server::current_user(cx).await.ok_or(()) else { return (StatusCode::UNAUTHORIZED, "").into_response(cx); }; let rx = server::app(cx).live.subscribe(); diff --git a/crates/im-web/src/pages.rs b/crates/im-web/src/pages.rs index e1424be..e49d9ae 100644 --- a/crates/im-web/src/pages.rs +++ b/crates/im-web/src/pages.rs @@ -154,7 +154,7 @@ async fn login_card(cx: &Cx) -> Result { if let Some(code) = error {
(error_text(&code, lang))
} -
+