//! The document shell every page renders inside, ported from //! `iz-web/src/app.rs`'s `shell`/`App`/`NotFound`. use topcoat::{ Result, asset::{Asset, asset}, context::Cx, router::{ StatusCode, error::{NotFoundError, not_found}, layout, page, }, view::{BoxView, Unescaped, View, ViewExt, error_boundary, view}, }; use crate::health::{probe_family, switcher_marks}; use crate::i18n::{Key, Lang, t}; use crate::server::{FAMILY_KEY, current_user, store}; /// The iz monogram again, as the tab icon: the same drawing as `wordmark`, /// 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 iz monogram — a dotted `i` beside a stroked `z`, the trace the product /// is named for. 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: `iz` spells the /// first two letters of `iz`, so 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 and setup pages wear it — see `mark`. pub(crate) async fn wordmark<'a>(cx: &'a Cx) -> Result { Ok(view! { cx => "iz" } .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. The URL carries the row's `photo_version` as /// `?v=`, so a changed face is a changed URL: a browser may cache the old /// answer for a year and still see the new one the day the row moves — the /// live refresh morphs the attribute and the img follows. The `` always /// renders and hides itself on error (see `avatar_script`), leaving the /// initials beneath as the fallback. Shared by the board, the modal and /// every topbar user menu. pub(crate) async fn avatar<'a>( cx: &'a Cx, id: &'a str, display_name: &'a str, photo_version: u64, extra: &'a str, ) -> Result { let tone = 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 initials = initials_of(display_name); let src = format!("/avatar/{id}?v={photo_version}"); Ok(view! { cx => (initials) }.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 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 `__izOwn` so the live morph /// — which owns no names, only what the client declares — does not strip it /// back off on the next refresh. pub(crate) async fn avatar_script<'a>(cx: &'a Cx) -> Result { use topcoat::view::{Unescaped, ViewExt}; const JS: &str = "\ (function () { \ if (window.__izAvatar) { return; } \ window.__izAvatar = true; \ function hide(img) { \ if (window.__izOwn) { window.__izOwn(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 topbar's signed-in identity: the display name, opening on hover or /// focus onto details (name, address, role) and sign-out. Shared by every /// signed-in page's topbar — which is why `avatar_script` rides along here: /// every page with avatars has this menu, and the script's guard makes the /// one emission enough no matter how many avatars the page carries. pub async fn user_menu<'a>( cx: &'a Cx, me: &'a crate::detail::Me, lang: Lang, ) -> Result { let role_key = match me.role { iz_core::Role::Admin => Key::RoleAdminOption, iz_core::Role::Member => Key::RoleMemberOption, iz_core::Role::Viewer => Key::RoleViewerOption, }; Ok(view! { cx =>
(me.display_name.clone())
(me.email.clone())
(t(lang, role_key))
(t(lang, Key::Profile)) (t(lang, Key::NavSettings))
(topcoat::view::Child::new(avatar_script(cx).await?)) }.boxed()) } /// The signed-in pages, as the topbar nav links between them. #[derive(Clone, Copy, PartialEq)] pub enum NavPage { Board, Rules, Logs, Tags, Settings, } impl NavPage { const ALL: [Self; 5] = [ Self::Board, Self::Rules, Self::Logs, Self::Tags, Self::Settings, ]; fn href(self) -> &'static str { match self { Self::Board => "/", Self::Rules => "/rules", Self::Logs => "/logs", Self::Tags => "/tags", Self::Settings => "/settings", } } fn label(self) -> Key { match self { Self::Board => Key::NavBoard, Self::Rules => Key::NavMailRules, Self::Logs => Key::NavLogs, Self::Tags => Key::NavTags, Self::Settings => Key::NavSettings, } } } /// The topbar's page nav, shared by every signed-in page: the pages with the /// current one marked, the admin-only ones (rules, logs, tags) shown only to /// roles that can administer. 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, role: iz_core::Role, lang: Lang, ) -> Result { Ok(view! { cx => }.boxed()) } /// The family list as the switcher shows it, read from the app's own /// `setting` store — the mirror im's admin panel feeds through the /// background beat in `main.rs`. Absent, empty, unparseable or a store /// that will not answer all read the same: an empty list, which renders /// no switcher. A page must not fail for the want of a wordmark. pub(crate) async fn family_of(cx: &Cx) -> Vec { match store(cx).get_setting(FAMILY_KEY).await { Ok(Some(raw)) => serde_json::from_str(&raw).unwrap_or_default(), _ => Vec::new(), } } /// The monogram with the family behind it — the way between the apps of /// dizey.sh. The mark alone stands in the chrome; the siblings' wordmarks /// hang 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` /// carries it), middots between, each titled with the human name im's admin /// panel gives it and wearing its `/healthz` reading as a dot — green while /// the sibling answers `ok`, muted while it does not ([`crate::health`]). /// No script: the flyout is CSS, and it stays in the DOM at opacity zero so /// Tab reaches its links. The list is the app's own mirror of im's /// `/family` ([`family_of`]), minus this app's own row — a door back into /// the room one is standing in is no door — so the panel decides the /// family without a deploy here, and a mirror that has not arrived yet, or /// a deployment standing alone, renders the bare mark: nothing to reveal, /// nothing to probe. /// The links leave this origin, so they carry `data-hard`, like the issuer /// link in the user menu. pub(crate) async fn family_mark<'a>(cx: &'a Cx) -> Result { const SELF: &str = "iz"; let siblings: Vec<_> = family_of(cx) .await .into_iter() .filter(|service| service.key != SELF) .collect(); if siblings.is_empty() { return mark(cx).await.map(|v| v.boxed()); } // Every probe at once, at most one family-wide round per TTL // ([`crate::health::probe_family`]): a sibling that is down costs its // two seconds once, not once per page render. let urls: Vec = siblings .iter() .map(|service| format!("{}/healthz", service.url.trim_end_matches('/'))) .collect(); let probes = probe_family(urls).await; let rows: Vec<_> = siblings .iter() .zip(probes) .map(|(service, probe)| { ( service.key.as_str(), service.name.as_str(), service.url.as_str(), probe, ) }) .collect(); let marks = switcher_marks(rows); Ok(view! { cx =>
(topcoat::view::Child::new(mark(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. The password pane was where this was first felt: a wrong /// current password and a right one landed on the same silent page. /// /// Every fetch that ends in a swap carries the navigation counter it started /// under (`window.__izNav`), 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()) } /// 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.__izEsc.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. It /// reproduces what the four former listeners' registration order produced /// per page (the modal's inline `escape_closes` registered before the board /// page's trailing scripts, `dropdown_script` before `escape_script` on /// settings/rules, `escape_script` before `card_menu_script` on the board): /// /// | prio | closes | registered by | /// |------|--------|---------------| /// | 95 | the open dropdown panel (refocusing its trigger) | `dropdown.rs`'s `dropdown_script` | /// | 90 | the viewer, then the delete confirm, then non-datepick edit popovers, then the task modal | `detail.rs`'s `escape_closes` | /// | 40 | the topbar `.user-menu` (pin+blur), then the rules composer, then a rules edit row (back to `/rules`) | `layout.rs`'s `escape_script` | /// | 20 | the datepicker popover | `board.rs`'s `card_menu_script` | /// | 10 | the card context menu | `board.rs`'s `card_menu_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 `__izGo` 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 `__izLive` 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, ViewExt}; const JS: &str = "\ (function () { \ if (window.__izEsc) { return; } \ window.__izEsc = { \ resolvers: [], \ register: function (priority, fn) { \ window.__izEsc.resolvers.push({ priority: priority, fn: fn }); \ window.__izEsc.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.__izEsc.resolvers.length; i++) { \ if (window.__izEsc.resolvers[i].fn(e)) { \ e.preventDefault(); \ e.stopImmediatePropagation(); \ return; \ } \ } \ }, true); \ })();"; Ok(view! { cx => }.boxed()) } /// Registers the topbar/rules `Escape` resolvers on `window.__izEsc` /// (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 — then /// a `.rule-new` composer left open on the rules page, then a rules edit /// row (navigating back to `/rules`). Never touches /// `details.confirm-details`; that flow stays `detail.rs`'s. pub async fn escape_script<'a>(cx: &'a Cx) -> Result { const JS: &str = "\ (function () { \ if (window.__izEscTop) { return; } \ window.__izEscTop = true; \ window.__izEsc.register(40, function () { \ var menu = document.querySelector('.user-menu'); \ if (menu && (menu.matches(':hover') || menu.contains(document.activeElement))) { \ window.__izOwn(menu, ['user-menu-esc'], []); \ var focused = document.activeElement; \ if (focused && focused.closest('.user-menu')) { focused.blur(); } \ return true; \ } \ var composer = document.querySelector('details.rule-new[open]'); \ if (composer) { composer.removeAttribute('open'); return true; } \ if (document.querySelector('.rule-new-body[action=\"/api/update_rule\"]')) { \ if (window.__izGo) { window.__izGo('/rules'); } else { window.location.href = '/rules'; } \ 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()) } /// 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"); #[layout("/")] async fn root_layout(cx: &Cx, slot: topcoat::view::Child<'_>) -> Result { // Pages with no session (auth screens) render light and English; both are // only set when the request's own user has one to read. let asking = match current_user(cx).await { Ok(user) => user.as_ref(), Err(_) => None, }; let dark = asking.is_some_and(|user| user.theme == "dark"); let ui = asking.map_or("instrument", |user| user.ui.as_str()); let lang = asking.map_or(Lang::En, |user| Lang::from_code(&user.language)); let nothing = t(lang, Key::NothingAtThisAddress).to_string(); // 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 signed-out front door is // the sign-in card, not the board. Anything unmatched — the catch-all // 404 among it — reads as the app's bare name. let path = topcoat::router::request::uri(cx).path(); let title = match path { "/" if asking.is_none() => format!("{} · iz", t(lang, Key::SignIn)), "/" => format!("{} · iz", t(lang, Key::NavBoard)), p if p.starts_with("/rules") => format!("{} · iz", t(lang, Key::NavMailRules)), p if p.starts_with("/logs") => format!("{} · iz", t(lang, Key::NavLogs)), p if p.starts_with("/tags") => format!("{} · iz", t(lang, Key::NavTags)), p if p.starts_with("/settings") => format!("{} · iz", t(lang, Key::NavSettings)), p if p.starts_with("/people") => format!("{} · iz", t(lang, Key::Members)), _ => "iz".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?)) if asking.is_some() { (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) ) }.boxed()) }