| 1 | /* rastrillo.js — the fragment shim. First-party, dependency-free, and |
| 2 | almost entirely inert: the polling section answers only to an opt-in |
| 3 | data attribute, and everything it enhances also works with scripts |
| 4 | disabled (a status page's <noscript> meta refresh). This file is |
| 5 | app-owned from the moment it is scaffolded — edit it like any other |
| 6 | static file. |
| 7 | |
| 8 | One section is on by default instead, because it has no per-instance |
| 9 | decision to make: light dismiss for the menu idioms, keyed off the |
| 10 | rst-dropdown / rst-row-menu attributes — a menu that closes on an |
| 11 | outside click on one screen and not the next is worse than either |
| 12 | rule applied everywhere. Delete it to opt the whole app out. |
| 13 | |
| 14 | The busy rule, which used to live here too, is busy.js: link it and |
| 15 | every submit button in every form is covered; leave it out and none |
| 16 | is. |
| 17 | |
| 18 | Vocabulary: |
| 19 | data-poll="URL" fetch URL for an HTML fragment, replace this |
| 20 | element with it, and keep going only if the |
| 21 | replacement element itself carries data-poll |
| 22 | data-poll-every="2" seconds between polls (default 2) |
| 23 | data-poll-push="URL" optional, beside data-poll: open an |
| 24 | EventSource to URL and re-fetch the fragment |
| 25 | when the server says so, instead of on a |
| 26 | timer. Any EventSource error downgrades this |
| 27 | element to timer polling for good (once, |
| 28 | no flapping); a browser without EventSource |
| 29 | never leaves the timer path |
| 30 | |
| 31 | select.js is a sibling file following exactly these rules, kept |
| 32 | separate so this one stays small enough to read in one sitting. It |
| 33 | answers data-rst-select on a <select>, which field-select emits past |
| 34 | ten options. |
| 35 | |
| 36 | Every poll carries the request header Rastrillo-Fragment: 1, which |
| 37 | marks the request as a shim poll so a handler can tell it apart from |
| 38 | direct navigation. Reserved: the framework's own handlers do not |
| 39 | read it today. |
| 40 | |
| 41 | Menus: an open <details rst-dropdown>, <details rst-row-menu>, a |
| 42 | nested <details rst-menu-group>, or the topbar's and console's narrow |
| 43 | <details rst-shell-menu> card (whose content is its next sibling, the |
| 44 | tail) closes on an outside click and on Escape, in EITHER spelling, |
| 45 | so upgrading this file before running `rastrillo markup` leaves no |
| 46 | dead menus. Exclusivity stays native. (anchor.js, beside this file, |
| 47 | keeps a dropdown's menu on the screen where CSS anchor positioning |
| 48 | is missing.) A switch's knob can be dragged along its track, and |
| 49 | snaps to the nearer end. The colour-scheme menu's forms apply in |
| 50 | place and write the server's cookie, instead of posting. |
| 51 | |
| 52 | A polled response may answer 204 with a Rastrillo-Location header |
| 53 | instead of a fragment; the shim navigates there, but only to a local |
| 54 | path. 403 and 404 end the poll for good — the job was swept, or was |
| 55 | never yours. Any other fetch error backs off (doubling to a 30s cap) |
| 56 | and keeps trying — a network blip must not strand a status page. */ |
| 57 | (function () { |
| 58 | "use strict"; |
| 59 | |
| 60 | // The same rule sessions.SafeReturn enforces server-side: a same-site |
| 61 | // absolute path — starts with exactly one "/", no scheme, no |
| 62 | // backslash, no control characters (browsers strip tab/CR/LF before |
| 63 | // parsing, so "/\t/evil.example" would resolve scheme-relative). |
| 64 | // Anything laxer is an open redirect, here driven by a response |
| 65 | // header instead of a form field. |
| 66 | function localPath(to) { |
| 67 | return to.charAt(0) === "/" && to.charAt(1) !== "/" && |
| 68 | to.indexOf("\\") === -1 && !/[\u0000-\u001f\u007f]/.test(to); |
| 69 | } |
| 70 | |
| 71 | function poll(el) { |
| 72 | var base = (parseFloat(el.getAttribute("data-poll-every")) || 2) * 1000; |
| 73 | var wait = base; |
| 74 | var src = null; // open EventSource while pushing; null on the timer path |
| 75 | var busy = false; // a fetch is in flight |
| 76 | var queued = false; // an update landed mid-fetch; tick again after it |
| 77 | function stop() { |
| 78 | if (src) { src.close(); src = null; } |
| 79 | } |
| 80 | // One downgrade, never back: push hands this element to the timer. |
| 81 | function fallback() { |
| 82 | stop(); |
| 83 | schedule(); |
| 84 | } |
| 85 | function tick() { |
| 86 | if (busy) { queued = true; return; } |
| 87 | busy = true; |
| 88 | fetch(el.getAttribute("data-poll"), { headers: { "Rastrillo-Fragment": "1" } }) |
| 89 | .then(function (res) { |
| 90 | // Terminal, not an error to retry: retrying a 404 forever is |
| 91 | // noise, and following a signed-out redirect would swap a |
| 92 | // sign-in page into the fragment's slot. |
| 93 | if (res.status === 403 || res.status === 404) return null; |
| 94 | if (!res.ok && res.status !== 204) throw new Error("status " + res.status); |
| 95 | var to = res.headers.get("Rastrillo-Location"); |
| 96 | if (to) { |
| 97 | if (localPath(to)) window.location.assign(to); |
| 98 | return null; // navigating, or refusing to — either way, done |
| 99 | } |
| 100 | return res.text(); |
| 101 | }) |
| 102 | .then(function (html) { |
| 103 | busy = false; |
| 104 | if (html === null) { stop(); return; } // stopped |
| 105 | wait = base; // a healthy response resets the backoff |
| 106 | var tpl = document.createElement("template"); |
| 107 | tpl.innerHTML = html; |
| 108 | var next = tpl.content.firstElementChild; |
| 109 | if (!next) { stop(); return; } // fragment with no element: stop politely |
| 110 | el.replaceWith(next); |
| 111 | el = next; |
| 112 | if (!el.hasAttribute("data-poll")) { stop(); return; } |
| 113 | if (!src) { schedule(); return; } |
| 114 | // Pushing: a fragment that dropped data-poll-push falls back |
| 115 | // to the timer; otherwise catch up if an update was queued. |
| 116 | if (!el.hasAttribute("data-poll-push")) { fallback(); return; } |
| 117 | if (queued) { queued = false; tick(); } |
| 118 | }) |
| 119 | .catch(function () { |
| 120 | busy = false; |
| 121 | wait = Math.min(wait * 2, 30000); |
| 122 | if (!src) schedule(); // pushing: the next event retries instead |
| 123 | }); |
| 124 | } |
| 125 | function schedule() { setTimeout(tick, wait); } |
| 126 | var push = el.getAttribute("data-poll-push"); |
| 127 | if (push && window.EventSource) { |
| 128 | src = new EventSource(push); |
| 129 | src.addEventListener("update", function () { tick(); }); |
| 130 | src.addEventListener("done", function () { stop(); tick(); }); |
| 131 | src.addEventListener("gone", stop); |
| 132 | src.onerror = fallback; |
| 133 | return; |
| 134 | } |
| 135 | schedule(); |
| 136 | } |
| 137 | |
| 138 | // Light dismiss — the one behaviour the native disclosure genuinely |
| 139 | // cannot do, which is the shim's whole admission rule. A <details> |
| 140 | // menu closes on a second click of its own summary and on nothing |
| 141 | // else: not on a click elsewhere on the page, not on Escape. Both are |
| 142 | // what every menu anywhere else does, and neither is expressible in |
| 143 | // HTML or CSS. |
| 144 | // |
| 145 | // Two delegated listeners on the document, never one per element, so a |
| 146 | // dropdown that arrives inside a polled fragment is covered the moment |
| 147 | // it lands and re-scanning can never double-bind. Capture phase, so a |
| 148 | // page whose own handler stops propagation cannot leave a menu stuck |
| 149 | // open. |
| 150 | // |
| 151 | // The scriptless baseline is untouched: with this file removed, the |
| 152 | // menus still toggle and the native <details name> group still keeps |
| 153 | // one open at a time. |
| 154 | // |
| 155 | // The nested rst-menu-group is in MENUS even though it is never in the |
| 156 | // <details name> group with its parent — the two mechanisms answer |
| 157 | // different questions. The name group decides which menus may be open |
| 158 | // at once, and a submenu must be exempt from it or opening one would |
| 159 | // close the menu around it. Dismissal is not exclusivity: a submenu |
| 160 | // left open behind its closing parent is still open the next time the |
| 161 | // parent opens, which is a menu remembering a state the user has no |
| 162 | // way to see. Listing it here also gives the natural behaviour of |
| 163 | // clicking elsewhere INSIDE the parent closing the submenu — the |
| 164 | // contains(except) test below already draws that line for free. |
| 165 | // |
| 166 | // The old sidebar drawer and the toggle-block are deliberately absent |
| 167 | // from MENUS: neither is a menu, and closing one because a click |
| 168 | // landed elsewhere would fight the user. The topbar's and console's |
| 169 | // narrow Menu IS in, since it became a floating card: an overlay, which |
| 170 | // is what this list is for. It is not in the rst-menus name group, |
| 171 | // which is document-wide; there, opening the account menu inside the |
| 172 | // card would close the card around it. |
| 173 | var MENUS = "[rst-dropdown][open],[rst-menu-group][open],[rst-row-menu][open]"; |
| 174 | MENUS += "," + MENUS.replace(/\[(rst[-\w]+)\]/g, ".$1"); |
| 175 | // Written out rather than derived: the class spelling of rst-shell-menu |
| 176 | // is .rst-shell__menu, which the rewrite above would spell wrong. Only |
| 177 | // in a topbar, or a console whose root names its view: a console |
| 178 | // layout from before the phone index gates its RAIL on this [open], |
| 179 | // and dismissing it there closed the whole navigation on a tap at a |
| 180 | // group label. No :is(), so an older engine still parses the list. |
| 181 | MENUS += ",[rst-shell-topbar] [rst-shell-menu][open],[rst-shell-console~=page] [rst-shell-menu][open],[rst-shell-console~=index] [rst-shell-menu][open]"; |
| 182 | MENUS += ",.rst-shell-topbar .rst-shell__menu[open],.rst-shell-console--page .rst-shell__menu[open],.rst-shell-console--index .rst-shell__menu[open]"; |
| 183 | var TAIL = "[rst-shell-tail],.rst-shell__tail"; |
| 184 | |
| 185 | // menuAround is closest(MENUS) plus one logical parent. The card's |
| 186 | // content (the tail) is the shell menu's next SIBLING, not its child, |
| 187 | // so without this a click on the account menu inside the card would |
| 188 | // close the card, and Escape from a plain nav link in it would find no |
| 189 | // menu at all. Only while the Menu summary is rendered: at 800px and |
| 190 | // up it is display: none, while a <details> opened at 390 and then |
| 191 | // widened keeps [open], and climbing to it would hand focus to a |
| 192 | // summary nobody can see. |
| 193 | function menuAround(node) { |
| 194 | var d = node.closest(MENUS), t, s; |
| 195 | if (d) return d; |
| 196 | t = node.closest(TAIL); |
| 197 | d = t && t.previousElementSibling; |
| 198 | s = d && d.matches(MENUS) && d.querySelector("summary"); |
| 199 | return s && s.getClientRects().length ? d : null; |
| 200 | } |
| 201 | |
| 202 | // except is the clicked node: every menu around it, directly or through |
| 203 | // menuAround's climb, stays open, which is what keeps a click on a menu |
| 204 | // item, or on the summary of a menu being opened right now, from |
| 205 | // closing the thing being used. |
| 206 | function closeMenus(except) { |
| 207 | var keep = [], m; |
| 208 | for (m = except && except.closest && menuAround(except); m; m = m.parentElement && menuAround(m.parentElement)) keep.push(m); |
| 209 | document.querySelectorAll(MENUS).forEach(function (d) { |
| 210 | if (keep.indexOf(d) < 0 && !(except && d.contains(except))) d.open = false; |
| 211 | }); |
| 212 | } |
| 213 | |
| 214 | function dismissMenus(e) { |
| 215 | if (e.type === "click") { closeMenus(e.target); return; } |
| 216 | if (e.key !== "Escape") return; |
| 217 | // Focus is about to be inside a subtree that is no longer rendered, |
| 218 | // which strands a keyboard user at the top of the document. Hand it |
| 219 | // back to the summary that opened the menu. |
| 220 | var el = document.activeElement; |
| 221 | var host = el && el.closest ? menuAround(el) : null; |
| 222 | // Climb to the OUTERMOST open menu around the focus. menuAround |
| 223 | // finds the innermost, which for focus inside a submenu is the |
| 224 | // submenu, and for focus in the account menu inside the card is the |
| 225 | // account menu: their summaries are inside the thing about to close, |
| 226 | // so focusing one would hand focus to something no longer rendered. |
| 227 | while (host && host.parentElement && menuAround(host.parentElement)) { |
| 228 | host = menuAround(host.parentElement); |
| 229 | } |
| 230 | closeMenus(null); |
| 231 | if (host) { |
| 232 | var summary = host.querySelector("summary"); |
| 233 | if (summary) summary.focus(); |
| 234 | } |
| 235 | } |
| 236 | |
| 237 | document.addEventListener("click", dismissMenus, true); |
| 238 | document.addEventListener("keydown", dismissMenus, true); |
| 239 | |
| 240 | // A switch slides. A press on its track that moves 4px drags the knob |
| 241 | // (the CSS reads its share of the travel, --rst-switch-p, and the on |
| 242 | // colour's share, --rst-switch-on, off the track) and on release the |
| 243 | // knob goes to the nearer end (half way is on) with the firm release |
| 244 | // curve, which the CSS keys off data-rst-settle on the label for the |
| 245 | // 0.18s it takes and a little slack; if that end is the other state, |
| 246 | // the checkbox is clicked, so input and change fire as for a tap. A |
| 247 | // press that does not move is the label's, which toggles as it always |
| 248 | // has; after a drag the label's own click is cancelled (never the |
| 249 | // checkbox's, which Space and the drop above send), so nothing |
| 250 | // toggles twice. The checkbox stays the state. |
| 251 | var TRACK = "[rst-switch-track],.rst-switch__track", drag = null, after = null, settling = null, settleT = 0, releasing = false; |
| 252 | function unsettle() { |
| 253 | if (settling) settling.removeAttribute("data-rst-settle"); |
| 254 | settling = null; |
| 255 | clearTimeout(settleT); |
| 256 | } |
| 257 | function settle(l) { |
| 258 | unsettle(); |
| 259 | settling = l; |
| 260 | l.setAttribute("data-rst-settle", ""); |
| 261 | settleT = setTimeout(unsettle, 300); |
| 262 | } |
| 263 | // A toggle while a switch settles takes a toggle's own curve: the |
| 264 | // mark goes on change, bar the release's own click. |
| 265 | document.addEventListener("change", function (e) { if (settling && !releasing && settling.contains(e.target)) unsettle(); }, true); |
| 266 | // One drag at a time: a second finger is ignored until the first |
| 267 | // lifts, and a drag ends (cleaned up, committed only on pointerup) |
| 268 | // however its pointer goes. A press by the same pointer means its |
| 269 | // release was missed, so that drag is over. |
| 270 | document.addEventListener("pointerdown", function (e) { |
| 271 | if (drag && e.pointerId !== drag.id) return; |
| 272 | // A toggle block's head is a switch too; its own input is first. |
| 273 | var t = e.target.closest && e.target.closest(TRACK), l = t && t.closest("[rst-switch],.rst-switch,[rst-tblock-head],.rst-tblock__head"), box = l && l.querySelector("input"); |
| 274 | if (drag) drop({ type: "lost", pointerId: drag.id }); |
| 275 | after = null; |
| 276 | // :disabled, not .disabled: a disabled fieldset disables the box |
| 277 | // without setting its property, and a click on it does nothing. |
| 278 | if (!box || box.matches(":disabled") || e.button) return; |
| 279 | var r = t.getBoundingClientRect(), max = r.width - r.height; |
| 280 | drag = { l: l, t: t, box: box, id: e.pointerId, x: e.clientX, max: max, at: box.checked ? max : 0, pos: -1, |
| 281 | dir: getComputedStyle(t).direction === "rtl" ? -1 : 1 }; |
| 282 | }); |
| 283 | document.addEventListener("pointermove", function (e) { |
| 284 | var g = drag, d; |
| 285 | if (!g || e.pointerId !== g.id) return; |
| 286 | d = (e.clientX - g.x) * g.dir; |
| 287 | if (g.pos < 0) { |
| 288 | if (Math.abs(d) < 4) return; |
| 289 | // A drag on a settling switch takes over: no mark. |
| 290 | if (settling === g.l) unsettle(); |
| 291 | g.l.setAttribute("data-rst-drag", ""); |
| 292 | g.t.setPointerCapture(e.pointerId); |
| 293 | } |
| 294 | g.pos = Math.min(g.max, Math.max(0, g.at + d)); |
| 295 | d = g.pos / g.max; |
| 296 | g.t.style.setProperty("--rst-switch-p", d); |
| 297 | g.t.style.setProperty("--rst-switch-on", d * 100 + "%"); |
| 298 | }); |
| 299 | function drop(e) { |
| 300 | var g = drag; |
| 301 | if (!g || e.pointerId !== g.id) return; |
| 302 | drag = null; |
| 303 | if (g.pos < 0) return; |
| 304 | g.l.removeAttribute("data-rst-drag"); |
| 305 | settle(g.l); |
| 306 | g.t.style.removeProperty("--rst-switch-p"); |
| 307 | g.t.style.removeProperty("--rst-switch-on"); |
| 308 | after = g.l; |
| 309 | releasing = true; |
| 310 | if (e.type === "pointerup" && !g.box.matches(":disabled") && g.pos >= g.max / 2 !== g.box.checked) g.box.click(); |
| 311 | releasing = false; |
| 312 | } |
| 313 | document.addEventListener("pointerup", drop); |
| 314 | document.addEventListener("pointercancel", drop); |
| 315 | document.addEventListener("lostpointercapture", drop); |
| 316 | document.addEventListener("click", function (e) { |
| 317 | if (after && after.contains(e.target) && e.target.tagName !== "INPUT") { |
| 318 | e.preventDefault(); |
| 319 | after = null; |
| 320 | } |
| 321 | }, true); |
| 322 | |
| 323 | // iOS applies :active on a tap only when a touch listener exists. This |
| 324 | // file owns the listener, not light.js, so an app that deletes |
| 325 | // light.js keeps its pressed states. |
| 326 | document.addEventListener("touchstart", function () {}, { passive: true }); |
| 327 | |
| 328 | // The colour-scheme switch's forms ([rst-scheme], POST /_theme) apply |
| 329 | // here instead of round-tripping: data-theme on <html> is what the |
| 330 | // themes read, and the cookie is the server's own (name, path, age, |
| 331 | // SameSite), so the next render paints the same scheme first. System |
| 332 | // is no attribute and no cookie, as on the server. |
| 333 | document.addEventListener("submit", function (e) { |
| 334 | var f = e.target, m = f.closest("[rst-scheme],.rst-scheme"), s = m && f.elements.scheme && f.elements.scheme.value, on = s === "light" || s === "dark"; |
| 335 | if (!s) return; |
| 336 | e.preventDefault(); |
| 337 | if (on) document.documentElement.setAttribute("data-theme", s); else document.documentElement.removeAttribute("data-theme"); |
| 338 | land(); |
| 339 | document.cookie = "rastrillo_scheme=" + (on ? s + "; Max-Age=31536000" : "; Max-Age=0") + "; Path=/; SameSite=Lax" + (location.protocol === "https:" ? "; Secure" : ""); |
| 340 | // Not toggleAttribute: aria-current="" reads as false. |
| 341 | m.querySelectorAll("button").forEach(function (b) { if (b.form === f) b.setAttribute("aria-current", "true"); else b.removeAttribute("aria-current"); }); |
| 342 | m.open = false; |
| 343 | }, true); |
| 344 | |
| 345 | // A scheme change lands in the frame it happens in. The shipped |
| 346 | // tints need no help: at rest nothing fades its background, and a |
| 347 | // hovered row's, tile's or rail item's tint rides a registered |
| 348 | // percentage, so a change of scheme re-resolves its colour at once. |
| 349 | // What this lands is everything else still running: an app's own |
| 350 | // colour transitions, or a switch track mid-toggle, which a change |
| 351 | // of scheme would otherwise retarget while the text changes at |
| 352 | // once. getAnimations() flushes style, which starts the transitions, |
| 353 | // and cancelling one lands it on its end value. Transitions only, |
| 354 | // told by transitionProperty: cancelling an animation would stop a |
| 355 | // spinner for good. |
| 356 | function land() { |
| 357 | if (!document.getAnimations) return; |
| 358 | document.getAnimations().forEach(function (a) { if (typeof a.transitionProperty === "string") a.cancel(); }); |
| 359 | } |
| 360 | |
| 361 | // The OS flipping under a page on System is the same change with no |
| 362 | // click: light-dark() repaints with no script involved. The change |
| 363 | // event reaches script a frame after the style update that started |
| 364 | // the fade, so this lands it a frame late rather than 200ms late. |
| 365 | var osScheme = window.matchMedia && matchMedia("(prefers-color-scheme: dark)"); |
| 366 | if (osScheme) osScheme.onchange = function () { if (!document.documentElement.hasAttribute("data-theme")) land(); }; |
| 367 | |
| 368 | function scan() { |
| 369 | document.querySelectorAll("[data-poll]").forEach(poll); |
| 370 | } |
| 371 | |
| 372 | // A prerendered page runs this before anyone is looking at it, and |
| 373 | // may never be shown: polling there would fetch on a timer, or hold an |
| 374 | // EventSource open, for a page the reader only hovered a link to. It |
| 375 | // starts when the page is activated instead. |
| 376 | function start() { |
| 377 | if (document.prerendering) document.addEventListener("prerenderingchange", scan, { once: true }); |
| 378 | else scan(); |
| 379 | } |
| 380 | |
| 381 | if (document.readyState === "loading") { |
| 382 | document.addEventListener("DOMContentLoaded", start); |
| 383 | } else { |
| 384 | start(); |
| 385 | } |
| 386 | })(); |
| 387 | |