forge
Explore
Log in

Don't you dare go Hollow

in_old

Clone
★ 0

0 watching0 forksRustGPL-3.01.1 MiB218b775Tahinli2 months ago90 commits

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