iz_old
Clone
https://git.tahinli.com/Tahinli/iz_old.git
0 watching·0 forks·Rust·GPL-3.0·2.2 MiB·4c154b4·Tahinli·2 months ago·301 commits
| 1 | //! The document shell every page renders inside, ported from |
| 2 | //! `iz-web/src/app.rs`'s `shell`/`App`/`NotFound`. |
| 3 | |
| 4 | use topcoat::{ |
| 5 | Result, |
| 6 | asset::{Asset, asset}, |
| 7 | context::Cx, |
| 8 | router::{ |
| 9 | StatusCode, |
| 10 | error::{NotFoundError, not_found}, |
| 11 | layout, page, |
| 12 | }, |
| 13 | view::{BoxView, Unescaped, View, ViewExt, error_boundary, view}, |
| 14 | }; |
| 15 | |
| 16 | use crate::health::{probe_family, switcher_marks}; |
| 17 | use crate::i18n::{Key, Lang, t}; |
| 18 | use crate::server::{FAMILY_KEY, current_user, store}; |
| 19 | |
| 20 | /// The iz monogram again, as the tab icon: the same drawing as `wordmark`, |
| 21 | /// inlined because it must carry its own colours — a data URI has no page to |
| 22 | /// inherit `currentColor` or the accent token from, so the two themes are |
| 23 | /// spelled out in a media query inside the SVG. |
| 24 | const FAVICON: &str = "data:image/svg+xml,\ |
| 25 | <svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'>\ |
| 26 | <style>.i{fill:%231a1b1d}.t{fill:%2346557b}.s{stroke:%231a1b1d}\ |
| 27 | @media(prefers-color-scheme:dark){.i{fill:%23e6e4de}.t{fill:%238ba1e8}\ |
| 28 | .s{stroke:%23e6e4de}}</style>\ |
| 29 | <rect class='i' x='3.1' y='9.4' width='4.4' height='11.6' rx='2.2'/>\ |
| 30 | <circle class='t' cx='5.3' cy='4.9' r='2.6'/>\ |
| 31 | <path class='s' d='M11.4 10.6h9.3L11.4 19.8h9.5' fill='none' \ |
| 32 | stroke-width='2.5' stroke-linecap='round' stroke-linejoin='round'/></svg>"; |
| 33 | |
| 34 | /// The iz monogram — a dotted `i` beside a stroked `z`, the trace the product |
| 35 | /// is named for. It takes `currentColor` for its strokes and the accent for |
| 36 | /// its tittle, so one drawing serves both skins and both themes. |
| 37 | /// |
| 38 | /// The monogram and the wordmark are alternates, never a pair: `iz` spells the |
| 39 | /// first two letters of `iz`, so standing them side by side reads as a |
| 40 | /// stutter no amount of space or framing repairs. The mark carries the chrome, |
| 41 | /// where the name is already known and the room is 44px; the word carries the |
| 42 | /// front door, where a stranger arrives and nothing else has said it yet. |
| 43 | pub(crate) async fn mark<'a>(cx: &'a Cx) -> Result<impl View + 'a> { |
| 44 | Ok(view! { |
| 45 | cx => |
| 46 | <a class="wordmark" href="/" aria-label="iz"> |
| 47 | <svg class="wordmark-mark" width="24" height="24" viewBox="0 0 24 24" |
| 48 | aria-hidden="true"> |
| 49 | <rect x="3.1" y="9.4" width="4.4" height="11.6" rx="2.2" |
| 50 | fill="currentColor"></rect> |
| 51 | <circle class="wordmark-tittle" cx="5.3" cy="4.9" r="2.6"></circle> |
| 52 | <path d="M11.4 10.6h9.3L11.4 19.8h9.5" fill="none" |
| 53 | stroke="currentColor" stroke-width="2.5" stroke-linecap="round" |
| 54 | stroke-linejoin="round"></path> |
| 55 | </svg> |
| 56 | </a> |
| 57 | } |
| 58 | .boxed()) |
| 59 | } |
| 60 | |
| 61 | /// The wordmark, the monogram's other half: the name alone, in the one face |
| 62 | /// both skins agree on. The sign-in and setup pages wear it — see `mark`. |
| 63 | pub(crate) async fn wordmark<'a>(cx: &'a Cx) -> Result<impl View + 'a> { |
| 64 | Ok(view! { |
| 65 | cx => |
| 66 | <a class="wordmark wordmark-lone" href="/"> |
| 67 | <span class="wordmark-text">"iz"</span> |
| 68 | </a> |
| 69 | } |
| 70 | .boxed()) |
| 71 | } |
| 72 | |
| 73 | /// A person as a circle (or, on the Instrument skin, a square): the initials, |
| 74 | /// toned by the id so every account has its own colour, with the im photo |
| 75 | /// over it when im has one. The URL carries the row's `photo_version` as |
| 76 | /// `?v=`, so a changed face is a changed URL: a browser may cache the old |
| 77 | /// answer for a year and still see the new one the day the row moves — the |
| 78 | /// live refresh morphs the attribute and the img follows. The `<img>` always |
| 79 | /// renders and hides itself on error (see `avatar_script`), leaving the |
| 80 | /// initials beneath as the fallback. Shared by the board, the modal and |
| 81 | /// every topbar user menu. |
| 82 | pub(crate) async fn avatar<'a>( |
| 83 | cx: &'a Cx, |
| 84 | id: &'a str, |
| 85 | display_name: &'a str, |
| 86 | photo_version: u64, |
| 87 | extra: &'a str, |
| 88 | ) -> Result<impl View + 'a> { |
| 89 | let tone = id |
| 90 | .bytes() |
| 91 | .fold(0u32, |acc, b| acc.wrapping_mul(31).wrapping_add(b as u32)) |
| 92 | % 5; |
| 93 | let class = format!("avatar avatar-tone-{tone} {extra}"); |
| 94 | let initials = initials_of(display_name); |
| 95 | let src = format!("/avatar/{id}?v={photo_version}"); |
| 96 | Ok(view! { |
| 97 | cx => |
| 98 | <span class="avatar-stack"> |
| 99 | <span class=(class.clone()) data-name=(display_name.to_string())>(initials)</span> |
| 100 | <img class=(format!("{class} avatar-photo")) src=(src) alt="" data-name=(display_name.to_string())> |
| 101 | </span> |
| 102 | }.boxed()) |
| 103 | } |
| 104 | |
| 105 | /// The first letters of the first two words, uppercased — "Ada Lovelace" |
| 106 | /// wears "AL", a bare address wears its first letter. |
| 107 | fn initials_of(name: &str) -> String { |
| 108 | let mut out = String::new(); |
| 109 | for word in name.split_whitespace().take(2) { |
| 110 | if let Some(first) = word.chars().next() { |
| 111 | out.extend(first.to_uppercase()); |
| 112 | } |
| 113 | } |
| 114 | if out.is_empty() { |
| 115 | out.push('?'); |
| 116 | } |
| 117 | out |
| 118 | } |
| 119 | |
| 120 | /// The photo half's client half: a missing photo must fall back to the |
| 121 | /// initials beneath it, and a bare `<img>` to a 404 shows the broken-image |
| 122 | /// box instead. One document-level capture `error` listener hides every |
| 123 | /// `img.avatar-photo` that fails, plus a sweep for the ones already failed |
| 124 | /// before it ran; hiding is registered through `__izOwn` so the live morph |
| 125 | /// — which owns no names, only what the client declares — does not strip it |
| 126 | /// back off on the next refresh. |
| 127 | pub(crate) async fn avatar_script<'a>(cx: &'a Cx) -> Result<impl View + 'a> { |
| 128 | use topcoat::view::{Unescaped, ViewExt}; |
| 129 | const JS: &str = "\ |
| 130 | (function () { \ |
| 131 | if (window.__izAvatar) { return; } \ |
| 132 | window.__izAvatar = true; \ |
| 133 | function hide(img) { \ |
| 134 | if (window.__izOwn) { window.__izOwn(img, [], ['style']); } \ |
| 135 | img.style.display = 'none'; \ |
| 136 | } \ |
| 137 | document.addEventListener('error', function (e) { \ |
| 138 | var img = e.target && e.target.closest ? e.target.closest('img.avatar-photo') : null; \ |
| 139 | if (img) { hide(img); } \ |
| 140 | }, true); \ |
| 141 | document.querySelectorAll('img.avatar-photo').forEach(function (img) { \ |
| 142 | if (img.complete && img.naturalWidth === 0) { hide(img); } \ |
| 143 | }); \ |
| 144 | })();"; |
| 145 | Ok(view! { cx => <script>(Unescaped::new_unchecked(JS))</script> }.boxed()) |
| 146 | } |
| 147 | |
| 148 | /// The topbar's signed-in identity: the display name, opening on hover or |
| 149 | /// focus onto details (name, address, role) and sign-out. Shared by every |
| 150 | /// signed-in page's topbar — which is why `avatar_script` rides along here: |
| 151 | /// every page with avatars has this menu, and the script's guard makes the |
| 152 | /// one emission enough no matter how many avatars the page carries. |
| 153 | pub async fn user_menu<'a>( |
| 154 | cx: &'a Cx, |
| 155 | me: &'a crate::detail::Me, |
| 156 | lang: Lang, |
| 157 | ) -> Result<impl View + 'a> { |
| 158 | let role_key = match me.role { |
| 159 | iz_core::Role::Admin => Key::RoleAdminOption, |
| 160 | iz_core::Role::Member => Key::RoleMemberOption, |
| 161 | iz_core::Role::Viewer => Key::RoleViewerOption, |
| 162 | }; |
| 163 | Ok(view! { |
| 164 | cx => |
| 165 | <div class="user-menu"> |
| 166 | <button type="button" class="user-menu-trigger"> |
| 167 | (topcoat::view::Child::new(avatar(cx, &me.id, &me.display_name, me.photo_version, "").await?)) |
| 168 | <span class="user-menu-trigger-name">(me.display_name.clone())</span> |
| 169 | </button> |
| 170 | <div class="user-menu-panel"> |
| 171 | <div class="user-menu-name">(me.display_name.clone())</div> |
| 172 | <div class="user-menu-email">(me.email.clone())</div> |
| 173 | <div class="user-menu-role">(t(lang, role_key))</div> |
| 174 | <a class="user-menu-item" href=(format!("{}/", crate::server::config(cx).oidc.issuer)) data-hard="">(t(lang, Key::Profile))</a> |
| 175 | <a class="user-menu-item" href="/settings">(t(lang, Key::NavSettings))</a> |
| 176 | </div> |
| 177 | </div> |
| 178 | (topcoat::view::Child::new(avatar_script(cx).await?)) |
| 179 | }.boxed()) |
| 180 | } |
| 181 | |
| 182 | /// The signed-in pages, as the topbar nav links between them. |
| 183 | #[derive(Clone, Copy, PartialEq)] |
| 184 | pub enum NavPage { |
| 185 | Board, |
| 186 | Rules, |
| 187 | Logs, |
| 188 | Tags, |
| 189 | Settings, |
| 190 | } |
| 191 | |
| 192 | impl NavPage { |
| 193 | const ALL: [Self; 5] = [ |
| 194 | Self::Board, |
| 195 | Self::Rules, |
| 196 | Self::Logs, |
| 197 | Self::Tags, |
| 198 | Self::Settings, |
| 199 | ]; |
| 200 | |
| 201 | fn href(self) -> &'static str { |
| 202 | match self { |
| 203 | Self::Board => "/", |
| 204 | Self::Rules => "/rules", |
| 205 | Self::Logs => "/logs", |
| 206 | Self::Tags => "/tags", |
| 207 | Self::Settings => "/settings", |
| 208 | } |
| 209 | } |
| 210 | |
| 211 | fn label(self) -> Key { |
| 212 | match self { |
| 213 | Self::Board => Key::NavBoard, |
| 214 | Self::Rules => Key::NavMailRules, |
| 215 | Self::Logs => Key::NavLogs, |
| 216 | Self::Tags => Key::NavTags, |
| 217 | Self::Settings => Key::NavSettings, |
| 218 | } |
| 219 | } |
| 220 | } |
| 221 | |
| 222 | /// The topbar's page nav, shared by every signed-in page: the pages with the |
| 223 | /// current one marked, the admin-only ones (rules, logs, tags) shown only to |
| 224 | /// roles that can administer. Plain `<a>`s — the soft-nav forwarder swaps them |
| 225 | /// like any same-origin link, so `data-hard` stays off. |
| 226 | pub async fn topbar_nav<'a>( |
| 227 | cx: &'a Cx, |
| 228 | active: NavPage, |
| 229 | role: iz_core::Role, |
| 230 | lang: Lang, |
| 231 | ) -> Result<impl View + 'a> { |
| 232 | Ok(view! { |
| 233 | cx => |
| 234 | <nav class="topbar-nav-links"> |
| 235 | for page in NavPage::ALL { |
| 236 | if role.can_administer() || !matches!(page, NavPage::Rules | NavPage::Logs | NavPage::Tags) { |
| 237 | <a |
| 238 | class=(if page == active { "topbar-nav topbar-nav-on" } else { "topbar-nav" }) |
| 239 | href=(page.href()) |
| 240 | > |
| 241 | (t(lang, page.label())) |
| 242 | </a> |
| 243 | } |
| 244 | } |
| 245 | </nav> |
| 246 | }.boxed()) |
| 247 | } |
| 248 | |
| 249 | /// The family list as the switcher shows it, read from the app's own |
| 250 | /// `setting` store — the mirror im's admin panel feeds through the |
| 251 | /// background beat in `main.rs`. Absent, empty, unparseable or a store |
| 252 | /// that will not answer all read the same: an empty list, which renders |
| 253 | /// no switcher. A page must not fail for the want of a wordmark. |
| 254 | pub(crate) async fn family_of(cx: &Cx) -> Vec<iz_client::FamilyService> { |
| 255 | match store(cx).get_setting(FAMILY_KEY).await { |
| 256 | Ok(Some(raw)) => serde_json::from_str(&raw).unwrap_or_default(), |
| 257 | _ => Vec::new(), |
| 258 | } |
| 259 | } |
| 260 | |
| 261 | /// The monogram with the family behind it — the way between the apps of |
| 262 | /// dizey.sh. The mark alone stands in the chrome; the siblings' wordmarks |
| 263 | /// hang in a flyout that opens under it on hover and on keyboard focus (the |
| 264 | /// mark is an `<a href="/">`, so it is already focusable and `:focus-within` |
| 265 | /// carries it), middots between, each titled with the human name im's admin |
| 266 | /// panel gives it and wearing its `/healthz` reading as a dot — green while |
| 267 | /// the sibling answers `ok`, muted while it does not ([`crate::health`]). |
| 268 | /// No script: the flyout is CSS, and it stays in the DOM at opacity zero so |
| 269 | /// Tab reaches its links. The list is the app's own mirror of im's |
| 270 | /// `/family` ([`family_of`]), minus this app's own row — a door back into |
| 271 | /// the room one is standing in is no door — so the panel decides the |
| 272 | /// family without a deploy here, and a mirror that has not arrived yet, or |
| 273 | /// a deployment standing alone, renders the bare mark: nothing to reveal, |
| 274 | /// nothing to probe. |
| 275 | /// The links leave this origin, so they carry `data-hard`, like the issuer |
| 276 | /// link in the user menu. |
| 277 | pub(crate) async fn family_mark<'a>(cx: &'a Cx) -> Result<impl View + 'a> { |
| 278 | const SELF: &str = "iz"; |
| 279 | let siblings: Vec<_> = family_of(cx) |
| 280 | .await |
| 281 | .into_iter() |
| 282 | .filter(|service| service.key != SELF) |
| 283 | .collect(); |
| 284 | if siblings.is_empty() { |
| 285 | return mark(cx).await.map(|v| v.boxed()); |
| 286 | } |
| 287 | // Every probe at once, at most one family-wide round per TTL |
| 288 | // ([`crate::health::probe_family`]): a sibling that is down costs its |
| 289 | // two seconds once, not once per page render. |
| 290 | let urls: Vec<String> = siblings |
| 291 | .iter() |
| 292 | .map(|service| format!("{}/healthz", service.url.trim_end_matches('/'))) |
| 293 | .collect(); |
| 294 | let probes = probe_family(urls).await; |
| 295 | let rows: Vec<_> = siblings |
| 296 | .iter() |
| 297 | .zip(probes) |
| 298 | .map(|(service, probe)| { |
| 299 | ( |
| 300 | service.key.as_str(), |
| 301 | service.name.as_str(), |
| 302 | service.url.as_str(), |
| 303 | probe, |
| 304 | ) |
| 305 | }) |
| 306 | .collect(); |
| 307 | let marks = switcher_marks(rows); |
| 308 | Ok(view! { |
| 309 | cx => |
| 310 | <div class="wordmark-family"> |
| 311 | (topcoat::view::Child::new(mark(cx).await?)) |
| 312 | <nav class="service-switcher">(topcoat::view::Unescaped::new_unchecked(marks))</nav> |
| 313 | </div> |
| 314 | }.boxed()) |
| 315 | } |
| 316 | |
| 317 | /// The page-swap machinery that keeps every mutation on the same document. |
| 318 | /// |
| 319 | /// Every `/api/*` mutation is a plain form post answered with a 303 — sound |
| 320 | /// without script, but a full navigation repaints the whole page for a |
| 321 | /// one-field change. This script, emitted first in `<body>` on every page, |
| 322 | /// intercepts those submits (capture-phase, so `requestSubmit()` from any |
| 323 | /// auto-submit control lands here too), replays them over `fetch`, and swaps |
| 324 | /// the redirected page's `<body>` children in place — same bytes the hard |
| 325 | /// navigation would have shown, no reload. Refusal banners and saved chips |
| 326 | /// arrive with the swap because the redirect URL's query params rendered |
| 327 | /// them server-side; `history.replaceState` keeps the address bar honest. |
| 328 | /// |
| 329 | /// The replay declares `Accept: text/html`, because a replayed form post is a |
| 330 | /// form post asking for the page back: `carry_refusal_on_redirect` |
| 331 | /// (`server.rs`) copies a refusing 303's answer onto the `Location` only for a |
| 332 | /// caller that wants the page, and a bare `fetch` asks for `*/*` — under which |
| 333 | /// the refusal stayed in a body nobody reads and the click looked like nothing |
| 334 | /// happening. The password pane was where this was first felt: a wrong |
| 335 | /// current password and a right one landed on the same silent page. |
| 336 | /// |
| 337 | /// Every fetch that ends in a swap carries the navigation counter it started |
| 338 | /// under (`window.__izNav`), and its answer is thrown away if that counter |
| 339 | /// has moved. Without it the newest paint is not the newest intent: the live |
| 340 | /// refresh fetches the URL it was on, and a click landing during that flight |
| 341 | /// pushed a new page that the refresh's answer then overwrote — the page |
| 342 | /// arriving and reverting to the previous one two hundred milliseconds later. |
| 343 | /// Navigations, form posts and the overlay closes each step the counter, so a |
| 344 | /// second click also wins over a first one still in flight, and a refresh — |
| 345 | /// which is not an intent, only an update of what is already on screen — |
| 346 | /// steps nothing and lands only if nothing else has happened. |
| 347 | /// |
| 348 | /// The address bar and the `<html>` attributes are rewritten *before* the |
| 349 | /// new body's scripts run, never after: a swapped-in script that reads |
| 350 | /// `location.href` (the log-fit reload in `logs.rs`) would otherwise read |
| 351 | /// the page it just replaced and hard-navigate back to it. |
| 352 | /// |
| 353 | /// Swapped-in `<script>` nodes are inert (parser-inserted only), so |
| 354 | /// `swap()` re-creates each one as a fresh element, which runs it; every |
| 355 | /// emitted script carries a one-shot `window.__iz*` guard, so that |
| 356 | /// re-execution never stacks duplicate document-level listeners. There |
| 357 | /// is no topcoat re-hydrate entry, so per-element behavior is re-run by |
| 358 | /// the `iz:wire` event (`dropdown.rs`, the audio player) over the new |
| 359 | /// nodes. |
| 360 | /// |
| 361 | /// Forms that must really navigate (sign-in/out: the session and the whole |
| 362 | /// page identity change) opt out with `data-hard`. |
| 363 | /// Overlay closes never hit the server at all: the board is already |
| 364 | /// rendered under the modal, so `__izCloseModal`/`__izCloseViewer` |
| 365 | /// drop the overlay's DOM and rewrite the URL. |
| 366 | /// |
| 367 | /// The click-forwarder at the end is the repo-wide fix for the dead-zone |
| 368 | /// class the member-role select first showed: any click inside a |
| 369 | /// `.field-box`/`.status-form`/`.member-role` that misses the `.dd-trigger` |
| 370 | /// (label, chevron glyph, box padding) is forwarded to the trigger. |
| 371 | /// |
| 372 | /// Ordinary same-origin links get the same treatment: a delegated capture |
| 373 | /// click listener — registered after the close/scrim one, and skipped when |
| 374 | /// that one already `preventDefault`ed — fetches the href and swaps it in |
| 375 | /// under a `history.pushState`, so board cards and file chips no longer |
| 376 | /// reload the page. Raw `/files/` byte routes, `download`/`target`/ |
| 377 | /// `data-hard` links and modified clicks (ctrl/meta/shift/alt, non-left |
| 378 | /// button) stay browser-native. `popstate` replays the same fetch without |
| 379 | /// pushing. Fresh-URL navigations pass `swap`'s third argument to scroll |
| 380 | /// to top; in-place swaps (form posts, back) keep the scroll position. |
| 381 | /// `wire()` also pins every `.comment-list` to its bottom, on initial |
| 382 | /// load (DOMContentLoaded) included. |
| 383 | pub async fn soft_nav_script<'a>(cx: &'a Cx) -> Result<impl View + 'a> { |
| 384 | const JS: &str = "\ |
| 385 | (function () { \ |
| 386 | if (window.__izSoft) { return; } \ |
| 387 | window.__izSoft = true; \ |
| 388 | window.__izBuild = document.documentElement.getAttribute('data-build') || ''; \ |
| 389 | window.__izOwn = function (node, classes, attrs) { \ |
| 390 | var own = node.__izMine; \ |
| 391 | if (!own) { own = node.__izMine = { c: [], a: [] }; } \ |
| 392 | (classes || []).forEach(function (c) { \ |
| 393 | if (own.c.indexOf(c) === -1) { own.c.push(c); } \ |
| 394 | node.classList.add(c); \ |
| 395 | }); \ |
| 396 | (attrs || []).forEach(function (a) { if (own.a.indexOf(a) === -1) { own.a.push(a); } }); \ |
| 397 | return node; \ |
| 398 | }; \ |
| 399 | window.__izAdded = function (node) { node.__izAdded = true; return node; }; \ |
| 400 | function wire() { \ |
| 401 | document.querySelectorAll('.comment-list').forEach(function (list) { list.scrollTop = list.scrollHeight; }); \ |
| 402 | document.dispatchEvent(new Event('iz:wire')); \ |
| 403 | } \ |
| 404 | function keyOf(el) { \ |
| 405 | var form = el.form ? (el.form.getAttribute('action') || '') : ''; \ |
| 406 | return form + '|' + (el.name || '') + '|' + (el.type || '') + '|' + (el.tagName || ''); \ |
| 407 | } \ |
| 408 | function editable(el) { \ |
| 409 | return el.type !== 'hidden' && el.type !== 'password' && el.type !== 'file'; \ |
| 410 | } \ |
| 411 | function captureFields() { \ |
| 412 | var active = document.activeElement, out = []; \ |
| 413 | document.querySelectorAll('input, textarea, select').forEach(function (el) { \ |
| 414 | if (!editable(el)) { return; } \ |
| 415 | var moved; \ |
| 416 | if (el.type === 'checkbox' || el.type === 'radio') { moved = el.checked !== el.defaultChecked; } \ |
| 417 | else if (el.tagName === 'SELECT') { \ |
| 418 | var def = -1; \ |
| 419 | for (var j = 0; j < el.options.length; j++) { if (el.options[j].defaultSelected) { def = j; break; } } \ |
| 420 | if (def < 0) { def = 0; } \ |
| 421 | moved = el.selectedIndex !== def; \ |
| 422 | } else { moved = el.value !== el.defaultValue; } \ |
| 423 | var focused = el === active; \ |
| 424 | if (!moved && !focused) { return; } \ |
| 425 | var start = -1, end = -1; \ |
| 426 | try { if (el.selectionStart != null) { start = el.selectionStart; end = el.selectionEnd; } } catch (err) { } \ |
| 427 | out.push({ k: keyOf(el), v: el.value, c: el.checked, i: el.selectedIndex, f: focused, s: start, e: end }); \ |
| 428 | }); \ |
| 429 | return out; \ |
| 430 | } \ |
| 431 | function restoreFields(saved) { \ |
| 432 | if (!saved || !saved.length) { return; } \ |
| 433 | var fields = document.querySelectorAll('input, textarea, select'); \ |
| 434 | saved.forEach(function (was) { \ |
| 435 | var el = null; \ |
| 436 | for (var i = 0; i < fields.length; i++) { \ |
| 437 | if (keyOf(fields[i]) === was.k) { el = fields[i]; break; } \ |
| 438 | } \ |
| 439 | if (!el) { return; } \ |
| 440 | if (el.type === 'checkbox' || el.type === 'radio') { el.checked = was.c; } \ |
| 441 | else if (el.tagName === 'SELECT') { el.selectedIndex = was.i; } \ |
| 442 | else { el.value = was.v; } \ |
| 443 | if (was.f) { \ |
| 444 | try { \ |
| 445 | el.focus(); \ |
| 446 | if (was.s >= 0 && el.setSelectionRange) { el.setSelectionRange(was.s, was.e); } \ |
| 447 | } catch (err) { } \ |
| 448 | } \ |
| 449 | }); \ |
| 450 | } \ |
| 451 | function clientMade(node) { return node.__izAdded === true; } \ |
| 452 | function pairable(a, b) { \ |
| 453 | if (a.nodeType !== b.nodeType) { return false; } \ |
| 454 | if (a.nodeType !== 1) { return true; } \ |
| 455 | if (a.nodeName !== b.nodeName) { return false; } \ |
| 456 | if (a.id || b.id) { return a.id === b.id; } \ |
| 457 | return true; \ |
| 458 | } \ |
| 459 | function syncClass(from, to, own) { \ |
| 460 | var want = []; \ |
| 461 | to.classList.forEach(function (c) { want.push(c); }); \ |
| 462 | if (own) { \ |
| 463 | own.c.forEach(function (c) { \ |
| 464 | if (from.classList.contains(c) && want.indexOf(c) === -1) { want.push(c); } \ |
| 465 | }); \ |
| 466 | } \ |
| 467 | if (want.length) { from.setAttribute('class', want.join(' ')); } \ |
| 468 | else if (from.hasAttribute('class')) { from.removeAttribute('class'); } \ |
| 469 | } \ |
| 470 | function syncAttrs(from, to) { \ |
| 471 | var own = from.__izMine, i, at; \ |
| 472 | for (i = to.attributes.length - 1; i >= 0; i--) { \ |
| 473 | at = to.attributes[i]; \ |
| 474 | if (at.name === 'class') { continue; } \ |
| 475 | if (own && own.a.indexOf(at.name) !== -1) { continue; } \ |
| 476 | if (from.getAttribute(at.name) !== at.value) { from.setAttribute(at.name, at.value); } \ |
| 477 | } \ |
| 478 | for (i = from.attributes.length - 1; i >= 0; i--) { \ |
| 479 | at = from.attributes[i]; \ |
| 480 | if (at.name === 'class') { continue; } \ |
| 481 | if (own && own.a.indexOf(at.name) !== -1) { continue; } \ |
| 482 | if (!to.hasAttribute(at.name)) { from.removeAttribute(at.name); } \ |
| 483 | } \ |
| 484 | syncClass(from, to, own); \ |
| 485 | } \ |
| 486 | function morph(from, to) { \ |
| 487 | if (from.nodeType !== 1) { \ |
| 488 | if (from.nodeValue !== to.nodeValue) { from.nodeValue = to.nodeValue; } \ |
| 489 | return; \ |
| 490 | } \ |
| 491 | syncAttrs(from, to); \ |
| 492 | if (from.nodeName === 'SCRIPT') { \ |
| 493 | if (from.textContent !== to.textContent) { \ |
| 494 | var live = document.createElement('script'); \ |
| 495 | if (to.hasAttribute('src')) { live.setAttribute('src', to.getAttribute('src')); } \ |
| 496 | live.textContent = to.textContent; \ |
| 497 | from.replaceWith(live); \ |
| 498 | } \ |
| 499 | return; \ |
| 500 | } \ |
| 501 | morphChildren(from, to); \ |
| 502 | } \ |
| 503 | function morphChildren(from, to) { \ |
| 504 | var mine = [], theirs = [], n; \ |
| 505 | for (n = from.firstChild; n; n = n.nextSibling) { if (!clientMade(n)) { mine.push(n); } } \ |
| 506 | for (n = to.firstChild; n; n = n.nextSibling) { theirs.push(n); } \ |
| 507 | var i; \ |
| 508 | for (i = 0; i < theirs.length; i++) { \ |
| 509 | if (i < mine.length) { \ |
| 510 | if (pairable(mine[i], theirs[i])) { morph(mine[i], theirs[i]); } \ |
| 511 | else { mine[i].replaceWith(document.importNode(theirs[i], true)); } \ |
| 512 | } else { \ |
| 513 | from.appendChild(document.importNode(theirs[i], true)); \ |
| 514 | } \ |
| 515 | } \ |
| 516 | for (i = theirs.length; i < mine.length; i++) { mine[i].remove(); } \ |
| 517 | } \ |
| 518 | window.__izNav = 0; \ |
| 519 | function navStep() { return ++window.__izNav; } \ |
| 520 | function stillCurrent(n) { return window.__izNav === n; } \ |
| 521 | function swap(html, url, fresh, push, morphing) { \ |
| 522 | var doc = new DOMParser().parseFromString(html, 'text/html'); \ |
| 523 | var build = doc.documentElement.getAttribute('data-build') || ''; \ |
| 524 | if (build && window.__izBuild && build !== window.__izBuild) { \ |
| 525 | var dirty = captureFields().length > 0; \ |
| 526 | var reloaded = null; \ |
| 527 | try { reloaded = sessionStorage.getItem('izSkewFor'); } catch (err) { } \ |
| 528 | if (!dirty && reloaded !== build) { \ |
| 529 | try { sessionStorage.setItem('izSkewFor', build); } catch (err) { } \ |
| 530 | location.reload(); \ |
| 531 | return; \ |
| 532 | } \ |
| 533 | if (!dirty) { \ |
| 534 | window.__izBuild = build; \ |
| 535 | document.documentElement.setAttribute('data-build', build); \ |
| 536 | } \ |
| 537 | } \ |
| 538 | var keep = window.__izKeep ? captureFields() : null; \ |
| 539 | window.__izKeep = false; \ |
| 540 | var x = window.scrollX, y = window.scrollY; \ |
| 541 | var root = doc.documentElement; \ |
| 542 | if (root.getAttribute('lang')) { document.documentElement.setAttribute('lang', root.getAttribute('lang')); } \ |
| 543 | if (root.hasAttribute('data-theme')) { document.documentElement.setAttribute('data-theme', root.getAttribute('data-theme')); } \ |
| 544 | else { document.documentElement.removeAttribute('data-theme'); } \ |
| 545 | if (root.hasAttribute('data-ui')) { document.documentElement.setAttribute('data-ui', root.getAttribute('data-ui')); } \ |
| 546 | else { document.documentElement.removeAttribute('data-ui'); } \ |
| 547 | var freshTitle = doc.querySelector('title'); \ |
| 548 | if (freshTitle && freshTitle.textContent) { document.title = freshTitle.textContent; } \ |
| 549 | if (url) { history[push ? 'pushState' : 'replaceState'](null, '', url); } \ |
| 550 | if (morphing) { \ |
| 551 | morph(document.body, doc.body); \ |
| 552 | } else { \ |
| 553 | document.body.replaceChildren(); \ |
| 554 | while (doc.body.firstChild) { document.body.appendChild(doc.body.firstChild); } \ |
| 555 | document.body.querySelectorAll('script').forEach(function (old) { \ |
| 556 | var live = document.createElement('script'); \ |
| 557 | if (old.hasAttribute('src')) { live.setAttribute('src', old.getAttribute('src')); } \ |
| 558 | live.textContent = old.textContent; \ |
| 559 | old.replaceWith(live); \ |
| 560 | }); \ |
| 561 | window.scrollTo(fresh ? 0 : x, fresh ? 0 : y); \ |
| 562 | } \ |
| 563 | restoreFields(keep); \ |
| 564 | wire(); \ |
| 565 | } \ |
| 566 | function sweepPanels() { \ |
| 567 | document.querySelectorAll('.dd-panel').forEach(function (panel) { \ |
| 568 | if (panel.__ddTrigger && !document.contains(panel.__ddTrigger)) { panel.remove(); } \ |
| 569 | }); \ |
| 570 | } \ |
| 571 | window.__izGo = function (url) { \ |
| 572 | var n = navStep(); \ |
| 573 | fetch(url).then( \ |
| 574 | function (r) { return r.text().then(function (t) { if (stillCurrent(n)) { swap(t, r.url); } }); }, \ |
| 575 | function () { window.location.href = url; } \ |
| 576 | ); \ |
| 577 | }; \ |
| 578 | window.__izRefresh = function () { \ |
| 579 | var n = window.__izNav; \ |
| 580 | fetch(window.location.href).then( \ |
| 581 | function (r) { return r.text().then(function (t) { if (stillCurrent(n)) { swap(t, r.url, false, false, true); } }); }, \ |
| 582 | function () {} \ |
| 583 | ); \ |
| 584 | }; \ |
| 585 | window.__izQuery = function (url) { \ |
| 586 | var n = navStep(); \ |
| 587 | fetch(url).then( \ |
| 588 | function (r) { return r.text().then(function (t) { if (stillCurrent(n)) { swap(t, r.url, false, false, true); } }); }, \ |
| 589 | function () {} \ |
| 590 | ); \ |
| 591 | }; \ |
| 592 | window.__izPost = function (action, fields) { \ |
| 593 | var n = navStep(); \ |
| 594 | fetch(action, { method: 'POST', headers: { accept: 'text/html' }, body: new URLSearchParams(fields) }).then( \ |
| 595 | function (r) { return r.text().then(function (t) { if (stillCurrent(n)) { swap(t, r.url); } }); }, \ |
| 596 | function () {} \ |
| 597 | ); \ |
| 598 | }; \ |
| 599 | window.__izCloseViewer = function () { \ |
| 600 | var scrim = document.querySelector('.viewer-scrim'); \ |
| 601 | if (!scrim) { return false; } \ |
| 602 | var back = scrim.querySelector('.viewer-close').getAttribute('href'); \ |
| 603 | navStep(); \ |
| 604 | scrim.remove(); \ |
| 605 | sweepPanels(); \ |
| 606 | history.replaceState(null, '', back); \ |
| 607 | var modal = document.querySelector('.modal'); \ |
| 608 | if (modal) { modal.focus(); } \ |
| 609 | return true; \ |
| 610 | }; \ |
| 611 | window.__izCloseModal = function () { \ |
| 612 | var scrims = document.querySelectorAll('.modal-scrim'); \ |
| 613 | if (!scrims.length) { return false; } \ |
| 614 | navStep(); \ |
| 615 | scrims.forEach(function (el) { el.remove(); }); \ |
| 616 | sweepPanels(); \ |
| 617 | var u = new URL(window.location.href); \ |
| 618 | ['task', 'file', 'confirm', 'new', 'refusal', 'on'].forEach(function (k) { u.searchParams.delete(k); }); \ |
| 619 | var q = u.searchParams.toString(); \ |
| 620 | history.replaceState(null, '', u.pathname + (q ? '?' + q : '')); \ |
| 621 | return true; \ |
| 622 | }; \ |
| 623 | document.addEventListener('submit', function (e) { \ |
| 624 | var form = e.target; \ |
| 625 | if (!form || form.hasAttribute('data-hard')) { return; } \ |
| 626 | var method = (form.getAttribute('method') || 'get').toLowerCase(); \ |
| 627 | if (method !== 'post') { \ |
| 628 | e.preventDefault(); \ |
| 629 | var q = new URLSearchParams(new FormData(form)).toString(); \ |
| 630 | window.__izGo((form.getAttribute('action') || window.location.pathname) + (q ? '?' + q : '')); \ |
| 631 | return; \ |
| 632 | } \ |
| 633 | e.preventDefault(); \ |
| 634 | var data = e.submitter ? new FormData(form, e.submitter) : new FormData(form); \ |
| 635 | var multipart = (form.getAttribute('enctype') || '').indexOf('multipart') !== -1; \ |
| 636 | if (multipart) { \ |
| 637 | if (form.__izUploading) { return; } \ |
| 638 | form.__izUploading = true; \ |
| 639 | var n = navStep(); \ |
| 640 | var box = form.querySelector('.file-upload-box'); \ |
| 641 | var input = form.querySelector('.file-upload-input'); \ |
| 642 | var bar = null, drop = null; \ |
| 643 | if (box) { \ |
| 644 | bar = document.createElement('div'); \ |
| 645 | bar.className = 'upload-progress'; \ |
| 646 | var fill = document.createElement('div'); \ |
| 647 | fill.className = 'upload-progress-fill'; \ |
| 648 | bar.appendChild(fill); \ |
| 649 | box.appendChild(window.__izAdded(bar)); \ |
| 650 | drop = document.createElement('button'); \ |
| 651 | drop.type = 'button'; \ |
| 652 | drop.className = 'file-chip-drop upload-progress-drop'; \ |
| 653 | var cancelLabel = form.getAttribute('data-cancel-label'); \ |
| 654 | if (cancelLabel) { drop.setAttribute('aria-label', cancelLabel); } \ |
| 655 | drop.innerHTML = '<svg class=\"glyph\" width=\"13\" height=\"13\" viewBox=\"0 0 16 16\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.5\" stroke-linecap=\"round\" aria-hidden=\"true\"><path d=\"M4 4l8 8M12 4l-8 8\"></path></svg>'; \ |
| 656 | drop.addEventListener('click', function (e) { e.preventDefault(); e.stopPropagation(); x.abort(); }); \ |
| 657 | box.appendChild(window.__izAdded(drop)); \ |
| 658 | } \ |
| 659 | if (input) { input.disabled = true; window.__izOwn(input, [], ['disabled']); } \ |
| 660 | var settle = function () { \ |
| 661 | form.__izUploading = false; \ |
| 662 | if (input) { input.disabled = false; } \ |
| 663 | if (bar && bar.parentNode) { bar.parentNode.removeChild(bar); } \ |
| 664 | if (drop && drop.parentNode) { drop.parentNode.removeChild(drop); } \ |
| 665 | }; \ |
| 666 | var x = new XMLHttpRequest(); \ |
| 667 | x.open('POST', form.getAttribute('action') || window.location.href); \ |
| 668 | x.setRequestHeader('accept', 'text/html'); \ |
| 669 | x.upload.onprogress = function (ev) { \ |
| 670 | if (!fill) { return; } \ |
| 671 | if (!bar.isConnected) { box.appendChild(bar); if (drop) { box.appendChild(drop); } } \ |
| 672 | if (ev.lengthComputable && ev.total > 0) { fill.style.width = Math.min(100, Math.round((ev.loaded / ev.total) * 100)) + '%'; } \ |
| 673 | }; \ |
| 674 | x.onload = function () { \ |
| 675 | settle(); \ |
| 676 | if (!stillCurrent(n)) { return; } \ |
| 677 | swap(x.responseText, x.responseURL || form.getAttribute('action') || window.location.href); \ |
| 678 | }; \ |
| 679 | x.onerror = function () { settle(); form.submit(); }; \ |
| 680 | x.onabort = function () { \ |
| 681 | if (input) { input.value = ''; } \ |
| 682 | var name = box ? box.querySelector('.file-upload-name') : null; \ |
| 683 | var empty = form.getAttribute('data-empty-label'); \ |
| 684 | if (name && empty) { name.textContent = empty; } \ |
| 685 | settle(); \ |
| 686 | }; \ |
| 687 | x.send(data); \ |
| 688 | return; \ |
| 689 | } \ |
| 690 | var n = navStep(); \ |
| 691 | fetch(form.getAttribute('action'), { method: 'POST', headers: { accept: 'text/html' }, body: new URLSearchParams(data) }).then( \ |
| 692 | function (r) { return r.text().then(function (t) { if (stillCurrent(n)) { swap(t, r.url); } }); }, \ |
| 693 | function () { form.submit(); } \ |
| 694 | ); \ |
| 695 | }, true); \ |
| 696 | document.addEventListener('change', function (e) { \ |
| 697 | var control = e.target; \ |
| 698 | if (control.classList && control.classList.contains('file-upload-input')) { \ |
| 699 | var label = control.closest('label'); \ |
| 700 | var name = label ? label.querySelector('.file-upload-name') : null; \ |
| 701 | if (name && control.files && control.files[0]) { \ |
| 702 | name.textContent = control.files[0].name + (control.files.length > 1 ? ' +' + (control.files.length - 1) : ''); \ |
| 703 | } \ |
| 704 | control.form.requestSubmit(); \ |
| 705 | return; \ |
| 706 | } \ |
| 707 | if (control.hasAttribute && control.hasAttribute('data-autosubmit')) { control.form.requestSubmit(); } \ |
| 708 | }); \ |
| 709 | // The Files tab's whole pane is the upload box's hit area: a drag |
| 710 | // caught anywhere in `.files-pane` lands on the box inside it, and |
| 711 | // the box is also the element that wears the mark — the control |
| 712 | // signals, the pane catches. A pane with no box (a viewer's Files |
| 713 | // tab) is not a target at all. |
| 714 | function uploadBox(zone) { \ |
| 715 | return zone.classList.contains('files-pane') ? zone.querySelector('.file-upload-box') : zone; \ |
| 716 | } \ |
| 717 | document.addEventListener('dragover', function (e) { \ |
| 718 | var zone = e.target.closest ? e.target.closest('.file-upload-box, .files-pane') : null; \ |
| 719 | var box = zone ? uploadBox(zone) : null; \ |
| 720 | if (!box || !e.dataTransfer || e.dataTransfer.types.indexOf('Files') === -1) { return; } \ |
| 721 | e.preventDefault(); \ |
| 722 | e.dataTransfer.dropEffect = 'copy'; \ |
| 723 | window.__izOwn(box, ['file-upload-over'], []); \ |
| 724 | }); \ |
| 725 | document.addEventListener('dragleave', function (e) { \ |
| 726 | var zone = e.target.closest ? e.target.closest('.file-upload-box, .files-pane') : null; \ |
| 727 | if (zone && !zone.contains(e.relatedTarget)) { \ |
| 728 | var box = uploadBox(zone); \ |
| 729 | if (box) { box.classList.remove('file-upload-over'); } \ |
| 730 | } \ |
| 731 | }); \ |
| 732 | document.addEventListener('drop', function (e) { \ |
| 733 | var zone = e.target.closest ? e.target.closest('.file-upload-box, .files-pane') : null; \ |
| 734 | var box = zone ? uploadBox(zone) : null; \ |
| 735 | if (!box) { return; } \ |
| 736 | e.preventDefault(); \ |
| 737 | box.classList.remove('file-upload-over'); \ |
| 738 | var input = box.querySelector('.file-upload-input'); \ |
| 739 | var form = input ? input.form : null; \ |
| 740 | if (!input || !form || form.__izUploading || !e.dataTransfer || !e.dataTransfer.files || e.dataTransfer.files.length === 0) { return; } \ |
| 741 | input.files = e.dataTransfer.files; \ |
| 742 | input.dispatchEvent(new Event('change', { bubbles: true })); \ |
| 743 | }); \ |
| 744 | document.addEventListener('click', function (e) { \ |
| 745 | var link = e.target.closest ? e.target.closest('a') : null; \ |
| 746 | if (link) { \ |
| 747 | if (link.classList.contains('viewer-close') || (link.classList.contains('detail-close') && link.closest('.viewer-scrim'))) { \ |
| 748 | e.preventDefault(); \ |
| 749 | window.__izCloseViewer(); \ |
| 750 | return; \ |
| 751 | } \ |
| 752 | if (link.getAttribute('href') === '/' && link.closest('.modal-scrim')) { \ |
| 753 | e.preventDefault(); \ |
| 754 | window.__izCloseModal(); \ |
| 755 | return; \ |
| 756 | } \ |
| 757 | } \ |
| 758 | if (e.target.classList && e.target.classList.contains('modal-scrim')) { \ |
| 759 | if (e.target.classList.contains('viewer-scrim')) { window.__izCloseViewer(); } \ |
| 760 | else { window.__izCloseModal(); } \ |
| 761 | } \ |
| 762 | }, true); \ |
| 763 | window.addEventListener('popstate', function () { window.__izGo(window.location.href); }); \ |
| 764 | document.addEventListener('click', function (e) { \ |
| 765 | if (e.defaultPrevented || e.button !== 0 || e.ctrlKey || e.metaKey || e.shiftKey || e.altKey) { return; } \ |
| 766 | var link = e.target.closest ? e.target.closest('a') : null; \ |
| 767 | if (!link || link.hasAttribute('download') || link.hasAttribute('target') || link.hasAttribute('data-hard')) { return; } \ |
| 768 | var href = link.getAttribute('href'); \ |
| 769 | if (!href || href.charAt(0) !== '/' || href.indexOf('/files/') === 0) { return; } \ |
| 770 | e.preventDefault(); \ |
| 771 | var n = navStep(); \ |
| 772 | fetch(href).then( \ |
| 773 | function (r) { return r.text().then(function (t) { if (stillCurrent(n)) { swap(t, r.url, true, true); } }); }, \ |
| 774 | function () { window.location.href = href; } \ |
| 775 | ); \ |
| 776 | }, true); \ |
| 777 | document.addEventListener('click', function (e) { \ |
| 778 | if (e.target.closest && e.target.closest('.dd-trigger, .dd-panel, button, a, input, select, textarea')) { return; } \ |
| 779 | var box = e.target.closest ? e.target.closest('.field-box, .status-form, .member-role') : null; \ |
| 780 | if (!box) { return; } \ |
| 781 | var trigger = box.querySelector('.dd-trigger'); \ |
| 782 | if (trigger) { e.stopImmediatePropagation(); trigger.click(); } \ |
| 783 | }); \ |
| 784 | if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', wire); } else { wire(); } \ |
| 785 | })();"; |
| 786 | Ok(view! { cx => <script>(Unescaped::new_unchecked(JS))</script> }.boxed()) |
| 787 | } |
| 788 | |
| 789 | /// The one document-level capture `keydown` listener for `Escape`, emitted |
| 790 | /// once from `root_layout` before every page's own scripts. Owners install |
| 791 | /// no listeners of their own; their scripts call |
| 792 | /// `window.__izEsc.register(priority, fn)` and on `Escape` the manager |
| 793 | /// runs the resolvers highest-priority first — the first to return true |
| 794 | /// closes its surface and the manager stops the key. Every consuming press |
| 795 | /// gets `preventDefault()`: a real Escape's browser default is stop-loading |
| 796 | /// (it once cancelled the navigation these branches used to start; synthetic |
| 797 | /// keys carry no default, so only a live keyboard ever showed it). |
| 798 | /// |
| 799 | /// The table below is the whole precedence order, topmost first; a resolver |
| 800 | /// whose surface is absent returns false so lower layers get the press. It |
| 801 | /// reproduces what the four former listeners' registration order produced |
| 802 | /// per page (the modal's inline `escape_closes` registered before the board |
| 803 | /// page's trailing scripts, `dropdown_script` before `escape_script` on |
| 804 | /// settings/rules, `escape_script` before `card_menu_script` on the board): |
| 805 | /// |
| 806 | /// | prio | closes | registered by | |
| 807 | /// |------|--------|---------------| |
| 808 | /// | 95 | the open dropdown panel (refocusing its trigger) | `dropdown.rs`'s `dropdown_script` | |
| 809 | /// | 90 | the viewer, then the delete confirm, then non-datepick edit popovers, then the task modal | `detail.rs`'s `escape_closes` | |
| 810 | /// | 40 | the topbar `.user-menu` (pin+blur), then the rules composer, then a rules edit row (back to `/rules`) | `layout.rs`'s `escape_script` | |
| 811 | /// | 20 | the datepicker popover | `board.rs`'s `card_menu_script` | |
| 812 | /// | 10 | the card context menu | `board.rs`'s `card_menu_script` | |
| 813 | /// The live channel's browser half: one `EventSource` per tab, and the slow |
| 814 | /// tick that keeps clock-driven text honest. |
| 815 | /// |
| 816 | /// Everything here is one script because both halves end in the same act — |
| 817 | /// re-fetch the current URL through `__izGo` and let `swap()` do what it |
| 818 | /// already does after every form post. There is deliberately no second render |
| 819 | /// path: a partial-update mechanism would be a second way for the page to be |
| 820 | /// wrong, and the full swap is the one the app exercises constantly. |
| 821 | /// |
| 822 | /// Three things it must not get wrong: |
| 823 | /// |
| 824 | /// The `__izLive` guard is not decoration. `swap()` re-executes every |
| 825 | /// swapped-in script, so without it each soft navigation would open another |
| 826 | /// `EventSource` and the tab would end up holding one connection per page it |
| 827 | /// had ever visited. |
| 828 | /// |
| 829 | /// A refresh must not disturb what somebody is in the middle of. The first |
| 830 | /// attempt held the refresh back while a form was dirty, which was wrong twice |
| 831 | /// over: one unsubmitted form froze every other surface on the screen, and a |
| 832 | /// dropdown could never be used at all while the workspace was busy, because |
| 833 | /// each update slammed it shut. |
| 834 | /// |
| 835 | /// The cause of both was the refresh throwing the whole page away. So the live |
| 836 | /// path does not: it MORPHS. `swap`'s morphing mode walks the freshly fetched |
| 837 | /// document against the live one and touches only what actually differs — |
| 838 | /// changed text, changed attributes, added and removed nodes. Everything else |
| 839 | /// is the same DOM node it was a moment ago, so an open dropdown stays open, a |
| 840 | /// caret stays where it was, a half-typed comment keeps its text, and a scrolled |
| 841 | /// panel keeps its position. Not because any of them is special-cased, but |
| 842 | /// because nothing touched them. |
| 843 | /// |
| 844 | /// A `<script>` whose text is unchanged is left alone rather than re-created, |
| 845 | /// so the live path stops re-running every script on the page; the `__iz*` |
| 846 | /// guards remain the backstop for the full-swap path, which still re-runs them. |
| 847 | /// |
| 848 | /// ## The client declares what is its own |
| 849 | /// |
| 850 | /// A morph rebuilds the page from HTML that knows nothing about the client. |
| 851 | /// Two things it would therefore destroy: nodes the client created, which |
| 852 | /// look like strays, and the marks an enhancement leaves on a node the server |
| 853 | /// *did* render — `dd-native` hiding a replaced select, `data-wired` on a |
| 854 | /// wired player, the position an open context menu was placed at. |
| 855 | /// |
| 856 | /// The first version of this knew their names: `clientMade` tested for |
| 857 | /// `.dd-panel`/`.dd-trigger`, and the attribute sweep skipped anything |
| 858 | /// starting with `data-dd`. That is a list, and a list is wrong the first |
| 859 | /// time somebody adds an enhancement without reading it. It was already |
| 860 | /// wrong: `data-dd-done` was on the list and `class` was not, so a save |
| 861 | /// unhid every native select underneath its own trigger while `enhanceAll` |
| 862 | /// skipped them as already done — one dropdown drawn twice, per field. |
| 863 | /// |
| 864 | /// So the morph knows no names at all. A node says what belongs to the |
| 865 | /// client, at the moment the client takes it: |
| 866 | /// |
| 867 | /// - `__izOwn(node, classes, attrs)` — the classes and attributes on this |
| 868 | /// server-rendered node are the client's. It adds the classes itself, so |
| 869 | /// there is no way to apply one without registering it. |
| 870 | /// - `__izAdded(node)` — this whole node is the client's; it is not a |
| 871 | /// stray and must not be deleted. |
| 872 | /// |
| 873 | /// Both record on a DOM *property*, which no morph can strip, and both are |
| 874 | /// defined here — before any script that could enhance anything runs. |
| 875 | /// `syncAttrs` then merges `class` (the server's list plus whatever owned |
| 876 | /// classes are still on the node) instead of overwriting it, and skips owned |
| 877 | /// attributes both when it copies the server's over and when it sweeps the |
| 878 | /// ones the server no longer has — an owned attribute is the client's fact, |
| 879 | /// stale server bytes say nothing against it. Nothing in this file mentions |
| 880 | /// a dropdown. |
| 881 | /// |
| 882 | /// The other half of the contract is `iz:wire`: an enhancement re-derives |
| 883 | /// whatever it draws from server data rather than assuming it is still true. |
| 884 | /// Ownership keeps the morph from breaking the enhancement; the wire pass is |
| 885 | /// how the enhancement follows the server when the data underneath it moves. |
| 886 | /// |
| 887 | /// Morphing is used only for the live refresh. Navigations and form posts keep |
| 888 | /// the full replace: they are a different page or a submitted form, where |
| 889 | /// carrying the old DOM's state over is wrong rather than kind. |
| 890 | /// |
| 891 | /// The tick exists because some text goes stale with no write behind it: the |
| 892 | /// queue's next-try time and a card's overdue mark change because the clock |
| 893 | /// moved, and no announcement will ever fire for that. Rather than re-format |
| 894 | /// those in JavaScript — which would mean a second implementation of the |
| 895 | /// locale- and timezone-aware formatting the server already does, free to |
| 896 | /// disagree with it — the tick re-fetches, and the server stays the only thing |
| 897 | /// that decides what a moment reads as. It runs only on pages carrying a |
| 898 | /// `data-tick` element, so a page with no clock-driven text is silent. |
| 899 | /// The channel also carries one goodbye: a `revoked` frame means this |
| 900 | /// tab's account was killed at the provider, and the answer is a hard |
| 901 | /// redirect to the front door, not a morph. A dropped stream is the other |
| 902 | /// way a tab learns it may be alone: the error path asks `/api/me`, and a |
| 903 | /// `401` there is the same redirect. A merely restarting server answers |
| 904 | /// 204, so a signed-in tab loses nothing — the `EventSource` reconnects |
| 905 | /// on its own. |
| 906 | /// |
| 907 | pub async fn live_script<'a>(cx: &'a Cx) -> Result<impl View + 'a> { |
| 908 | const JS: &str = "\ |
| 909 | (function () { \ |
| 910 | if (window.__izLive) { return; } \ |
| 911 | window.__izLive = true; \ |
| 912 | var timer = null; \ |
| 913 | function refresh() { \ |
| 914 | window.__izKeep = true; \ |
| 915 | if (window.__izRefresh) { window.__izRefresh(); } \ |
| 916 | } \ |
| 917 | function schedule() { \ |
| 918 | if (timer) { clearTimeout(timer); } \ |
| 919 | timer = setTimeout(function () { timer = null; refresh(); }, 200); \ |
| 920 | } \ |
| 921 | function wanted(topic) { \ |
| 922 | if (topic === 'resync') { return true; } \ |
| 923 | var path = window.location.pathname; \ |
| 924 | if (path === '/logs') { return topic !== 'board' && topic !== 'task'; } \ |
| 925 | if (path === '/rules') { return topic === 'rules' || topic === 'members'; } \ |
| 926 | if (path === '/tags') { return topic === 'tags' || topic === 'members'; } \ |
| 927 | if (path === '/settings') { return topic === 'settings' || topic === 'members'; } \ |
| 928 | if (path === '/people/') { return topic === 'members'; } \ |
| 929 | return topic === 'members'; \ |
| 930 | } \ |
| 931 | try { \ |
| 932 | var src = new EventSource('/api/live'); \ |
| 933 | src.onmessage = function (e) { \ |
| 934 | var frame; \ |
| 935 | try { frame = JSON.parse(e.data); } catch (err) { return; } \ |
| 936 | if (frame && frame.topic === 'revoked') { window.location.href = '/'; return; } \ |
| 937 | if (frame && wanted(frame.topic)) { schedule(); } \ |
| 938 | }; \ |
| 939 | src.onerror = function () { \ |
| 940 | fetch('/api/me', { cache: 'no-store' }).then(function (r) { \ |
| 941 | if (r.status === 401) { window.location.href = '/'; } \ |
| 942 | }).catch(function () { }); \ |
| 943 | }; \ |
| 944 | } catch (err) { } \ |
| 945 | setInterval(function () { \ |
| 946 | if (document.querySelector('[data-tick]')) { refresh(); } \ |
| 947 | }, 60000); \ |
| 948 | })(); \ |
| 949 | "; |
| 950 | Ok(view! { cx => <script>(Unescaped::new_unchecked(JS))</script> }.boxed()) |
| 951 | } |
| 952 | |
| 953 | pub async fn escape_manager_script<'a>(cx: &'a Cx) -> Result<impl View + 'a> { |
| 954 | use topcoat::view::{Unescaped, ViewExt}; |
| 955 | const JS: &str = "\ |
| 956 | (function () { \ |
| 957 | if (window.__izEsc) { return; } \ |
| 958 | window.__izEsc = { \ |
| 959 | resolvers: [], \ |
| 960 | register: function (priority, fn) { \ |
| 961 | window.__izEsc.resolvers.push({ priority: priority, fn: fn }); \ |
| 962 | window.__izEsc.resolvers.sort(function (a, b) { return b.priority - a.priority; }); \ |
| 963 | } \ |
| 964 | }; \ |
| 965 | document.addEventListener('keydown', function (e) { \ |
| 966 | if (e.key !== 'Escape') { return; } \ |
| 967 | for (var i = 0; i < window.__izEsc.resolvers.length; i++) { \ |
| 968 | if (window.__izEsc.resolvers[i].fn(e)) { \ |
| 969 | e.preventDefault(); \ |
| 970 | e.stopImmediatePropagation(); \ |
| 971 | return; \ |
| 972 | } \ |
| 973 | } \ |
| 974 | }, true); \ |
| 975 | })();"; |
| 976 | Ok(view! { cx => <script>(Unescaped::new_unchecked(JS))</script> }.boxed()) |
| 977 | } |
| 978 | /// Registers the topbar/rules `Escape` resolvers on `window.__izEsc` |
| 979 | /// (priority 40 — the table is on `escape_manager_script`): the topbar |
| 980 | /// `.user-menu` panel — hover-open included, pinned shut by a |
| 981 | /// `user-menu-esc` class that a `mouseenter` inside the menu clears — then |
| 982 | /// a `.rule-new` composer left open on the rules page, then a rules edit |
| 983 | /// row (navigating back to `/rules`). Never touches |
| 984 | /// `details.confirm-details`; that flow stays `detail.rs`'s. |
| 985 | pub async fn escape_script<'a>(cx: &'a Cx) -> Result<impl View + 'a> { |
| 986 | const JS: &str = "\ |
| 987 | (function () { \ |
| 988 | if (window.__izEscTop) { return; } \ |
| 989 | window.__izEscTop = true; \ |
| 990 | window.__izEsc.register(40, function () { \ |
| 991 | var menu = document.querySelector('.user-menu'); \ |
| 992 | if (menu && (menu.matches(':hover') || menu.contains(document.activeElement))) { \ |
| 993 | window.__izOwn(menu, ['user-menu-esc'], []); \ |
| 994 | var focused = document.activeElement; \ |
| 995 | if (focused && focused.closest('.user-menu')) { focused.blur(); } \ |
| 996 | return true; \ |
| 997 | } \ |
| 998 | var composer = document.querySelector('details.rule-new[open]'); \ |
| 999 | if (composer) { composer.removeAttribute('open'); return true; } \ |
| 1000 | if (document.querySelector('.rule-new-body[action=\"/api/update_rule\"]')) { \ |
| 1001 | if (window.__izGo) { window.__izGo('/rules'); } else { window.location.href = '/rules'; } \ |
| 1002 | return true; \ |
| 1003 | } \ |
| 1004 | return false; \ |
| 1005 | }); \ |
| 1006 | document.addEventListener('mouseenter', function (e) { \ |
| 1007 | var menu = e.target.closest ? e.target.closest('.user-menu') : null; \ |
| 1008 | if (menu) { menu.classList.remove('user-menu-esc'); } \ |
| 1009 | }, true); \ |
| 1010 | })();"; |
| 1011 | Ok(view! { cx => <script>(Unescaped::new_unchecked(JS))</script> }.boxed()) |
| 1012 | } |
| 1013 | |
| 1014 | /// Every path that matches no page raises a `NotFoundError`, so it renders |
| 1015 | /// through `root_layout`'s catch below rather than the router's bare default. |
| 1016 | /// `/` itself is served by `landing` above and never reaches this route. |
| 1017 | #[page("/{*path}")] |
| 1018 | async fn missing() -> Result<BoxView<'static>> { |
| 1019 | Err(not_found().into()) |
| 1020 | } |
| 1021 | |
| 1022 | /// `style/main.scss`, compiled by `build.rs` into `assets/main.css`. |
| 1023 | const STYLE: Asset = asset!("assets/main.css"); |
| 1024 | |
| 1025 | #[layout("/")] |
| 1026 | async fn root_layout(cx: &Cx, slot: topcoat::view::Child<'_>) -> Result<impl View> { |
| 1027 | // Pages with no session (auth screens) render light and English; both are |
| 1028 | // only set when the request's own user has one to read. |
| 1029 | let asking = match current_user(cx).await { |
| 1030 | Ok(user) => user.as_ref(), |
| 1031 | Err(_) => None, |
| 1032 | }; |
| 1033 | let dark = asking.is_some_and(|user| user.theme == "dark"); |
| 1034 | let ui = asking.map_or("instrument", |user| user.ui.as_str()); |
| 1035 | let lang = asking.map_or(Lang::En, |user| Lang::from_code(&user.language)); |
| 1036 | |
| 1037 | let nothing = t(lang, Key::NothingAtThisAddress).to_string(); |
| 1038 | // The tab title a page wears, read off its address: the shell is |
| 1039 | // paired around pages by path prefix, so a page cannot hand its name |
| 1040 | // up — the router's own address decides. The signed-out front door is |
| 1041 | // the sign-in card, not the board. Anything unmatched — the catch-all |
| 1042 | // 404 among it — reads as the app's bare name. |
| 1043 | let path = topcoat::router::request::uri(cx).path(); |
| 1044 | let title = match path { |
| 1045 | "/" if asking.is_none() => format!("{} · iz", t(lang, Key::SignIn)), |
| 1046 | "/" => format!("{} · iz", t(lang, Key::NavBoard)), |
| 1047 | p if p.starts_with("/rules") => format!("{} · iz", t(lang, Key::NavMailRules)), |
| 1048 | p if p.starts_with("/logs") => format!("{} · iz", t(lang, Key::NavLogs)), |
| 1049 | p if p.starts_with("/tags") => format!("{} · iz", t(lang, Key::NavTags)), |
| 1050 | p if p.starts_with("/settings") => format!("{} · iz", t(lang, Key::NavSettings)), |
| 1051 | p if p.starts_with("/people") => format!("{} · iz", t(lang, Key::Members)), |
| 1052 | _ => "iz".to_string(), |
| 1053 | }; |
| 1054 | Ok(view! { |
| 1055 | cx => |
| 1056 | <!DOCTYPE html> |
| 1057 | <html lang=(lang.code()) data-theme=(dark.then_some("dark")) data-ui=(ui) data-build=(STYLE.id().as_u64().to_string())> |
| 1058 | <head> |
| 1059 | <meta charset="utf-8"> |
| 1060 | <meta name="viewport" content="width=device-width, initial-scale=1"> |
| 1061 | <link rel="preconnect" href="https://fonts.googleapis.com"> |
| 1062 | <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin=""> |
| 1063 | <link |
| 1064 | rel="stylesheet" |
| 1065 | href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500&family=Newsreader:ital,wght@0,400;0,600;1,400;1,600&display=swap" |
| 1066 | > |
| 1067 | <title>(title)</title> |
| 1068 | <link rel="icon" href=(FAVICON)> |
| 1069 | <link rel="stylesheet" href=(STYLE)> |
| 1070 | topcoat::runtime::script() |
| 1071 | topcoat::dev::script() |
| 1072 | </head> |
| 1073 | <body> |
| 1074 | (topcoat::view::Child::new(escape_manager_script(cx).await?)) |
| 1075 | (topcoat::view::Child::new(soft_nav_script(cx).await?)) |
| 1076 | if asking.is_some() { (topcoat::view::Child::new(live_script(cx).await?)) } |
| 1077 | error_boundary( |
| 1078 | fallback: |error| { |
| 1079 | if error.downcast_ref::<NotFoundError>().is_none() { |
| 1080 | return Err(error); |
| 1081 | } |
| 1082 | Ok(view! { |
| 1083 | cx => |
| 1084 | (StatusCode::NOT_FOUND) |
| 1085 | <main class="scaffold-note"> |
| 1086 | <p>(nothing)</p> |
| 1087 | </main> |
| 1088 | }) |
| 1089 | }, |
| 1090 | (slot) |
| 1091 | ) |
| 1092 | </body> |
| 1093 | </html> |
| 1094 | }.boxed()) |
| 1095 | } |