//! The document shell every page renders inside: the monogram, the wordmark, //! the topbar, the client scripts, and the root layout with its 404 catch. //! //! The one document-level contract with the client lives in the scripts at //! the bottom — `soft_nav_script`, `search_script`, `live_script` and the //! escape manager — and the morph ownership flags they define (`__inOwn`, //! `__inAdded`, `__inNav`). use topcoat::{ Result, asset::{Asset, asset}, context::Cx, router::{ StatusCode, error::{NotFoundError, not_found}, layout, page, request::uri, }, view::{Unescaped, View, ViewExt, error_boundary, view}, }; use in_core::store::User; use crate::health::{family_probes, Probe}; use crate::i18n::{Key, Lang, t}; use crate::server::{app, current_user}; /// The in monogram again, as the tab icon: the same drawing as `mark`, /// inlined because it must carry its own colours — a data URI has no page to /// inherit `currentColor` or the accent token from, so the two themes are /// spelled out in a media query inside the SVG. const FAVICON: &str = "data:image/svg+xml,\ \ \ \ \ "; /// The in monogram — a dotted `i` beside a stroked `n`. It takes /// `currentColor` for its strokes and the accent for its tittle, so one /// drawing serves both skins and both themes. /// /// The monogram and the wordmark are alternates, never a pair: standing them /// side by side reads as a stutter no amount of space or framing repairs. /// The mark carries the chrome, where the name is already known and the room /// is 44px; the word carries the front door, where a stranger arrives and /// nothing else has said it yet. pub(crate) async fn mark<'a>(cx: &'a Cx) -> Result { Ok(view! { cx => } .boxed()) } /// The wordmark, the monogram's other half: the name alone, in the one face /// both skins agree on. The sign-in page wears it — see `mark`. pub(crate) async fn wordmark<'a>(cx: &'a Cx) -> Result { Ok(view! { cx => "in" } .boxed()) } /// A person as a circle (or, on the Instrument skin, a square): the initials, /// toned by the id so every account has its own colour, with the im photo /// over it when im has one. Whether im has one is not known cheaply — the /// photo is the app's credentialed fetch, not the browser's — so the `` /// always renders and hides itself on error (see `avatar_script`), leaving /// the initials beneath as the fallback. Shared by the topbar user menu on /// every signed-in page. pub(crate) async fn avatar<'a>( cx: &'a Cx, user: &'a User, extra: &'a str, ) -> Result { let tone = user .id .bytes() .fold(0u32, |acc, b| acc.wrapping_mul(31).wrapping_add(b as u32)) % 5; let class = format!("avatar avatar-tone-{tone} {extra}"); let name = user.display_name.clone(); let initials = initials_of(&user.display_name); let src = format!("/avatar/{}?v={}", user.id, user.photo_version); Ok(view! { cx => (initials) } .boxed()) } /// The photo half's client half: a missing photo must fall back to the /// initials beneath it, and a bare `` to a 404 shows the broken-image /// box instead. One document-level capture `error` listener hides every /// `img.avatar-photo` that fails, plus a sweep for the ones already failed /// before it ran; hiding is registered through `__inOwn` so the live morph /// — which owns no names, only what the client declares — does not strip it /// back off on the next refresh. pub async fn avatar_script<'a>(cx: &'a Cx) -> Result { use topcoat::view::Unescaped; const JS: &str = "\ (function () { \ if (window.__inAvatar) { return; } \ window.__inAvatar = true; \ function hide(img) { \ if (window.__inOwn) { window.__inOwn(img, [], ['style']); } \ img.style.display = 'none'; \ } \ document.addEventListener('error', function (e) { \ var img = e.target && e.target.closest ? e.target.closest('img.avatar-photo') : null; \ if (img) { hide(img); } \ }, true); \ document.querySelectorAll('img.avatar-photo').forEach(function (img) { \ if (img.complete && img.naturalWidth === 0) { hide(img); } \ }); \ })();"; Ok(view! { cx => }.boxed()) } /// The first letters of the first two words, uppercased — "Ada Lovelace" /// wears "AL", a bare address wears its first letter. fn initials_of(name: &str) -> String { let mut out = String::new(); for word in name.split_whitespace().take(2) { if let Some(first) = word.chars().next() { out.extend(first.to_uppercase()); } } if out.is_empty() { out.push('?'); } out } /// The topbar's signed-in identity: the display name, opening on hover or /// focus onto details (name, address) and sign-out. Shared by every /// signed-in page's topbar. pub async fn user_menu<'a>(cx: &'a Cx, user: &'a User, lang: Lang) -> Result { Ok(view! { cx =>
(user.display_name.clone())
(user.email.clone())
if user.admin {
(t(lang, Key::AdminBadge))
} (t(lang, Key::Profile)) (t(lang, Key::NavSettings)) (t(lang, Key::SignOut))
}.boxed()) } /// The signed-in pages, as the topbar nav links between them. #[derive(Clone, Copy, PartialEq)] pub enum NavPage { Drive, Shared, Trash, Settings, } impl NavPage { /// Settings is deliberately absent: it lives in the user menu, not the /// page nav — the variant stays so the settings page can still name /// itself active without a link to mark. const ALL: [Self; 3] = [Self::Drive, Self::Shared, Self::Trash]; fn href(self) -> &'static str { match self { Self::Drive => "/drive", Self::Shared => "/shared", Self::Trash => "/trash", Self::Settings => "/settings", } } fn label(self) -> Key { match self { Self::Drive => Key::NavDrive, Self::Shared => Key::NavShared, Self::Trash => Key::NavTrash, Self::Settings => Key::NavSettings, } } } /// The topbar's page nav, shared by every signed-in page, with the current /// one marked. Plain ``s — the soft-nav forwarder swaps them like any /// same-origin link, so `data-hard` stays off. pub async fn topbar_nav<'a>(cx: &'a Cx, active: NavPage, lang: Lang) -> Result { Ok(view! { cx => } .boxed()) } /// This app's key in the family list: the entry matching it is the one /// marked as where the reader already is. const SELF_KEY: &str = "in"; /// The suite list as im keeps it, mirrored into the `setting` store under /// `family` by the background fetch that started at boot. A list that is /// absent, or not parseable JSON, reads as empty — a suite nobody told /// this app about keeps the chrome exactly as it has always been. async fn family_of(cx: &Cx) -> Vec { match app(cx).store.get_setting("family").await { Ok(Some(raw)) => serde_json::from_str(&raw).unwrap_or_default(), _ => Vec::new(), } } /// The monogram with the family behind it: the in mark as ever, and the /// sibling services' wordmarks in a flyout that opens under it on hover /// and on keyboard focus — the mark is an ``, so it is already /// focusable and `:focus-within` needs nothing added. Middots between, /// each a plain link to the service's own address, carrying its health /// dot — the same `/healthz` reading: green while the sibling answers /// `ok`, muted while it does not. The cross-origin hop navigates the /// browser natively. No script: the flyout is CSS on /// `:hover` / `:focus-within`, and it stays in the DOM at opacity zero so /// Tab reaches its links. A family that is absent, or holds no one but /// this app, renders the bare mark — there is nothing to reveal. async fn family_mark<'a>(cx: &'a Cx) -> Result { let family = family_of(cx).await; let siblings: Vec<_> = family .into_iter() .filter(|service| service.key != SELF_KEY) .collect(); if siblings.is_empty() { return mark(cx).await.map(|v| v.boxed()); } // Every probe at once, one reading shared per window: a family member // that is down costs its two seconds once per half minute, not on // every page the reader opens. let asked: Vec<(&str, &str)> = siblings .iter() .map(|service| (service.key.as_str(), service.url.as_str())) .collect(); let probes = family_probes(&asked).await; let rows: Vec<_> = siblings .iter() .zip(probes) .map(|(service, probe)| { ( service.key.as_str(), service.url.as_str(), service.name.as_str(), probe, ) }) .collect(); let marks = switcher_marks(rows); Ok(view! { cx =>
(topcoat::view::Child::new(mark(cx).await?))
} .boxed()) } /// The flyout's marks as final HTML, pure over resolved probes: 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 never reach /// the chrome. Extracted from `family_mark` so the tests pin this exact /// markup without a router or an asset bundle. pub fn switcher_marks<'a>( rows: impl IntoIterator, ) -> String { rows.into_iter() .map(|(key, url, name, probe)| { let key = escape(key); let url = escape(url); let name = escape(name); let dot = match probe { Probe::Up { .. } => "health-on", Probe::Down => "health-off", }; format!( r#"
{key}"# ) }) .collect::>() .join(r#"·"#) } /// Everything the flyout's marks interpolate crosses them as raw HTML — /// key, address, title — so each passes through `escape` first: the same /// discipline im's chrome keeps, anything the family list carries is /// escaped before it reaches the markup. fn escape(raw: &str) -> String { raw.replace('&', "&") .replace('<', "<") .replace('>', ">") .replace('"', """) } /// The signed-in chrome: the monogram with the family behind it, the page /// nav, the identity menu. Wave-2 pages render their content under this. pub async fn topbar<'a>( cx: &'a Cx, active: NavPage, user: &'a User, lang: Lang, ) -> Result { Ok(view! { cx =>
(topcoat::view::Child::new(family_mark(cx).await?)) (topcoat::view::Child::new(topbar_nav(cx, active, lang).await?)) (topcoat::view::Child::new(user_menu(cx, user, lang).await?))
(topcoat::view::Child::new(avatar_script(cx).await?)) } .boxed()) } /// The page-swap machinery that keeps every mutation on the same document. /// /// Every `/api/*` mutation is a plain form post answered with a 303 — sound /// without script, but a full navigation repaints the whole page for a /// one-field change. This script, emitted first in `` on every page, /// intercepts those submits (capture-phase, so `requestSubmit()` from any /// auto-submit control lands here too), replays them over `fetch`, and swaps /// the redirected page's `` children in place — same bytes the hard /// navigation would have shown, no reload. Refusal banners and saved chips /// arrive with the swap because the redirect URL's query params rendered /// them server-side; `history.replaceState` keeps the address bar honest. /// /// The replay declares `Accept: text/html`, because a replayed form post is a /// form post asking for the page back: `carry_refusal_on_redirect` /// (`server.rs`) copies a refusing 303's answer onto the `Location` only for a /// caller that wants the page, and a bare `fetch` asks for `*/*` — under which /// the refusal stayed in a body nobody reads and the click looked like nothing /// happening. A refused save and a clean one once landed on the same silent /// page; the header is what keeps them apart. /// /// Every fetch that ends in a swap carries the navigation counter it started /// under (`window.__inNav`), and its answer is thrown away if that counter /// has moved. Without it the newest paint is not the newest intent: the live /// refresh fetches the URL it was on, and a click landing during that flight /// pushed a new page that the refresh's answer then overwrote — the page /// arriving and reverting to the previous one two hundred milliseconds later. /// Navigations, form posts and the overlay closes each step the counter, so a /// second click also wins over a first one still in flight, and a refresh — /// which is not an intent, only an update of what is already on screen — /// steps nothing and lands only if nothing else has happened. /// /// The address bar and the `` attributes are rewritten *before* the /// new body's scripts run, never after: a swapped-in script that reads /// `location.href` (the log-fit reload in `logs.rs`) would otherwise read /// the page it just replaced and hard-navigate back to it. /// /// Swapped-in ` }.boxed()) } /// Live search: the filterbar's `q` box fetches its page as the user types — /// debounced, morphed in place through `__inQuery`, the URL replaced rather /// than pushed so a keystroke never becomes a history entry. The listener is /// delegated on `document`, so the morph cannot orphan it; the value is /// deduped against the last one fetched, so an unchanged box never refetches; /// and `__inKeep` carries the box's value, focus and caret across the swap, /// so typing never stutters. Every page gets it from `root_layout` — the /// drive, shared and trash filterbars share the one `.field-box-search` /// shape, and a page without it never raises an `input` the listener wants. /// Enter still submits through `soft_nav_script`'s GET handler (a real /// navigation, history entry and all); an emptied box asks for the plain /// listing, which the server already answers. pub async fn search_script<'a>(cx: &'a Cx) -> Result { const JS: &str = "\ (function () { \ if (window.__inSearch) { return; } \ window.__inSearch = true; \ var timer = null; \ var last = (document.querySelector('.field-box-search input[name=q]') || {}).value || ''; \ function fire() { \ var el = document.querySelector('.field-box-search input[name=q]'); \ if (!el || !el.form || !window.__inQuery || el.value === last) { return; } \ last = el.value; \ window.__inKeep = true; \ window.__inQuery((el.form.getAttribute('action') || window.location.pathname) + '?' + new URLSearchParams(new FormData(el.form)).toString()); \ } \ document.addEventListener('input', function (e) { \ var el = e.target; \ if (!el || el.name !== 'q' || !el.closest || !el.closest('.field-box-search')) { return; } \ if (timer) { clearTimeout(timer); } \ timer = setTimeout(function () { timer = null; fire(); }, 200); \ }); \ })();"; Ok(view! { cx => }.boxed()) } /// The one document-level capture `keydown` listener for `Escape`, emitted /// once from `root_layout` before every page's own scripts. Owners install /// no listeners of their own; their scripts call /// `window.__inEsc.register(priority, fn)` and on `Escape` the manager /// runs the resolvers highest-priority first — the first to return true /// closes its surface and the manager stops the key. Every consuming press /// gets `preventDefault()`: a real Escape's browser default is stop-loading /// (it once cancelled the navigation these branches used to start; synthetic /// keys carry no default, so only a live keyboard ever showed it). /// /// The table below is the whole precedence order, topmost first; a resolver /// whose surface is absent returns false so lower layers get the press. /// Wave-2 pages register their closers here rather than installing their /// own listeners: /// /// | prio | closes | registered by | /// |------|--------|---------------| /// | 95 | the open dropdown panel (refocusing its trigger) | wave-2 `dropdown_script` | /// | 90 | the viewer, then the delete confirm | wave-2 file/share pages | /// | 40 | the topbar `.user-menu` (pin+blur) | `layout.rs`'s `escape_script` | /// | 20 | the datepicker popover, if wave 2 adds one | wave-2 page script | /// | 10 | the row context menu | wave-2 drive page script | /// The live channel's browser half: one `EventSource` per tab, and the slow /// tick that keeps clock-driven text honest. /// /// Everything here is one script because both halves end in the same act — /// re-fetch the current URL through `__inGo` and let `swap()` do what it /// already does after every form post. There is deliberately no second render /// path: a partial-update mechanism would be a second way for the page to be /// wrong, and the full swap is the one the app exercises constantly. /// /// Three things it must not get wrong: /// /// The `__inLive` guard is not decoration. `swap()` re-executes every /// swapped-in script, so without it each soft navigation would open another /// `EventSource` and the tab would end up holding one connection per page it /// had ever visited. /// /// A refresh must not disturb what somebody is in the middle of. The first /// attempt held the refresh back while a form was dirty, which was wrong twice /// over: one unsubmitted form froze every other surface on the screen, and a /// dropdown could never be used at all while the workspace was busy, because /// each update slammed it shut. /// /// The cause of both was the refresh throwing the whole page away. So the live /// path does not: it MORPHS. `swap`'s morphing mode walks the freshly fetched /// document against the live one and touches only what actually differs — /// changed text, changed attributes, added and removed nodes. Everything else /// is the same DOM node it was a moment ago, so an open dropdown stays open, a /// caret stays where it was, a half-typed comment keeps its text, and a scrolled /// panel keeps its position. Not because any of them is special-cased, but /// because nothing touched them. /// /// A ` }.boxed()) } pub async fn escape_manager_script<'a>(cx: &'a Cx) -> Result { use topcoat::view::Unescaped; const JS: &str = "\ (function () { \ if (window.__inEsc) { return; } \ window.__inEsc = { \ resolvers: [], \ register: function (priority, fn) { \ window.__inEsc.resolvers.push({ priority: priority, fn: fn }); \ window.__inEsc.resolvers.sort(function (a, b) { return b.priority - a.priority; }); \ } \ }; \ document.addEventListener('keydown', function (e) { \ if (e.key !== 'Escape') { return; } \ for (var i = 0; i < window.__inEsc.resolvers.length; i++) { \ if (window.__inEsc.resolvers[i].fn(e)) { \ e.preventDefault(); \ e.stopImmediatePropagation(); \ return; \ } \ } \ }, true); \ })();"; Ok(view! { cx => }.boxed()) } /// Registers the topbar `Escape` resolver on `window.__inEsc` /// (priority 40 — the table is on `escape_manager_script`): the topbar /// `.user-menu` panel — hover-open included, pinned shut by a /// `user-menu-esc` class that a `mouseenter` inside the menu clears. pub async fn escape_script<'a>(cx: &'a Cx) -> Result { const JS: &str = "\ (function () { \ if (window.__inEscTop) { return; } \ window.__inEscTop = true; \ window.__inEsc.register(40, function () { \ var menu = document.querySelector('.user-menu'); \ if (menu && (menu.matches(':hover') || menu.contains(document.activeElement))) { \ window.__inOwn(menu, ['user-menu-esc'], []); \ var focused = document.activeElement; \ if (focused && focused.closest('.user-menu')) { focused.blur(); } \ return true; \ } \ return false; \ }); \ document.addEventListener('mouseenter', function (e) { \ var menu = e.target.closest ? e.target.closest('.user-menu') : null; \ if (menu) { menu.classList.remove('user-menu-esc'); } \ }, true); \ })();"; Ok(view! { cx => }.boxed()) } /// The persistent notice stack's client half: upload errors and completions /// that must stay until dismissed. Emitted from the document shell so every /// page carries the stack — an upload started on the drive keeps its home /// when the reader soft-navigates to the trash mid-flight. /// /// How the cards survive the swaps: every card is registered through /// `__inAdded`, so the live path's morph — which pairs only server-rendered /// nodes and leaves client-made ones alone — keeps them where they are. The /// full-replace path (navigations, form posts) rebuilds the body and would /// drop them, so every notice is also mirrored in `window.__inNotices`, /// which lives on the document's `window` and outlives any one body; the /// `in:wire` pass `swap()` runs after every paint re-renders the stack from /// that array. Dismissing (the ✕, labelled from the stack's /// `data-dismiss-label`) drops the notice from both. Nothing here /// auto-times out. /// /// The server-rendered `?refusal` banner needs no such route: it rides the /// redirect URL the swap just painted, so both paths re-render it from the /// server's own bytes. pub async fn status_script<'a>(cx: &'a Cx) -> Result { const JS: &str = "\ (function () { \ if (window.__inStatus) { return; } \ window.__inStatus = true; \ if (!window.__inNotices) { window.__inNotices = []; } \ var seq = 0; \ window.__inNotices.forEach(function (n) { if (n.id > seq) { seq = n.id; } }); \ function box() { return document.getElementById('in-status'); } \ function dismissLabel() { \ var b = box(); \ return (b && b.getAttribute('data-dismiss-label')) || ''; \ } \ window.__inNotify = function (kind, text) { \ seq++; \ window.__inNotices.push({ id: seq, kind: kind, text: text }); \ render(); \ }; \ function render() { \ var target = box(); \ if (!target) { return; } \ target.querySelectorAll('[data-notice]').forEach(function (old) { old.remove(); }); \ window.__inNotices.forEach(function (n) { \ var card = document.createElement('div'); \ card.className = 'in-status-card in-status-' + n.kind; \ card.setAttribute('data-notice', String(n.id)); \ var text = document.createElement('span'); \ text.className = 'in-status-text'; \ text.textContent = n.text; \ var shut = document.createElement('button'); \ shut.type = 'button'; \ shut.className = 'in-status-dismiss'; \ shut.textContent = '✕'; \ shut.setAttribute('aria-label', dismissLabel()); \ shut.addEventListener('click', function () { \ window.__inNotices = window.__inNotices.filter(function (x) { return x.id !== n.id; }); \ card.remove(); \ }); \ card.appendChild(text); \ card.appendChild(shut); \ target.appendChild(window.__inAdded(card)); \ }); \ } \ document.addEventListener('in:wire', render); \ render(); \ })();"; Ok(view! { cx => }.boxed()) } /// Every path that matches no page raises a `NotFoundError`, so it renders /// through `root_layout`'s catch below rather than the router's bare default. /// `/` itself is served by `landing` above and never reaches this route. #[page("/{*path}")] async fn missing() -> Result> { Err(not_found().into()) } /// `style/main.scss`, compiled by `build.rs` into `assets/main.css`. const STYLE: Asset = asset!("assets/main.css"); /// The document shell itself: everything from `` to ``, the /// part `root_layout` pairs around every page. `#[route]` handlers bypass /// layout pairing — the public share pages among them, whose query can ask /// for bytes a page-shaped answer cannot carry — so this is `pub(crate)`: /// they wrap their views in the same shell by calling it directly instead of /// hand-copying the head, passing their own `title`. Signed-out visitors /// wear the provision defaults and the session-gated live stream stays off /// (`asking` is false without a session), so a stranger's page carries no /// user data and opens no `/api/live` connection. pub(crate) async fn document_shell<'a>( cx: &'a Cx, slot: topcoat::view::Child<'a>, title: impl Into, ) -> Result { let title = title.into(); // The per-user chrome knobs, read off the request's own user: the theme // into `data-theme`, the interface into `data-ui`, the language into // ``. Signed-out (or unreadable) wears the provision defaults — // light and instrument, matching im and iz — and the language falls back // to `Accept-Language`. let me = match current_user(cx).await { Ok(user) => user.as_ref(), Err(_) => None, }; let asking = me.is_some(); let dark = me.as_ref().is_some_and(|user| user.theme == "dark"); let ui = me.as_ref().map_or("instrument", |user| user.ui.as_str()); let lang = crate::i18n::lang(cx).await; let nothing = t(lang, Key::NothingAtThisAddress).to_string(); Ok(view! { cx => (title) topcoat::runtime::script() topcoat::dev::script() (topcoat::view::Child::new(escape_manager_script(cx).await?)) (topcoat::view::Child::new(soft_nav_script(cx).await?)) (topcoat::view::Child::new(search_script(cx).await?)) if asking { (topcoat::view::Child::new(live_script(cx).await?)) } error_boundary( fallback: |error| { if error.downcast_ref::().is_none() { return Err(error); } Ok(view! { cx => (StatusCode::NOT_FOUND)

