im_old
Clone
https://git.tahinli.com/Tahinli/im_old.git
0 watching·0 forks·Rust·GPL-3.0·755.6 KiB·84318dc·Tahinli·2 months ago·77 commits
| 1 | //! The document shell every im page renders through. No hydration, no |
| 2 | //! runtime script: pages are plain HTML forms, posted hard. |
| 3 | |
| 4 | use im_core::model::User; |
| 5 | use topcoat::Result; |
| 6 | use topcoat::asset::{Asset, asset}; |
| 7 | use topcoat::context::Cx; |
| 8 | use topcoat::view::{BoxView, Child, View, ViewExt, view}; |
| 9 | |
| 10 | use crate::health::{Probe, probe_family}; |
| 11 | use crate::i18n::{Key, Lang, lang_of, t}; |
| 12 | use crate::server; |
| 13 | |
| 14 | /// `style/main.scss`, compiled by `build.rs` into `assets/main.css`. |
| 15 | pub(crate) const STYLE: Asset = asset!("assets/main.css"); |
| 16 | |
| 17 | /// The mark, in the word as it is in the name: lower case, the Turkish |
| 18 | /// tittle. Text-only here — the auth card is the whole chrome. |
| 19 | pub async fn wordmark(cx: &Cx) -> Result<impl View + '_> { |
| 20 | Ok(view! { |
| 21 | cx => |
| 22 | <span class="wordmark"> |
| 23 | <span class="wordmark-text">"im"</span> |
| 24 | </span> |
| 25 | }) |
| 26 | } |
| 27 | |
| 28 | /// The signed-in chrome's wordmark with the family behind it: the `im` |
| 29 | /// mark as above, and the sibling services' wordmarks in a flyout that |
| 30 | /// opens under it on hover and on keyboard focus (the mark is focusable |
| 31 | /// for that), middots between, each a plain link carrying a health dot — |
| 32 | /// the same `/healthz` reading the admin panel's table takes its rows |
| 33 | /// from, green while the sibling answers `ok`, muted while it does not. |
| 34 | /// No script: the flyout is CSS on `:hover` / `:focus-within`. A family |
| 35 | /// with no siblings renders the bare mark — nothing to reveal, nothing |
| 36 | /// to probe. The list is the stored one, the same rows `/family` serves, |
| 37 | /// minus im's own row. |
| 38 | pub async fn family_wordmark(cx: &Cx) -> Result<BoxView<'_>> { |
| 39 | let services = im_core::services::list(&server::app(cx).store).await?; |
| 40 | let siblings = services |
| 41 | .iter() |
| 42 | .filter(|service| service.key != "im") |
| 43 | .collect::<Vec<_>>(); |
| 44 | if siblings.is_empty() { |
| 45 | return wordmark(cx).await.map(ViewExt::boxed); |
| 46 | } |
| 47 | // One shared reading: a render inside the cache window reuses the |
| 48 | // last probe round, so a family member that is down costs its two |
| 49 | // seconds once per window, not once per page view. |
| 50 | let urls = siblings |
| 51 | .iter() |
| 52 | .map(|service| format!("{}/healthz", service.url.trim_end_matches('/'))) |
| 53 | .collect::<Vec<_>>(); |
| 54 | let probes = probe_family(&urls).await; |
| 55 | let rows = siblings |
| 56 | .iter() |
| 57 | .zip(probes) |
| 58 | .map(|(service, probe)| (service.key.as_str(), service.url.as_str(), probe)) |
| 59 | .collect::<Vec<_>>(); |
| 60 | let marks = trio_marks(rows); |
| 61 | Ok(view! { |
| 62 | cx => |
| 63 | <div class="wordmark-family"> |
| 64 | <span class="wordmark" tabindex="0"> |
| 65 | <span class="wordmark-text">"im"</span> |
| 66 | </span> |
| 67 | <nav class="service-trio">(topcoat::view::Unescaped::new_unchecked(marks))</nav> |
| 68 | </div> |
| 69 | } |
| 70 | .boxed()) |
| 71 | } |
| 72 | |
| 73 | /// The flyout's marks as final HTML, pure over resolved probes: im's own |
| 74 | /// row filtered out, every sibling a plain link carrying its probe's dot |
| 75 | /// — `health-on` while it answers `ok`, `health-off` while it does not — |
| 76 | /// middots between. Dots only: the probe's body and latency belong to |
| 77 | /// the admin table, never to the chrome. Extracted from |
| 78 | /// `family_wordmark` so the tests pin this exact markup without a |
| 79 | /// router or an asset bundle. |
| 80 | pub(crate) fn trio_marks<'a>( |
| 81 | rows: impl IntoIterator<Item = (&'a str, &'a str, Probe)>, |
| 82 | ) -> String { |
| 83 | rows.into_iter() |
| 84 | .filter(|(key, _, _)| *key != "im") |
| 85 | .map(|(key, url, probe)| { |
| 86 | let key = crate::pages::escape(key); |
| 87 | let url = crate::pages::escape(url); |
| 88 | let dot = match probe { |
| 89 | Probe::Up { .. } => "health-on", |
| 90 | Probe::Down => "health-off", |
| 91 | }; |
| 92 | format!( |
| 93 | r#"<a class="trio-mark" href="{url}"><span class="health-dot {dot}"></span>{key}</a>"# |
| 94 | ) |
| 95 | }) |
| 96 | .collect::<Vec<_>>() |
| 97 | .join(r#"<span class="trio-sep">·</span>"#) |
| 98 | } |
| 99 | |
| 100 | /// The profile card's face: the photo when the account has one, the name's |
| 101 | /// first letter on a quiet tile when it does not. The URL's `?v=` is the |
| 102 | /// row's `photo_version` — the same number `/directory` answers with — so |
| 103 | /// a changed photo is a changed URL, in this process and in every sibling. |
| 104 | pub async fn avatar<'a>(cx: &'a Cx, user: &'a im_core::model::User) -> Result<BoxView<'a>> { |
| 105 | if user.has_photo { |
| 106 | let src = format!("/photo/{}?v={}", user.id, user.photo_version); |
| 107 | Ok(view! { |
| 108 | cx => |
| 109 | <img class="profile-avatar" src=(src) alt=(user.name.clone())> |
| 110 | } |
| 111 | .boxed()) |
| 112 | } else { |
| 113 | let initial = user |
| 114 | .name |
| 115 | .chars() |
| 116 | .next() |
| 117 | .unwrap_or('?') |
| 118 | .to_uppercase() |
| 119 | .to_string(); |
| 120 | Ok(view! { |
| 121 | cx => |
| 122 | <span class="profile-avatar profile-avatar-initial">(initial)</span> |
| 123 | } |
| 124 | .boxed()) |
| 125 | } |
| 126 | |
| 127 | } |
| 128 | |
| 129 | /// The one script im serves, and the only behavior it carries: the avatar |
| 130 | /// overlay and the picker's autosubmit. A click on a photo `.avatar-view` |
| 131 | /// opens a `.viewer-scrim` around the same `/photo/{id}?v=` URL the avatar |
| 132 | /// reads — the overlay has no server state behind it, so it is client-built |
| 133 | /// and client-closed (scrim click or Escape). A face marked `data-own` gets |
| 134 | /// the photo's Change/Remove inside the viewer, so the page itself carries |
| 135 | /// no buttons for a picture. A `data-autosubmit` input posts its form on |
| 136 | /// change: choosing a file IS the upload, no Save button. Both are delegated |
| 137 | /// document listeners, so the hard-post re-render never needs rewiring. |
| 138 | /// Emitted by the landing and the person page — every surface that draws a |
| 139 | /// clickable face. |
| 140 | pub async fn avatar_script(cx: &Cx, lang: Lang) -> Result<impl View + '_> { |
| 141 | use topcoat::view::Unescaped; |
| 142 | /// Single-quoted into the script below; the staged strings carry no |
| 143 | /// quoting of their own, and this keeps it true if one ever does. |
| 144 | fn js_escape(raw: &str) -> String { |
| 145 | raw.replace('\\', "\\\\").replace('\'', "\\'") |
| 146 | } |
| 147 | const JS_TEMPLATE: &str = "\ |
| 148 | (function () { \ |
| 149 | if (window.__imAvatar) { return; } \ |
| 150 | window.__imAvatar = true; \ |
| 151 | document.addEventListener('click', function (e) { \ |
| 152 | var view = e.target.closest ? e.target.closest('.avatar-view') : null; \ |
| 153 | if (view) { \ |
| 154 | var img = view.querySelector('img.profile-avatar'); \ |
| 155 | if (!img || document.querySelector('.viewer-scrim')) { return; } \ |
| 156 | var scrim = document.createElement('div'); \ |
| 157 | scrim.className = 'viewer-scrim'; \ |
| 158 | var media = document.createElement('img'); \ |
| 159 | media.className = 'viewer-media'; \ |
| 160 | media.src = img.src; \ |
| 161 | media.alt = img.alt; \ |
| 162 | var box = document.createElement('div'); \ |
| 163 | box.className = 'viewer'; \ |
| 164 | box.tabIndex = -1; \ |
| 165 | box.appendChild(media); \ |
| 166 | if (view.hasAttribute('data-own')) { \ |
| 167 | var actions = document.createElement('div'); \ |
| 168 | actions.className = 'viewer-actions'; \ |
| 169 | var change = document.createElement('label'); \ |
| 170 | change.className = 'admin-action'; \ |
| 171 | change.setAttribute('for', 'profile-photo-input'); \ |
| 172 | change.textContent = '__IM_CHANGE__'; \ |
| 173 | var remove = document.createElement('button'); \ |
| 174 | remove.type = 'submit'; \ |
| 175 | remove.className = 'admin-action admin-danger'; \ |
| 176 | remove.setAttribute('form', 'profile-photo-remove'); \ |
| 177 | remove.textContent = '__IM_REMOVE__'; \ |
| 178 | actions.appendChild(change); \ |
| 179 | actions.appendChild(remove); \ |
| 180 | box.appendChild(actions); \ |
| 181 | } \ |
| 182 | scrim.appendChild(box); \ |
| 183 | document.body.appendChild(scrim); \ |
| 184 | box.focus(); \ |
| 185 | return; \ |
| 186 | } \ |
| 187 | if (e.target.classList && e.target.classList.contains('viewer-scrim')) { \ |
| 188 | e.target.remove(); \ |
| 189 | } \ |
| 190 | }); \ |
| 191 | document.addEventListener('keydown', function (e) { \ |
| 192 | if (e.key !== 'Escape') { return; } \ |
| 193 | var scrim = document.querySelector('.viewer-scrim'); \ |
| 194 | if (scrim) { scrim.remove(); } \ |
| 195 | var openSession = document.querySelector('.session-item[open]'); \ |
| 196 | if (openSession) { openSession.removeAttribute('open'); } \ |
| 197 | }); \ |
| 198 | document.addEventListener('change', function (e) { \ |
| 199 | var input = e.target.closest ? e.target.closest('[data-autosubmit]') : null; \ |
| 200 | if (!input || !input.form || input.form.__imUploading) { return; } \ |
| 201 | var form = input.form; \ |
| 202 | var head = input.closest('.profile-head'); \ |
| 203 | if (!head) { form.submit(); return; } \ |
| 204 | /* Captured before the input is disabled — a disabled control \ |
| 205 | is no longer listed, and the post would carry no file. */ \ |
| 206 | var data = new FormData(form); \ |
| 207 | form.__imUploading = true; \ |
| 208 | input.disabled = true; \ |
| 209 | /* The picker may have fired from the viewer's Change — the \ |
| 210 | overlay steps aside so the progress row is the thing seen. */ \ |
| 211 | var openScrim = document.querySelector('.viewer-scrim'); \ |
| 212 | if (openScrim) { openScrim.remove(); } \ |
| 213 | var row = document.createElement('div'); \ |
| 214 | row.className = 'profile-upload-row'; \ |
| 215 | var bar = document.createElement('div'); \ |
| 216 | bar.className = 'upload-progress'; \ |
| 217 | var fill = document.createElement('div'); \ |
| 218 | fill.className = 'upload-progress-fill'; \ |
| 219 | bar.appendChild(fill); \ |
| 220 | row.appendChild(bar); \ |
| 221 | var cancel = document.createElement('button'); \ |
| 222 | cancel.type = 'button'; \ |
| 223 | cancel.className = 'admin-action upload-cancel'; \ |
| 224 | cancel.textContent = '\\u00d7'; \ |
| 225 | cancel.setAttribute('aria-label', '__IM_CANCEL_UPLOAD__'); \ |
| 226 | row.appendChild(cancel); \ |
| 227 | head.insertAdjacentElement('afterend', row); \ |
| 228 | var settle = function () { \ |
| 229 | form.__imUploading = false; \ |
| 230 | input.disabled = false; \ |
| 231 | if (row.parentNode) { row.parentNode.removeChild(row); } \ |
| 232 | }; \ |
| 233 | var x = new XMLHttpRequest(); \ |
| 234 | x.open('POST', form.getAttribute('action')); \ |
| 235 | x.upload.onprogress = function (ev) { \ |
| 236 | if (ev.lengthComputable && ev.total > 0) { \ |
| 237 | fill.style.width = Math.min(100, Math.round((ev.loaded / ev.total) * 100)) + '%'; \ |
| 238 | } \ |
| 239 | }; \ |
| 240 | x.onload = function () { \ |
| 241 | settle(); \ |
| 242 | if (window.__imRefresh) { window.__imRefresh(); return; } \ |
| 243 | window.location.href = x.responseURL || form.getAttribute('action'); \ |
| 244 | }; \ |
| 245 | x.onerror = function () { settle(); form.submit(); }; \ |
| 246 | x.onabort = function () { input.value = ''; settle(); }; \ |
| 247 | cancel.addEventListener('click', function () { x.abort(); }); \ |
| 248 | x.send(data); \ |
| 249 | }); \ |
| 250 | })();"; |
| 251 | let js = JS_TEMPLATE |
| 252 | .replace("__IM_CHANGE__", &js_escape(t(lang, Key::Change))) |
| 253 | .replace("__IM_REMOVE__", &js_escape(t(lang, Key::Remove))) |
| 254 | .replace( |
| 255 | "__IM_CANCEL_UPLOAD__", |
| 256 | &js_escape(t(lang, Key::CancelUploadLabel)), |
| 257 | ); |
| 258 | Ok(view! { cx => <script>(Unescaped::new_unchecked(js))</script> }) |
| 259 | } |
| 260 | |
| 261 | /// Soft navigation, iz's model cut to im's shape: same-app links and form |
| 262 | /// posts are fetched and swapped in place — no full reload, no white flash, |
| 263 | /// no lost scroll on a save. Session-changing forms (sign-in, enroll, |
| 264 | /// redeem, sign-out) carry `data-hard` and post natively; multipart forms |
| 265 | /// belong to the avatar script above and are left to it. Global listeners |
| 266 | /// live on document/window and survive every swap; the guard makes the |
| 267 | /// re-created script a no-op. |
| 268 | pub async fn soft_nav_script(cx: &Cx) -> Result<impl View + '_> { |
| 269 | use topcoat::view::Unescaped; |
| 270 | const JS: &str = r#"(function () { |
| 271 | if (window.__imSoft) { return; } |
| 272 | window.__imSoft = true; |
| 273 | var nav = 0; |
| 274 | function step() { nav += 1; return nav; } |
| 275 | |
| 276 | // Field preservation, izlek's model: only a dirty or focused field is |
| 277 | // worth saving, and the caret offsets come along — a live search typing |
| 278 | // through a refresh keeps both focus and cursor. |
| 279 | function keyOf(el) { |
| 280 | var form = el.form ? (el.form.getAttribute('action') || '') : ''; |
| 281 | return form + '|' + (el.name || '') + '|' + (el.type || '') + '|' + (el.tagName || ''); |
| 282 | } |
| 283 | function editable(el) { |
| 284 | return el.type !== 'hidden' && el.type !== 'password' && el.type !== 'file'; |
| 285 | } |
| 286 | function captureFields() { |
| 287 | var active = document.activeElement, out = []; |
| 288 | document.querySelectorAll('input, textarea, select').forEach(function (el) { |
| 289 | if (!editable(el)) { return; } |
| 290 | var moved; |
| 291 | if (el.type === 'checkbox' || el.type === 'radio') { moved = el.checked !== el.defaultChecked; } |
| 292 | else if (el.tagName === 'SELECT') { |
| 293 | var def = -1; |
| 294 | for (var j = 0; j < el.options.length; j++) { if (el.options[j].defaultSelected) { def = j; break; } } |
| 295 | if (def < 0) { def = 0; } |
| 296 | moved = el.selectedIndex !== def; |
| 297 | } else { moved = el.value !== el.defaultValue; } |
| 298 | var focused = el === active; |
| 299 | if (!moved && !focused) { return; } |
| 300 | var start = -1, end = -1; |
| 301 | try { if (el.selectionStart != null) { start = el.selectionStart; end = el.selectionEnd; } } catch (err) { } |
| 302 | out.push({ k: keyOf(el), v: el.value, c: el.checked, i: el.selectedIndex, f: focused, s: start, e: end }); |
| 303 | }); |
| 304 | return out; |
| 305 | } |
| 306 | function restoreFields(saved) { |
| 307 | if (!saved || !saved.length) { return; } |
| 308 | var fields = document.querySelectorAll('input, textarea, select'); |
| 309 | saved.forEach(function (was) { |
| 310 | var el = null; |
| 311 | for (var i = 0; i < fields.length; i++) { |
| 312 | if (keyOf(fields[i]) === was.k) { el = fields[i]; break; } |
| 313 | } |
| 314 | if (!el) { return; } |
| 315 | if (el.type === 'checkbox' || el.type === 'radio') { el.checked = was.c; } |
| 316 | else if (el.tagName === 'SELECT') { el.selectedIndex = was.i; } |
| 317 | else { el.value = was.v; } |
| 318 | if (was.f) { |
| 319 | try { |
| 320 | el.focus(); |
| 321 | if (was.s >= 0 && el.setSelectionRange) { el.setSelectionRange(was.s, was.e); } |
| 322 | } catch (err) { } |
| 323 | } |
| 324 | }); |
| 325 | } |
| 326 | |
| 327 | function adopt(doc, preserve) { |
| 328 | document.title = doc.title; |
| 329 | var root = doc.documentElement; |
| 330 | ['lang', 'data-theme', 'data-ui'].forEach(function (a) { |
| 331 | if (root.hasAttribute(a)) { document.documentElement.setAttribute(a, root.getAttribute(a)); } |
| 332 | else { document.documentElement.removeAttribute(a); } |
| 333 | }); |
| 334 | var keep = preserve ? captureFields() : null; |
| 335 | document.body.replaceChildren(); |
| 336 | Array.from(doc.body.childNodes).forEach(function (n) { document.body.appendChild(document.importNode(n, true)); }); |
| 337 | document.querySelectorAll('script').forEach(function (old) { |
| 338 | var s = document.createElement('script'); |
| 339 | s.textContent = old.textContent; |
| 340 | old.replaceWith(s); |
| 341 | }); |
| 342 | if (window.__imDdEnhance) { window.__imDdEnhance(); } |
| 343 | if (keep) { restoreFields(keep); } |
| 344 | } |
| 345 | |
| 346 | function swap(html, url, fresh, push) { |
| 347 | var doc = new DOMParser().parseFromString(html, 'text/html'); |
| 348 | if (!doc.body) { location.assign(url); return; } |
| 349 | var x = window.scrollX, y = window.scrollY; |
| 350 | adopt(doc, false); |
| 351 | if (push) { history.pushState(null, '', url); } else { history.replaceState(null, '', url); } |
| 352 | if (fresh) { window.scrollTo(0, 0); } else { window.scrollTo(x, y); } |
| 353 | } |
| 354 | |
| 355 | function go(url, fresh, push) { |
| 356 | var mark = step(); |
| 357 | fetch(url, { headers: { accept: 'text/html' } }) |
| 358 | .then(function (r) { return r.text().then(function (text) { return { text: text, url: r.url }; }); }) |
| 359 | .then(function (res) { if (mark === nav) { swap(res.text, res.url, fresh, push); } }) |
| 360 | .catch(function () { location.assign(url); }); |
| 361 | } |
| 362 | |
| 363 | document.addEventListener('click', function (e) { |
| 364 | if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) { return; } |
| 365 | var a = e.target.closest ? e.target.closest('a') : null; |
| 366 | if (!a || a.target || a.hasAttribute('download') || a.hasAttribute('data-hard')) { return; } |
| 367 | var href = a.getAttribute('href') || ''; |
| 368 | // Same-app paths only: `//host` is protocol-relative — another origin — |
| 369 | // and goes the browser's own way. |
| 370 | if (href.indexOf('/') !== 0 || href.indexOf('//') === 0) { return; } |
| 371 | e.preventDefault(); |
| 372 | go(href, true, true); |
| 373 | }, true); |
| 374 | |
| 375 | document.addEventListener('submit', function (e) { |
| 376 | var form = e.target; |
| 377 | if (!form || !form.action || form.hasAttribute('data-hard')) { return; } |
| 378 | if ((form.enctype || '').indexOf('multipart') === 0) { return; } |
| 379 | if ((form.method || 'get').toLowerCase() === 'get') { |
| 380 | e.preventDefault(); |
| 381 | var q = new URLSearchParams(new FormData(form)).toString(); |
| 382 | go(form.action.split('?')[0] + (q ? '?' + q : ''), true, true); |
| 383 | return; |
| 384 | } |
| 385 | e.preventDefault(); |
| 386 | var mark = step(); |
| 387 | var data = new FormData(form); |
| 388 | if (e.submitter && e.submitter.name) { data.append(e.submitter.name, e.submitter.value); } |
| 389 | fetch(form.action, { method: 'POST', headers: { accept: 'text/html' }, body: new URLSearchParams(data) }) |
| 390 | .then(function (r) { return r.text().then(function (text) { return { text: text, url: r.url }; }); }) |
| 391 | .then(function (res) { if (mark === nav) { swap(res.text, res.url, false, false); } }) |
| 392 | .catch(function () { form.submit(); }); |
| 393 | }); |
| 394 | |
| 395 | window.addEventListener('popstate', function () { go(location.pathname + location.search, false, false); }); |
| 396 | |
| 397 | // Filter controls submit their form on pick; file inputs with |
| 398 | // data-autosubmit belong to the avatar script's uploader, not to this. |
| 399 | document.addEventListener('change', function (e) { |
| 400 | var c = e.target && e.target.closest ? e.target.closest('[data-autosubmit]') : null; |
| 401 | if (!c || !c.form || c.type === 'file') { return; } |
| 402 | c.form.requestSubmit(); |
| 403 | }); |
| 404 | |
| 405 | // izlek's __izQuery: a filtered view asked for in place — the URL swaps |
| 406 | // under replaceState (no history entry per keystroke), fields and caret |
| 407 | // come through the adopt. |
| 408 | window.__imQuery = function (url) { |
| 409 | var mark = step(); |
| 410 | fetch(url, { headers: { accept: 'text/html' } }) |
| 411 | .then(function (r) { return r.text().then(function (text) { return { text: text, url: r.url }; }); }) |
| 412 | .then(function (res) { |
| 413 | if (mark !== nav) { return; } |
| 414 | var doc = new DOMParser().parseFromString(res.text, 'text/html'); |
| 415 | if (!doc.body) { return; } |
| 416 | var x = window.scrollX, y = window.scrollY; |
| 417 | adopt(doc, true); |
| 418 | history.replaceState(null, '', res.url); |
| 419 | window.scrollTo(x, y); |
| 420 | }) |
| 421 | .catch(function () {}); |
| 422 | }; |
| 423 | |
| 424 | // The logs search box: two hundred still milliseconds after the last key, |
| 425 | // the whole filter form rides the query — kind, actor, dates, direction |
| 426 | // and q together. |
| 427 | var searchTimer = null; |
| 428 | document.addEventListener('input', function (e) { |
| 429 | var el = e.target; |
| 430 | if (!el || el.name !== 'q' || !el.closest || !el.closest('.logs-filters')) { return; } |
| 431 | if (searchTimer) { clearTimeout(searchTimer); } |
| 432 | searchTimer = setTimeout(function () { |
| 433 | searchTimer = null; |
| 434 | if (!el.form) { return; } |
| 435 | window.__imQuery((el.form.getAttribute('action') || location.pathname) + '?' + new URLSearchParams(new FormData(el.form)).toString()); |
| 436 | }, 200); |
| 437 | }); |
| 438 | |
| 439 | // The panel's own refresh: a tick says something moved and the page |
| 440 | // re-reads itself in place. While a show-once banner (a fresh client |
| 441 | // secret) stands, the refresh holds — the banner is a one-render affair, |
| 442 | // and a re-read would find the shelf empty and wipe it. The panel |
| 443 | // catches up on the next tick once the admin has moved on. |
| 444 | window.__imRefresh = function () { |
| 445 | if (document.querySelector('.auth-secret')) { return; } |
| 446 | fetch(location.href, { headers: { accept: 'text/html' } }) |
| 447 | .then(function (r) { return r.text(); }) |
| 448 | .then(function (html) { |
| 449 | var doc = new DOMParser().parseFromString(html, 'text/html'); |
| 450 | if (!doc.body) { return; } |
| 451 | var x = window.scrollX, y = window.scrollY; |
| 452 | adopt(doc, true); |
| 453 | window.scrollTo(x, y); |
| 454 | }) |
| 455 | .catch(function () {}); |
| 456 | }; |
| 457 | })();"#; |
| 458 | Ok(view! { cx => <script>(Unescaped::new_unchecked(JS))</script> }) |
| 459 | } |
| 460 | |
| 461 | /// The live channel's client, iz's shape: a bare tick says *something* |
| 462 | /// moved; the page re-fetches itself through the ordinary route — where the |
| 463 | /// ordinary gate answers — and morphs with fields and scroll intact. A |
| 464 | /// focused field freezes the refresh mid-typing. Mounted only for a signed-in |
| 465 | /// viewer, so auth screens never reconnect against a 401. A `revoked` |
| 466 | /// frame — the eviction news, addressed — or a probe answering 401 sends |
| 467 | /// the tab home instead of re-reading. |
| 468 | pub async fn live_script(cx: &Cx) -> Result<impl View + '_> { |
| 469 | use topcoat::view::Unescaped; |
| 470 | const JS: &str = r#"(function () { |
| 471 | if (window.__imLive) { return; } |
| 472 | window.__imLive = true; |
| 473 | var timer = null; |
| 474 | function schedule() { |
| 475 | if (timer) { clearTimeout(timer); } |
| 476 | timer = setTimeout(function () { timer = null; if (window.__imRefresh) { window.__imRefresh(); } }, 200); |
| 477 | } |
| 478 | try { |
| 479 | var src = new EventSource('/live'); |
| 480 | src.onmessage = function () { schedule(); }; |
| 481 | // A sign-out in motion: this tab's own session was revoked — go home. |
| 482 | src.addEventListener('revoked', function () { location.href = '/'; }); |
| 483 | // A dropped stream reconnects by itself, but one that keeps dying |
| 484 | // against a revoked session is news: the bare probe says whether the |
| 485 | // session still stands. |
| 486 | src.onerror = function () { |
| 487 | fetch('/api/me').then(function (r) { |
| 488 | if (r.status === 401) { location.href = '/'; } |
| 489 | }).catch(function () {}); |
| 490 | }; |
| 491 | } catch (err) {} |
| 492 | })();"#; |
| 493 | Ok(view! { cx => <script>(Unescaped::new_unchecked(JS))</script> }) |
| 494 | } |
| 495 | |
| 496 | /// A full document around an already-rendered stage — the same way |
| 497 | /// izlek-web's `#[layout]` receives its slot. The viewer stamps the chrome: |
| 498 | /// their theme/language/ui when signed in, English/light/instrument when |
| 499 | /// not — mirroring iz's root_layout, minus its build stamp. |
| 500 | pub async fn shell<'a>( |
| 501 | cx: &'a Cx, |
| 502 | title: impl Into<String>, |
| 503 | viewer: Option<User>, |
| 504 | stage: Child<'a>, |
| 505 | ) -> Result<impl View + 'a> { |
| 506 | let title = title.into(); |
| 507 | let lang = lang_of(viewer.as_ref()); |
| 508 | let dark = viewer.as_ref().is_some_and(|user| user.theme == "dark"); |
| 509 | let ui = viewer |
| 510 | .as_ref() |
| 511 | .map_or("instrument", |user| user.ui.as_str()) |
| 512 | .to_string(); |
| 513 | let live = viewer.is_some(); |
| 514 | Ok(view! { |
| 515 | cx => |
| 516 | <!DOCTYPE html> |
| 517 | <html lang=(lang.code()) data-theme=(dark.then_some("dark")) data-ui=(ui)> |
| 518 | <head> |
| 519 | <meta charset="utf-8"> |
| 520 | <meta name="viewport" content="width=device-width, initial-scale=1"> |
| 521 | <link rel="preconnect" href="https://fonts.googleapis.com"> |
| 522 | <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin=""> |
| 523 | <link |
| 524 | rel="stylesheet" |
| 525 | href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500&display=swap" |
| 526 | > |
| 527 | <title>(title)</title> |
| 528 | <link rel="stylesheet" href=(STYLE)> |
| 529 | </head> |
| 530 | <body> |
| 531 | (stage) |
| 532 | (soft_nav_script(cx).await?.first().await?) |
| 533 | if live { |
| 534 | (live_script(cx).await?.first().await?) |
| 535 | (crate::dropdown::dropdown_script(cx).await?.first().await?) |
| 536 | } |
| 537 | </body> |
| 538 | </html> |
| 539 | }) |
| 540 | } |