forge
Explore
Log in

Don't you dare go Hollow

Soft navigation and a live channel on every signed-in page — iz's model: links and form posts swap in place, and a bare tick re-fetches and morphs the page with fields and scroll intact

Browse files at this commit

21e0e945b76e2e76795784113005ecf0209dc085Ahmet Kaan GümüşParent: 8929bd1
crates/im-web/src/admin.rsmodified+8 -30
@@ -63,35 +63,13 @@ fn confirm_action(
63 r#"<details class="admin-confirm"><summary class="admin-action{extra_class}">{word}</summary><div class="admin-confirm-pop"><div class="admin-confirm-title">{title}</div><div class="muted">{cost}</div><form method="post" action="{action}"><input type="hidden" name="user" value="{id}"><button class="admin-action{extra_class}" type="submit">{confirm}</button></form></div></details>"#63 r#"<details class="admin-confirm"><summary class="admin-action{extra_class}">{word}</summary><div class="admin-confirm-pop"><div class="admin-confirm-title">{title}</div><div class="muted">{cost}</div><form method="post" action="{action}"><input type="hidden" name="user" value="{id}"><button class="admin-action{extra_class}" type="submit">{confirm}</button></form></div></details>"#
64 )64 )
65 }65 }
66-/// The panel's live wiring, the client half of `live.rs`. One EventSource66+/// The panel's live wiring moved into the shell: `layout::live_script` runs
67-/// per tab; a tick re-fetches the page and swaps the panel's body. iz's67+/// on every signed-in page and morphs through `__imRefresh`. What stays here
68-/// lesson is honored in miniature: the swap must not throw away what someone68+/// is the one bit of behavior the no-script markup cannot do itself — an open
69-/// is doing, so a focused field suspends the refresh until the next tick,69+/// confirm disclosure closes on outside click and Escape.
70-/// and the morph is one innerHTML swap of the column — small DOM, no diffing70+const ADMIN_SCRIPT: &str = r#"<script>(function () {
71-/// library needed.71+ if (window.__imAdmin) { return; }
72-///72+ window.__imAdmin = true;
73-/// The same script closes an open confirm disclosure on outside click and
74-/// Escape — the one bit of behavior the no-script markup cannot do itself.
75-const LIVE_SCRIPT: &str = r#"<script>(function () {
76- if (window.__imLive) { return; }
77- window.__imLive = true;
78- var timer = null;
79- function refresh() {
80- timer = null;
81- var active = document.activeElement;
82- if (active && /^(INPUT|SELECT|TEXTAREA)$/.test(active.tagName)) { return; }
83- fetch(location.href).then(function (r) { return r.text(); }).then(function (html) {
84- var fresh = new DOMParser().parseFromString(html, 'text/html');
85- var here = document.querySelector('.admin-column');
86- var there = fresh.querySelector('.admin-column');
87- if (here && there) { here.innerHTML = there.innerHTML; }
88- }).catch(function () {});
89- }
90- var source = new EventSource('/admin/live');
91- source.onmessage = function () {
92- if (timer) { return; }
93- timer = setTimeout(refresh, 200);
94- };
95 document.addEventListener('click', function (e) {73 document.addEventListener('click', function (e) {
96 document.querySelectorAll('.admin-confirm[open]').forEach(function (d) {74 document.querySelectorAll('.admin-confirm[open]').forEach(function (d) {
97 if (!d.contains(e.target)) { d.removeAttribute('open'); }75 if (!d.contains(e.target)) { d.removeAttribute('open'); }
@@ -198,7 +176,7 @@ async fn admin_page(cx: &Cx) -> Result<Response> {
198 (topcoat::view::Unescaped::new_unchecked(banner))176 (topcoat::view::Unescaped::new_unchecked(banner))
199 }177 }
200 (topcoat::view::Unescaped::new_unchecked(section_html))178 (topcoat::view::Unescaped::new_unchecked(section_html))
201- (topcoat::view::Unescaped::new_unchecked(LIVE_SCRIPT.to_string()))179+ (topcoat::view::Unescaped::new_unchecked(ADMIN_SCRIPT.to_string()))
202 </div>180 </div>
203 </main>181 </main>
204 };182 };
crates/im-web/src/layout.rsmodified+139 -0
@@ -165,6 +165,7 @@ pub async fn avatar_script(cx: &Cx, lang: Lang) -> Result {
165 }; \165 }; \
166 x.onload = function () { \166 x.onload = function () { \
167 settle(); \167 settle(); \
168+ if (window.__imRefresh) { window.__imRefresh(); return; } \
168 window.location.href = x.responseURL || form.getAttribute('action'); \169 window.location.href = x.responseURL || form.getAttribute('action'); \
169 }; \170 }; \
170 x.onerror = function () { settle(); form.submit(); }; \171 x.onerror = function () { settle(); form.submit(); }; \
@@ -183,6 +184,140 @@ pub async fn avatar_script(cx: &Cx, lang: Lang) -> Result {
183 view! { cx => <script>(Unescaped::new_unchecked(js))</script> }184 view! { cx => <script>(Unescaped::new_unchecked(js))</script> }
184 }185 }
185 186
187+/// Soft navigation, iz's model cut to im's shape: same-app links and form
188+/// posts are fetched and swapped in place — no full reload, no white flash,
189+/// no lost scroll on a save. Session-changing forms (sign-in, enroll,
190+/// redeem, sign-out) carry `data-hard` and post natively; multipart forms
191+/// belong to the avatar script above and are left to it. Global listeners
192+/// live on document/window and survive every swap; the guard makes the
193+/// re-created script a no-op.
194+pub async fn soft_nav_script(cx: &Cx) -> Result {
195+ use topcoat::view::Unescaped;
196+ const JS: &str = r#"(function () {
197+ if (window.__imSoft) { return; }
198+ window.__imSoft = true;
199+ var nav = 0;
200+ function step() { nav += 1; return nav; }
201+
202+ function adopt(doc, preserve) {
203+ document.title = doc.title;
204+ var root = doc.documentElement;
205+ ['lang', 'data-theme', 'data-ui'].forEach(function (a) {
206+ if (root.hasAttribute(a)) { document.documentElement.setAttribute(a, root.getAttribute(a)); }
207+ else { document.documentElement.removeAttribute(a); }
208+ });
209+ var fields = null;
210+ if (preserve) {
211+ fields = {};
212+ document.querySelectorAll('input[name], select[name], textarea[name]').forEach(function (f) {
213+ if (f.type === 'password' || f.type === 'file' || f.type === 'hidden') { return; }
214+ fields[f.name] = f.value;
215+ });
216+ }
217+ document.body.replaceChildren();
218+ Array.from(doc.body.childNodes).forEach(function (n) { document.body.appendChild(document.importNode(n, true)); });
219+ document.querySelectorAll('script').forEach(function (old) {
220+ var s = document.createElement('script');
221+ s.textContent = old.textContent;
222+ old.replaceWith(s);
223+ });
224+ if (fields) {
225+ document.querySelectorAll('input[name], select[name], textarea[name]').forEach(function (f) {
226+ if (Object.prototype.hasOwnProperty.call(fields, f.name)) { f.value = fields[f.name]; }
227+ });
228+ }
229+ }
230+
231+ function swap(html, url, fresh, push) {
232+ var doc = new DOMParser().parseFromString(html, 'text/html');
233+ if (!doc.body) { location.assign(url); return; }
234+ var x = window.scrollX, y = window.scrollY;
235+ adopt(doc, false);
236+ if (push) { history.pushState(null, '', url); } else { history.replaceState(null, '', url); }
237+ if (fresh) { window.scrollTo(0, 0); } else { window.scrollTo(x, y); }
238+ }
239+
240+ function go(url, fresh, push) {
241+ var mark = step();
242+ fetch(url, { headers: { accept: 'text/html' } })
243+ .then(function (r) { return r.text().then(function (text) { return { text: text, url: r.url }; }); })
244+ .then(function (res) { if (mark === nav) { swap(res.text, res.url, fresh, push); } })
245+ .catch(function () { location.assign(url); });
246+ }
247+
248+ document.addEventListener('click', function (e) {
249+ if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) { return; }
250+ var a = e.target.closest ? e.target.closest('a') : null;
251+ if (!a || a.target || a.hasAttribute('download') || a.hasAttribute('data-hard')) { return; }
252+ var href = a.getAttribute('href') || '';
253+ if (href.indexOf('/') !== 0) { return; }
254+ e.preventDefault();
255+ go(href, true, true);
256+ }, true);
257+
258+ document.addEventListener('submit', function (e) {
259+ var form = e.target;
260+ if (!form || !form.action || form.hasAttribute('data-hard')) { return; }
261+ if ((form.enctype || '').indexOf('multipart') === 0) { return; }
262+ if ((form.method || 'get').toLowerCase() === 'get') {
263+ e.preventDefault();
264+ var q = new URLSearchParams(new FormData(form)).toString();
265+ go(form.action.split('?')[0] + (q ? '?' + q : ''), true, true);
266+ return;
267+ }
268+ e.preventDefault();
269+ var mark = step();
270+ var data = new FormData(form);
271+ if (e.submitter && e.submitter.name) { data.append(e.submitter.name, e.submitter.value); }
272+ fetch(form.action, { method: 'POST', headers: { accept: 'text/html' }, body: new URLSearchParams(data) })
273+ .then(function (r) { return r.text().then(function (text) { return { text: text, url: r.url }; }); })
274+ .then(function (res) { if (mark === nav) { swap(res.text, res.url, false, false); } })
275+ .catch(function () { form.submit(); });
276+ });
277+
278+ window.addEventListener('popstate', function () { go(location.pathname + location.search, false, false); });
279+
280+ window.__imRefresh = function () {
281+ var active = document.activeElement;
282+ if (active && /^(INPUT|SELECT|TEXTAREA)$/.test(active.tagName)) { return; }
283+ fetch(location.href, { headers: { accept: 'text/html' } })
284+ .then(function (r) { return r.text(); })
285+ .then(function (html) {
286+ var doc = new DOMParser().parseFromString(html, 'text/html');
287+ if (!doc.body) { return; }
288+ var x = window.scrollX, y = window.scrollY;
289+ adopt(doc, true);
290+ window.scrollTo(x, y);
291+ })
292+ .catch(function () {});
293+ };
294+})();"#;
295+ view! { cx => <script>(Unescaped::new_unchecked(JS))</script> }
296+}
297+
298+/// The live channel's client, iz's shape: a bare tick says *something*
299+/// moved; the page re-fetches itself through the ordinary route — where the
300+/// ordinary gate answers — and morphs with fields and scroll intact. A
301+/// focused field freezes the refresh mid-typing. Mounted only for a signed-in
302+/// viewer, so auth screens never reconnect against a 401.
303+pub async fn live_script(cx: &Cx) -> Result {
304+ use topcoat::view::Unescaped;
305+ const JS: &str = r#"(function () {
306+ if (window.__imLive) { return; }
307+ window.__imLive = true;
308+ var timer = null;
309+ function schedule() {
310+ if (timer) { clearTimeout(timer); }
311+ timer = setTimeout(function () { timer = null; if (window.__imRefresh) { window.__imRefresh(); } }, 200);
312+ }
313+ try {
314+ var src = new EventSource('/live');
315+ src.onmessage = function () { schedule(); };
316+ } catch (err) {}
317+})();"#;
318+ view! { cx => <script>(Unescaped::new_unchecked(JS))</script> }
319+}
320+
186 /// A full document around an already-rendered stage — the same way321 /// A full document around an already-rendered stage — the same way
187 /// izlek-web's `#[layout]` receives its slot. The viewer stamps the chrome:322 /// izlek-web's `#[layout]` receives its slot. The viewer stamps the chrome:
188 /// their theme/language/ui when signed in, English/light/instrument when323 /// 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) -
210 </head>345 </head>
211 <body>346 <body>
212 (stage)347 (stage)
348+ (soft_nav_script(cx).await?)
349+ if viewer.is_some() {
350+ (live_script(cx).await?)
351+ }
213 </body>352 </body>
214 </html>353 </html>
215 }354 }
crates/im-web/src/live.rsmodified+8 -12
@@ -1,11 +1,11 @@
1-//! The live channel: one long-lived connection per open admin tab, carrying1+//! The live channel: one long-lived connection per open signed-in tab,
2-//! the news that something changed — ported from iz's `live.rs`.2+//! carrying the news that something changed — ported from iz's `live.rs`.
3 //!3 //!
4 //! What travels here is a bare tick and nothing else — never a row, never a4 //! What travels here is a bare tick and nothing else — never a row, never a
5-//! name. The client is told only *that* the panel moved, and re-fetches it5+//! name. The client is told only *that* the page moved, and re-fetches it
6-//! through the ordinary route, where the ordinary admin gate answers. The6+//! through the ordinary route, where the ordinary gate answers. Every page
7-//! route itself is admin-gated, and the whole panel behind it is admin-only,7+//! behind it needs the same session the stream asked for, so there is no
8-//! so there is no per-topic filtering to get wrong.8+//! per-topic filtering to get wrong.
9 9
10 use std::time::{Duration, Instant};10 use std::time::{Duration, Instant};
11 11
@@ -36,14 +36,10 @@ const WINDOW: Duration = Duration::from_secs(50 * 60);
36 #[derive(Clone)]36 #[derive(Clone)]
37 pub struct Shutdown(pub tokio::sync::watch::Receiver<bool>);37 pub struct Shutdown(pub tokio::sync::watch::Receiver<bool>);
38 38
39-#[route(GET "/admin/live")]39+#[route(GET "/live")]
40 async fn live(cx: &Cx) -> topcoat::Result<Response> {40 async fn live(cx: &Cx) -> topcoat::Result<Response> {
41 // Resolved once, here, and never again for the life of this connection.41 // Resolved once, here, and never again for the life of this connection.
42- let Ok(_admin) = server::current_user(cx)42+ let Ok(_user) = server::current_user(cx).await.ok_or(()) else {
43- .await
44- .filter(|user| user.admin)
45- .ok_or(())
46- else {
47 return (StatusCode::UNAUTHORIZED, "").into_response(cx);43 return (StatusCode::UNAUTHORIZED, "").into_response(cx);
48 };44 };
49 let rx = server::app(cx).live.subscribe();45 let rx = server::app(cx).live.subscribe();
crates/im-web/src/pages.rsmodified+6 -6
@@ -154,7 +154,7 @@ async fn login_card(cx: &Cx) -> Result {
154 if let Some(code) = error {154 if let Some(code) = error {
155 <div class="auth-problem">(error_text(&code, lang))</div>155 <div class="auth-problem">(error_text(&code, lang))</div>
156 }156 }
157- <form method="post" action="/login">157+ <form method="post" action="/login" data-hard="">
158 <input type="hidden" name="back" value=(back)>158 <input type="hidden" name="back" value=(back)>
159 <label class="auth-field">159 <label class="auth-field">
160 <span class="auth-label">(t(lang, Key::EmailLabel))</span>160 <span class="auth-label">(t(lang, Key::EmailLabel))</span>
@@ -211,7 +211,7 @@ async fn totp(cx: &Cx) -> Result<Response> {
211 if let Some(code) = error {211 if let Some(code) = error {
212 <div class="auth-problem">(error_text(&code, lang))</div>212 <div class="auth-problem">(error_text(&code, lang))</div>
213 }213 }
214- <form method="post" action="/login/totp">214+ <form method="post" action="/login/totp" data-hard="">
215 <label class="auth-field">215 <label class="auth-field">
216 <span class="auth-label">(t(lang, Key::CodeLabel))</span>216 <span class="auth-label">(t(lang, Key::CodeLabel))</span>
217 <input217 <input
@@ -270,7 +270,7 @@ async fn invite(cx: &Cx) -> Result<Response> {
270 if let Some(code) = error {270 if let Some(code) = error {
271 <div class="auth-problem">(error_text(&code, lang))</div>271 <div class="auth-problem">(error_text(&code, lang))</div>
272 }272 }
273- <form method="post" action="/invite">273+ <form method="post" action="/invite" data-hard="">
274 <input type="hidden" name="token" value=(token.to_string())>274 <input type="hidden" name="token" value=(token.to_string())>
275 <div class="auth-field">275 <div class="auth-field">
276 <span class="auth-label">(t(lang, Key::EmailLabel))</span>276 <span class="auth-label">(t(lang, Key::EmailLabel))</span>
@@ -401,7 +401,7 @@ async fn enroll(cx: &Cx) -> Result<Response> {
401 }401 }
402 <div class="auth-qr">(topcoat::view::Unescaped::new_unchecked(qr))</div>402 <div class="auth-qr">(topcoat::view::Unescaped::new_unchecked(qr))</div>
403 <div class="auth-secret">(manual)</div>403 <div class="auth-secret">(manual)</div>
404- <form method="post" action="/enroll">404+ <form method="post" action="/enroll" data-hard="">
405 <label class="auth-field">405 <label class="auth-field">
406 <span class="auth-label">(t(lang, Key::CodeLabel))</span>406 <span class="auth-label">(t(lang, Key::CodeLabel))</span>
407 <input407 <input
@@ -622,7 +622,7 @@ async fn signed_in(cx: &Cx, user: &im_core::model::User) -> Result {
622 <div class="session-list">(topcoat::view::Unescaped::new_unchecked(sessions_html))</div>622 <div class="session-list">(topcoat::view::Unescaped::new_unchecked(sessions_html))</div>
623 </div>623 </div>
624 <div class="auth-card">624 <div class="auth-card">
625- <form method="post" action="/logout">625+ <form method="post" action="/logout" data-hard="">
626 <button class="auth-submit" type="submit">626 <button class="auth-submit" type="submit">
627 <span class="auth-submit-text">(t(lang, Key::SignOutEverywhere))</span>627 <span class="auth-submit-text">(t(lang, Key::SignOutEverywhere))</span>
628 </button>628 </button>
@@ -888,7 +888,7 @@ async fn reset_page(cx: &Cx) -> Result<Response> {
888 if let Some(code) = error {888 if let Some(code) = error {
889 <div class="auth-problem">(error_text(&code, lang))</div>889 <div class="auth-problem">(error_text(&code, lang))</div>
890 }890 }
891- <form method="post" action="/reset">891+ <form method="post" action="/reset" data-hard="">
892 <input type="hidden" name="token" value=(token.to_string())>892 <input type="hidden" name="token" value=(token.to_string())>
893 <label class="auth-field">893 <label class="auth-field">
894 <span class="auth-label">(t(lang, Key::NewPasswordLabel))</span>894 <span class="auth-label">(t(lang, Key::NewPasswordLabel))</span>
crates/im-web/src/server.rsmodified+4 -3
@@ -3,9 +3,10 @@
3 //! and second factor), and the refusal codes a redirect carries back to the3 //! and second factor), and the refusal codes a redirect carries back to the
4 //! page that posted the form.4 //! page that posted the form.
5 //!5 //!
6-//! im serves no client-side script, so there is no refusal-carrying layer as6+//! Every form post answers a plain 303 whose query names the refusal, and
7-//! in İzlek: every form post answers a plain 303 whose query names the7+//! the page reads it back on render. The soft-nav script replays posts over
8-//! refusal, and the page reads it back on render.8+//! fetch with `accept: text/html`, so the 303's target document is what
9+//! comes back — no refusal-carrying layer as in İzlek is needed.
9 10
10 use std::sync::Arc;11 use std::sync::Arc;
11 12