(nothing)

}) }, (slot) )
(topcoat::view::Child::new(status_script(cx).await?)) }.boxed()) } /// The tab title a page wears, read off its address: the shell is paired /// around pages by path prefix, so a page cannot hand its name up — the /// router's own address decides. The share pages, which wrap themselves in /// the shell directly, pass their own instead. Anything unmatched — the /// catch-all 404 among it — reads as the app's bare name. fn title_key_of(path: &str) -> Option { match path { "/" => Some(Key::SignIn), p if p.starts_with("/drive") => Some(Key::NavDrive), p if p.starts_with("/shared") => Some(Key::NavShared), p if p.starts_with("/trash") => Some(Key::NavTrash), p if p.starts_with("/settings") => Some(Key::NavSettings), p if p.starts_with("/view/") => Some(Key::FileDetails), _ => None, } } /// The router's own shell route: pairing is by path prefix, so every page /// under `/` wears `document_shell` through here, titled off its address. #[layout("/")] async fn root_layout(cx: &Cx, slot: topcoat::view::Child<'_>) -> Result { let lang = crate::i18n::lang(cx).await; let title = match title_key_of(uri(cx).path()) { None => "in".to_string(), Some(key) => format!("{} · in", t(lang, key)), }; document_shell(cx, slot, title).await }