//! The document shell every im page renders through. No hydration, no //! runtime script: pages are plain HTML forms, posted hard. use im_core::model::User; use topcoat::Result; use topcoat::asset::{Asset, asset}; use topcoat::context::Cx; use topcoat::view::{BoxView, Child, View, ViewExt, view}; use crate::health::{Probe, probe_family}; use crate::i18n::{Key, Lang, lang_of, t}; use crate::server; /// `style/main.scss`, compiled by `build.rs` into `assets/main.css`. pub(crate) const STYLE: Asset = asset!("assets/main.css"); /// The mark, in the word as it is in the name: lower case, the Turkish /// tittle. Text-only here — the auth card is the whole chrome. pub async fn wordmark(cx: &Cx) -> Result { Ok(view! { cx => "im" }) } /// The signed-in chrome's wordmark with the family behind it: the `im` /// mark as above, and the sibling services' wordmarks in a flyout that /// opens under it on hover and on keyboard focus (the mark is focusable /// for that), middots between, each a plain link carrying a health dot — /// the same `/healthz` reading the admin panel's table takes its rows /// from, green while the sibling answers `ok`, muted while it does not. /// No script: the flyout is CSS on `:hover` / `:focus-within`. A family /// with no siblings renders the bare mark — nothing to reveal, nothing /// to probe. The list is the stored one, the same rows `/family` serves, /// minus im's own row. pub async fn family_wordmark(cx: &Cx) -> Result> { let services = im_core::services::list(&server::app(cx).store).await?; let siblings = services .iter() .filter(|service| service.key != "im") .collect::>(); if siblings.is_empty() { return wordmark(cx).await.map(ViewExt::boxed); } // One shared reading: a render inside the cache window reuses the // last probe round, so a family member that is down costs its two // seconds once per window, not once per page view. let urls = siblings .iter() .map(|service| format!("{}/healthz", service.url.trim_end_matches('/'))) .collect::>(); let probes = probe_family(&urls).await; let rows = siblings .iter() .zip(probes) .map(|(service, probe)| (service.key.as_str(), service.url.as_str(), probe)) .collect::>(); let marks = trio_marks(rows); Ok(view! { cx =>
"im"
} .boxed()) } /// The flyout's marks as final HTML, pure over resolved probes: im's own /// row filtered out, every sibling a plain link carrying its probe's dot /// — `health-on` while it answers `ok`, `health-off` while it does not — /// middots between. Dots only: the probe's body and latency belong to /// the admin table, never to the chrome. Extracted from /// `family_wordmark` so the tests pin this exact markup without a /// router or an asset bundle. pub(crate) fn trio_marks<'a>( rows: impl IntoIterator, ) -> String { rows.into_iter() .filter(|(key, _, _)| *key != "im") .map(|(key, url, probe)| { let key = crate::pages::escape(key); let url = crate::pages::escape(url); let dot = match probe { Probe::Up { .. } => "health-on", Probe::Down => "health-off", }; format!( r#"{key}"# ) }) .collect::>() .join(r#"·"#) } /// The profile card's face: the photo when the account has one, the name's /// first letter on a quiet tile when it does not. The URL's `?v=` is the /// row's `photo_version` — the same number `/directory` answers with — so /// a changed photo is a changed URL, in this process and in every sibling. pub async fn avatar<'a>(cx: &'a Cx, user: &'a im_core::model::User) -> Result> { if user.has_photo { let src = format!("/photo/{}?v={}", user.id, user.photo_version); Ok(view! { cx => (user.name.clone()) } .boxed()) } else { let initial = user .name .chars() .next() .unwrap_or('?') .to_uppercase() .to_string(); Ok(view! { cx => (initial) } .boxed()) } } /// The one script im serves, and the only behavior it carries: the avatar /// overlay and the picker's autosubmit. A click on a photo `.avatar-view` /// opens a `.viewer-scrim` around the same `/photo/{id}?v=` URL the avatar /// reads — the overlay has no server state behind it, so it is client-built /// and client-closed (scrim click or Escape). A face marked `data-own` gets /// the photo's Change/Remove inside the viewer, so the page itself carries /// no buttons for a picture. A `data-autosubmit` input posts its form on /// change: choosing a file IS the upload, no Save button. Both are delegated /// document listeners, so the hard-post re-render never needs rewiring. /// Emitted by the landing and the person page — every surface that draws a /// clickable face. pub async fn avatar_script(cx: &Cx, lang: Lang) -> Result { use topcoat::view::Unescaped; /// Single-quoted into the script below; the staged strings carry no /// quoting of their own, and this keeps it true if one ever does. fn js_escape(raw: &str) -> String { raw.replace('\\', "\\\\").replace('\'', "\\'") } const JS_TEMPLATE: &str = "\ (function () { \ if (window.__imAvatar) { return; } \ window.__imAvatar = true; \ document.addEventListener('click', function (e) { \ var view = e.target.closest ? e.target.closest('.avatar-view') : null; \ if (view) { \ var img = view.querySelector('img.profile-avatar'); \ if (!img || document.querySelector('.viewer-scrim')) { return; } \ var scrim = document.createElement('div'); \ scrim.className = 'viewer-scrim'; \ var media = document.createElement('img'); \ media.className = 'viewer-media'; \ media.src = img.src; \ media.alt = img.alt; \ var box = document.createElement('div'); \ box.className = 'viewer'; \ box.tabIndex = -1; \ box.appendChild(media); \ if (view.hasAttribute('data-own')) { \ var actions = document.createElement('div'); \ actions.className = 'viewer-actions'; \ var change = document.createElement('label'); \ change.className = 'admin-action'; \ change.setAttribute('for', 'profile-photo-input'); \ change.textContent = '__IM_CHANGE__'; \ var remove = document.createElement('button'); \ remove.type = 'submit'; \ remove.className = 'admin-action admin-danger'; \ remove.setAttribute('form', 'profile-photo-remove'); \ remove.textContent = '__IM_REMOVE__'; \ actions.appendChild(change); \ actions.appendChild(remove); \ box.appendChild(actions); \ } \ scrim.appendChild(box); \ document.body.appendChild(scrim); \ box.focus(); \ return; \ } \ if (e.target.classList && e.target.classList.contains('viewer-scrim')) { \ e.target.remove(); \ } \ }); \ document.addEventListener('keydown', function (e) { \ if (e.key !== 'Escape') { return; } \ var scrim = document.querySelector('.viewer-scrim'); \ if (scrim) { scrim.remove(); } \ var openSession = document.querySelector('.session-item[open]'); \ if (openSession) { openSession.removeAttribute('open'); } \ }); \ document.addEventListener('change', function (e) { \ var input = e.target.closest ? e.target.closest('[data-autosubmit]') : null; \ if (!input || !input.form || input.form.__imUploading) { return; } \ var form = input.form; \ var head = input.closest('.profile-head'); \ if (!head) { form.submit(); return; } \ /* Captured before the input is disabled — a disabled control \ is no longer listed, and the post would carry no file. */ \ var data = new FormData(form); \ form.__imUploading = true; \ input.disabled = true; \ /* The picker may have fired from the viewer's Change — the \ overlay steps aside so the progress row is the thing seen. */ \ var openScrim = document.querySelector('.viewer-scrim'); \ if (openScrim) { openScrim.remove(); } \ var row = document.createElement('div'); \ row.className = 'profile-upload-row'; \ var bar = document.createElement('div'); \ bar.className = 'upload-progress'; \ var fill = document.createElement('div'); \ fill.className = 'upload-progress-fill'; \ bar.appendChild(fill); \ row.appendChild(bar); \ var cancel = document.createElement('button'); \ cancel.type = 'button'; \ cancel.className = 'admin-action upload-cancel'; \ cancel.textContent = '\\u00d7'; \ cancel.setAttribute('aria-label', '__IM_CANCEL_UPLOAD__'); \ row.appendChild(cancel); \ head.insertAdjacentElement('afterend', row); \ var settle = function () { \ form.__imUploading = false; \ input.disabled = false; \ if (row.parentNode) { row.parentNode.removeChild(row); } \ }; \ var x = new XMLHttpRequest(); \ x.open('POST', form.getAttribute('action')); \ x.upload.onprogress = function (ev) { \ if (ev.lengthComputable && ev.total > 0) { \ fill.style.width = Math.min(100, Math.round((ev.loaded / ev.total) * 100)) + '%'; \ } \ }; \ x.onload = function () { \ settle(); \ if (window.__imRefresh) { window.__imRefresh(); return; } \ window.location.href = x.responseURL || form.getAttribute('action'); \ }; \ x.onerror = function () { settle(); form.submit(); }; \ x.onabort = function () { input.value = ''; settle(); }; \ cancel.addEventListener('click', function () { x.abort(); }); \ x.send(data); \ }); \ })();"; let js = JS_TEMPLATE .replace("__IM_CHANGE__", &js_escape(t(lang, Key::Change))) .replace("__IM_REMOVE__", &js_escape(t(lang, Key::Remove))) .replace( "__IM_CANCEL_UPLOAD__", &js_escape(t(lang, Key::CancelUploadLabel)), ); Ok(view! { cx => }) } /// 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; } // Field preservation, izlek's model: only a dirty or focused field is // worth saving, and the caret offsets come along — a live search typing // through a refresh keeps both focus and cursor. function keyOf(el) { var form = el.form ? (el.form.getAttribute('action') || '') : ''; return form + '|' + (el.name || '') + '|' + (el.type || '') + '|' + (el.tagName || ''); } function editable(el) { return el.type !== 'hidden' && el.type !== 'password' && el.type !== 'file'; } function captureFields() { var active = document.activeElement, out = []; document.querySelectorAll('input, textarea, select').forEach(function (el) { if (!editable(el)) { return; } var moved; if (el.type === 'checkbox' || el.type === 'radio') { moved = el.checked !== el.defaultChecked; } else if (el.tagName === 'SELECT') { var def = -1; for (var j = 0; j < el.options.length; j++) { if (el.options[j].defaultSelected) { def = j; break; } } if (def < 0) { def = 0; } moved = el.selectedIndex !== def; } else { moved = el.value !== el.defaultValue; } var focused = el === active; if (!moved && !focused) { return; } var start = -1, end = -1; try { if (el.selectionStart != null) { start = el.selectionStart; end = el.selectionEnd; } } catch (err) { } out.push({ k: keyOf(el), v: el.value, c: el.checked, i: el.selectedIndex, f: focused, s: start, e: end }); }); return out; } function restoreFields(saved) { if (!saved || !saved.length) { return; } var fields = document.querySelectorAll('input, textarea, select'); saved.forEach(function (was) { var el = null; for (var i = 0; i < fields.length; i++) { if (keyOf(fields[i]) === was.k) { el = fields[i]; break; } } if (!el) { return; } if (el.type === 'checkbox' || el.type === 'radio') { el.checked = was.c; } else if (el.tagName === 'SELECT') { el.selectedIndex = was.i; } else { el.value = was.v; } if (was.f) { try { el.focus(); if (was.s >= 0 && el.setSelectionRange) { el.setSelectionRange(was.s, was.e); } } catch (err) { } } }); } 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 keep = preserve ? captureFields() : null; 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 (window.__imDdEnhance) { window.__imDdEnhance(); } if (keep) { restoreFields(keep); } } 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') || ''; // Same-app paths only: `//host` is protocol-relative — another origin — // and goes the browser's own way. if (href.indexOf('/') !== 0 || 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); }); // Filter controls submit their form on pick; file inputs with // data-autosubmit belong to the avatar script's uploader, not to this. document.addEventListener('change', function (e) { var c = e.target && e.target.closest ? e.target.closest('[data-autosubmit]') : null; if (!c || !c.form || c.type === 'file') { return; } c.form.requestSubmit(); }); // izlek's __izQuery: a filtered view asked for in place — the URL swaps // under replaceState (no history entry per keystroke), fields and caret // come through the adopt. window.__imQuery = function (url) { 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) { return; } var doc = new DOMParser().parseFromString(res.text, 'text/html'); if (!doc.body) { return; } var x = window.scrollX, y = window.scrollY; adopt(doc, true); history.replaceState(null, '', res.url); window.scrollTo(x, y); }) .catch(function () {}); }; // The logs search box: two hundred still milliseconds after the last key, // the whole filter form rides the query — kind, actor, dates, direction // and q together. var searchTimer = null; document.addEventListener('input', function (e) { var el = e.target; if (!el || el.name !== 'q' || !el.closest || !el.closest('.logs-filters')) { return; } if (searchTimer) { clearTimeout(searchTimer); } searchTimer = setTimeout(function () { searchTimer = null; if (!el.form) { return; } window.__imQuery((el.form.getAttribute('action') || location.pathname) + '?' + new URLSearchParams(new FormData(el.form)).toString()); }, 200); }); // The panel's own refresh: a tick says something moved and the page // re-reads itself in place. While a show-once banner (a fresh client // secret) stands, the refresh holds — the banner is a one-render affair, // and a re-read would find the shelf empty and wipe it. The panel // catches up on the next tick once the admin has moved on. window.__imRefresh = function () { if (document.querySelector('.auth-secret')) { 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 () {}); }; })();"#; Ok(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. A `revoked` /// frame — the eviction news, addressed — or a probe answering 401 sends /// the tab home instead of re-reading. 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(); }; // A sign-out in motion: this tab's own session was revoked — go home. src.addEventListener('revoked', function () { location.href = '/'; }); // A dropped stream reconnects by itself, but one that keeps dying // against a revoked session is news: the bare probe says whether the // session still stands. src.onerror = function () { fetch('/api/me').then(function (r) { if (r.status === 401) { location.href = '/'; } }).catch(function () {}); }; } catch (err) {} })();"#; Ok(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 /// not — mirroring iz's root_layout, minus its build stamp. pub async fn shell<'a>( cx: &'a Cx, title: impl Into, viewer: Option, stage: Child<'a>, ) -> Result { let title = title.into(); let lang = lang_of(viewer.as_ref()); let dark = viewer.as_ref().is_some_and(|user| user.theme == "dark"); let ui = viewer .as_ref() .map_or("instrument", |user| user.ui.as_str()) .to_string(); let live = viewer.is_some(); Ok(view! { cx => (title) (stage) (soft_nav_script(cx).await?.first().await?) if live { (live_script(cx).await?.first().await?) (crate::dropdown::dropdown_script(cx).await?.first().await?) } }) }