oficina / fichas Public

Clone
git clone https://amadan.net/oficina/fichas

Plain git — no account needed to clone.

Download

Download this file

1/* live.js — live regions. First-party, dependency-free, and inert unless
2 the page has the rastrillo-live meta and a data-live region. With
3 scripts off a live page is an ordinary page, current when loaded.
4 App-owned once scaffolded: edit it like any other static file.
5
6 It answers: which parts of this page are out of date, and how do they
7 become current without disturbing the person using them? The stream
8 says which topics moved, never what changed; the page fetches its own
9 regions again, from its own URL, as its own viewer.
10
11 Vocabulary:
12 <meta name="rastrillo-live" content="PATH" data-paused="TEXT"
13 data-unconfirmed="TEXT">
14 the stream, the note shown when it stops, and
15 the note for a form whose outcome is unknown
16 data-live="T@V …" on a region with an id: its topics, each at the
17 version it was rendered from
18 data-live-boot="B" the server process that rendered it
19 data-live-stale set here on a region left alone while being
20 edited; it is fetched when the editing ends
21 id="notice" the role="status" notice: its contents change
22 in place, the element is never replaced
23 data-live-form="R …" on a <form>: sent with fetch, asking for its
24 own region (its closest data-live), regions R
25 and the notice, and swapping in the answer
26
27 One EventSource per page, GET PATH?carlos_hold=1&boot=B&t=T@V&t=T@V,
28 each topic at the lowest version a region holds. carlos_hold=1 asks
29 a CARLOS edge to hold the stream while the instance sleeps, so an
30 open page never keeps it awake; the edge strips it, and a server
31 elsewhere ignores it. On a change event, each region
32 showing an older version is fetched with Rastrillo-Fragment: <id>,
33 and replaced by the answer's element (listed in Rastrillo-Regions).
34 A 204 with Rastrillo-Location navigates to the URL the answer came
35 from, which keeps a locale prefix the header's path has lost; the
36 header's path is used only when the browser reports no URL.
37
38 The rules (a form's answer skips the edit check for the form's own
39 region only, since that holds what was just sent):
40 - This file owns reconnecting: an error closes the EventSource, so
41 the browser's own retry never runs beside this one, and it reopens
42 after 1s, doubling to a minute. Only a stream open 30s resets the
43 delay: one that ends as it opens (an edge over its cap) waits
44 longer each time.
45 - One fetch in flight per region, one change queued behind it, and
46 an answer, a 204 too, applies only if it is from the fetch the
47 region started last, before any pagehide.
48 - Just before a swap, the region must be on the page and not being
49 edited (holding the focused field, or a field changed from its
50 default). A stream's navigation waits while anything on the page
51 is, or a form's request is out.
52 - Focus moves to the focused element's replacement, else to the
53 region itself (tabindex="-1"); never to <body>.
54 - A failed fetch is retried after 1s, 2s, 4s; then, as when the
55 stream has been down 10s, an empty notice shows the paused note.
56 It clears once the stream is open and no region's fetches are
57 failing.
58 - Hidden a minute, the stream closes until shown. pagehide closes it
59 and abandons fetches; a back/forward restore reopens it from the
60 regions' versions. A prerendered page starts once shown.
61
62 A swapping form is sent as the browser would send it (the submitter
63 and its form* overrides too), plus Rastrillo-Page; one with a target,
64 a GET, another origin or text/plain is left to the browser. Its
65 submitter shows busy.js's busy state (busy.js leaves these forms
66 here) for at least 650ms, a second submit is refused, and its
67 regions' stream fetches wait. A 204 navigates; regions swap in (on
68 400 or 422 focus goes to the first [aria-invalid="true"]); a whole
69 page replaces this one, shown as text unless it is text/html. No
70 answer, a 5xx or an empty Rastrillo-Regions is an unknown outcome:
71 the input stays, the notice says data-unconfirmed, the regions are
72 fetched again, and nothing is resent. It is sent a tick after the
73 submit, once every handler has run (a window one added after this
74 file's too), so one that cancels it (a confirm, its own fetch) wins
75 and nothing is sent.
76 Unlike a native submit, a whole page from a redirect replaces the
77 form page's history entry (Back skips it), and one answered directly
78 (a 4xx, say) keeps the form page's URL. */
79(function () {
80 "use strict";
81
82 var NOTICE = "notice";
83 var SKIP = /^(button|submit|reset|image|hidden)$/;
84 var meta = null;
85 var src = null; // the EventSource
86 var up = false; // src is open
87 var following = ""; // the topics src follows
88 var wait = 1000; // the next reconnect's delay
89 var reconnect = 0, down = 0, hidden = 0, steady = 0; // timers
90 var ctl = null; // aborts this run's fetches; null while stopped
91 var seq = 0; // fetches started on this page
92 var paused = false;
93 // Per region id. Region names are the server's, but "constructor" is
94 // a valid one, so nothing here may inherit from Object.
95 var regions = Object.create(null);
96
97 // rastrillo.js's guard, as sessions.SafeReturn: anything laxer is an
98 // open redirect. Browsers strip tab/CR/LF before parsing, so
99 // "/\t/evil.example" would be scheme-relative.
100 function localPath(to) {
101 return to.charAt(0) === "/" && to.charAt(1) !== "/" &&
102 to.indexOf("\\") === -1 && !/[\u0000-\u001f\u007f]/.test(to);
103 }
104
105 // leaveFor is where a live 204 sends the page: the URL the answer came
106 // from (after any redirect), or "" to stay. The header names that same
107 // page, but under a locale prefix the server has stripped it, and
108 // following it would drop the reader's language. Only a browser that
109 // reports no URL falls back to the header, which must be local.
110 function leaveFor(res) {
111 var to = res.headers.get("Rastrillo-Location"), u = res.url;
112 if (!u) return to && localPath(to) ? to : "";
113 try { return new URL(u).origin === location.origin ? u : ""; } catch (x) { return ""; }
114 }
115
116 function state(name) {
117 return regions[name] || (regions[name] = {
118 last: 0, busy: false, queued: false, stale: false, tries: 0, retry: 0, failed: false, forms: 0
119 });
120 }
121
122 function token(s) {
123 var at = s.lastIndexOf("@");
124 return at > 0 ? { topic: s.slice(0, at), v: Number(s.slice(at + 1)), raw: s } : null;
125 }
126
127 function tokens(el) {
128 return (el.getAttribute("data-live") || "").split(" ").map(token).filter(Boolean);
129 }
130
131 // The notice is never fetched as a live region: a fragment request
132 // naming it takes the flash, and a background refresh would eat a
133 // message nobody saw.
134 function live() {
135 return Array.prototype.filter.call(document.querySelectorAll("[data-live]"), function (el) {
136 return el.id && el.id !== NOTICE;
137 });
138 }
139
140 // Each topic once, at the lowest version a region holds: that region
141 // is still owed a fetch. Regions from two boots (one swapped in after
142 // a restart) send no boot, which the server reads as "all changed",
143 // rather than one boot's versions as the other's.
144 function subscription() {
145 var low = Object.create(null), order = [], boot = null;
146 live().forEach(function (el) {
147 var b = el.getAttribute("data-live-boot") || "";
148 boot = boot === null || boot === b ? b : "";
149 tokens(el).forEach(function (t) {
150 if (!low[t.topic]) order.push(t.topic);
151 if (!low[t.topic] || t.v < low[t.topic].v) low[t.topic] = t;
152 });
153 });
154 return {
155 boot: boot || "",
156 topics: order.join(" "),
157 query: order.map(function (k) { return "&t=" + encodeURIComponent(low[k].raw); }).join("")
158 };
159 }
160
161 function open() {
162 clearTimeout(reconnect);
163 reconnect = 0;
164 var sub = subscription();
165 if (!sub.topics) return;
166 var path = meta.getAttribute("content") || "";
167 var es = new EventSource(path + (path.indexOf("?") < 0 ? "?" : "&") +
168 "carlos_hold=1&boot=" + encodeURIComponent(sub.boot) + sub.query);
169 src = es;
170 following = sub.topics;
171 es.addEventListener("open", function () {
172 if (src !== es) return;
173 up = true;
174 steady = setTimeout(function () { wait = 1000; }, 30000);
175 clearTimeout(down);
176 down = 0;
177 unpause();
178 });
179 es.addEventListener("change", changed);
180 // EventSource hides the status, so a refused topic, a full server
181 // and a dropped connection all look alike: back off and retry.
182 es.addEventListener("error", function () {
183 if (src !== es) return;
184 close();
185 reconnect = setTimeout(open, wait);
186 wait = Math.min(wait * 2, 60000);
187 if (!down) down = setTimeout(pause, 10000);
188 });
189 }
190
191 function close() {
192 if (src) { src.close(); src = null; }
193 up = false;
194 clearTimeout(steady);
195 steady = 0;
196 }
197
198 function changed(e) {
199 var t = token(e.data || "");
200 if (!t) return;
201 var boot = (e.lastEventId || "").split(" ")[0];
202 live().forEach(function (el) {
203 var mine = tokens(el).filter(function (x) { return x.topic === t.topic; })[0];
204 // Already showing this version (the page's own form fetch landed
205 // first) costs nothing. Another boot's number says nothing about
206 // this region.
207 if (!mine || (el.getAttribute("data-live-boot") === boot && mine.v >= t.v)) return;
208 refresh(el.id);
209 });
210 }
211
212 function refresh(name) {
213 var st = state(name), el = document.getElementById(name), run = ctl;
214 if (!run || !el) return;
215 // Behind a form's fetch too: started later, this one would drop the
216 // form's answer.
217 if (st.busy || st.forms) { st.queued = true; return; }
218 if (editing(el)) { stale(el); return; }
219 clearTimeout(st.retry);
220 st.busy = true;
221 send(location.pathname + location.search, [name], {}, null).then(function () {
222 if (run !== ctl) return; // abandoned on pagehide
223 st.busy = st.failed = false;
224 st.tries = 0;
225 unpause();
226 if (st.queued) { st.queued = false; refresh(name); }
227 }, function () {
228 if (run !== ctl) return;
229 // The retry fetches the latest, so a queued change rides on it.
230 st.busy = st.queued = false;
231 // Retries are ordinary requests; they must not run forever.
232 if (++st.tries > 3) { st.failed = true; pause(); return; }
233 st.retry = setTimeout(function () { refresh(name); }, 1000 << (st.tries - 1));
234 });
235 }
236
237 // send fetches regions and applies the answer: the one way anything
238 // reaches the page, so the forms below get ordering, focus and the
239 // notice rule from it (init's headers a plain object or Headers; init
240 // is not changed). Every region named counts this fetch as the last it
241 // started, so whatever it had in flight is superseded. mine is the
242 // submitted form's own region ("" for none), or null for a stream
243 // fetch: only mine skips the edit check, since a form's answer must
244 // swap the form, which holds what was just sent and often the focus.
245 // Another target's draft was not sent, and is left as a stream would
246 // leave it. The swap waits for hold, a form's minimum busy time. A
247 // non-answer rejects with the Response as res.
248 function send(url, names, init, mine, hold) {
249 var id = ++seq, run = ctl, opts = {}, k, stream = mine === null;
250 if (!run) return Promise.reject(new Error("live.js is stopped"));
251 names.forEach(function (n) { state(n).last = id; });
252 for (k in init) opts[k] = init[k];
253 opts.headers = new Headers(opts.headers || {});
254 opts.headers.set("Rastrillo-Fragment", names.join(" "));
255 opts.signal = run.signal;
256 // Past the HTTP cache: its lock makes a GET wait for any other GET
257 // of the same URL still out, so no fetch could overtake a slow one.
258 opts.cache = "no-store";
259 return fetch(url, opts).then(function (res) {
260 var to = res.headers.get("Rastrillo-Location");
261 if (res.status === 204 && to) {
262 // An old answer, as for a swap: a newer fetch for these regions
263 // decides, and a page hidden since has moved on.
264 if (run !== ctl || names.some(function (n) { return state(n).last !== id; })) return res;
265 // Leaving discards whatever is typed anywhere on the page, or a
266 // form's request still out, and a background change can wait
267 // until that is sent and answered.
268 if (stream && (out.length || editing(document.body))) {
269 names.forEach(function (n) {
270 var el = document.getElementById(n);
271 if (el) { state(n).leave = true; stale(el); }
272 });
273 } else if (leaveFor(res)) location.assign(res.left = leaveFor(res));
274 return res;
275 }
276 // Only an answer that names its regions is one. A signed-out
277 // redirect ends on a whole sign-in page, whose notice would
278 // otherwise be swapped into this one.
279 var held = res.headers.get("Rastrillo-Regions");
280 if (held === null) {
281 var err = new Error("not a region answer: " + res.status);
282 err.res = res;
283 throw err;
284 }
285 held = held.split(" ");
286 return Promise.all([res.text(), hold]).then(function (r) {
287 if (run === ctl) apply(r[0], names.filter(function (n) { return held.indexOf(n) >= 0; }), id, mine);
288 return res;
289 });
290 });
291 }
292
293 function apply(html, names, id, mine) {
294 var tpl = document.createElement("template");
295 tpl.innerHTML = html;
296 Array.prototype.slice.call(tpl.content.children).forEach(function (next) {
297 var name = next.id, old = document.getElementById(name);
298 if (names.indexOf(name) < 0 || state(name).last !== id || !old) return;
299 if (name === NOTICE) {
300 // In place: a role="status" element that is replaced is a new
301 // live region, and screen readers announce nothing in it.
302 if (old.innerHTML !== next.innerHTML) old.innerHTML = next.innerHTML;
303 paused = false;
304 return;
305 }
306 if (name !== mine && editing(old)) { stale(old); return; }
307 swap(old, next);
308 });
309 // A swap can change what the page follows (a keyed topic for a new
310 // row); a stream left on the old set would never hear of it.
311 if (src && subscription().topics !== following) { close(); open(); }
312 }
313
314 function swap(old, next) {
315 var focused = document.activeElement, inside = !!focused && old.contains(focused);
316 // The notice inside a region: the new one is from a render that did
317 // not take the flash, so it is empty. Keep the element, and what it
318 // is saying.
319 var notice = document.getElementById(NOTICE), slot = notice && old.contains(notice) && find(next, NOTICE);
320 if (slot) slot.replaceWith(notice);
321 old.replaceWith(next);
322 state(next.id).stale = false;
323 if (inside) land(next, focused !== old && focused.id);
324 }
325
326 function land(region, id) {
327 var to = id ? find(region, id) : null;
328 if (to) to.focus({ preventScroll: true });
329 if (!to || document.activeElement !== to) {
330 region.setAttribute("tabindex", "-1");
331 region.focus({ preventScroll: true });
332 }
333 }
334
335 // Ids are arbitrary strings; comparing them avoids building a
336 // selector that would need escaping.
337 function find(root, id) {
338 if (root.id === id) return root;
339 var all = root.querySelectorAll("[id]");
340 for (var i = 0; i < all.length; i++) if (all[i].id === id) return all[i];
341 return null;
342 }
343
344 function editing(el) {
345 var a = document.activeElement;
346 if (a && a !== el && el.contains(a) && (a.isContentEditable ||
347 /^(INPUT|TEXTAREA|SELECT)$/.test(a.tagName) && !SKIP.test(a.type))) return true;
348 return Array.prototype.some.call(el.querySelectorAll("input,textarea,select"), unsent);
349 }
350
351 function unsent(c) {
352 var o = c.options, picked = false, i;
353 if (SKIP.test(c.type)) return false;
354 if (c.type === "file") return c.files.length > 0;
355 if (c.type === "checkbox" || c.type === "radio") return c.checked !== c.defaultChecked;
356 if (!o) return c.value !== c.defaultValue;
357 for (i = 0; i < o.length; i++) if (o[i].defaultSelected) picked = true;
358 // With no option marked selected the browser shows the first (none,
359 // in a list box). That is the default, not an edit.
360 if (!picked) return c.selectedIndex > (c.multiple || c.size > 1 ? -1 : 0);
361 for (i = 0; i < o.length; i++) if (o[i].selected !== o[i].defaultSelected) return true;
362 return false;
363 }
364
365 function stale(el) {
366 state(el.id).stale = true;
367 el.setAttribute("data-live-stale", "");
368 }
369
370 // Read once focus has landed: during focusout it is still on its way.
371 // A region held back from navigating waits on the whole page.
372 function edited() {
373 for (var name in regions) {
374 var st = regions[name], el = st.stale && document.getElementById(name);
375 if (el && !editing(st.leave ? document.body : el)) { st.stale = st.leave = false; refresh(name); }
376 }
377 }
378
379 // Not over a flash: it is what someone is reading, and unpause clears
380 // only the paused note, so the flash would be lost for good.
381 function pause() {
382 var n = document.getElementById(NOTICE), text = meta.getAttribute("data-paused");
383 if (!n || !text || n.textContent.trim() && n.textContent !== text) return;
384 n.textContent = text;
385 paused = true;
386 }
387
388 // The note is true until the stream is open and no region's fetches
389 // are failing; either alone can still mean updates are not arriving.
390 // Only our own words are cleared: a flash that arrived since stays.
391 function unpause() {
392 var n = document.getElementById(NOTICE);
393 if (!paused || !up) return;
394 for (var name in regions) if (regions[name].failed) return;
395 if (n && n.textContent === meta.getAttribute("data-paused")) n.textContent = "";
396 paused = false;
397 }
398
399 // The stream and its timers, for a hidden tab. Fetches already out may
400 // still land.
401 function quiet() {
402 close();
403 clearTimeout(reconnect);
404 clearTimeout(down);
405 reconnect = down = 0;
406 }
407
408 function hide() {
409 if (!hidden) hidden = setTimeout(function () { hidden = 0; quiet(); }, 60000);
410 }
411
412 // pagehide: everything, at once. An answer to a fetch from before the
413 // page was cached must not land after the ones fetched on its return,
414 // and an open stream or fetch keeps a page out of the cache.
415 function stop() {
416 quiet();
417 clearTimeout(hidden);
418 hidden = 0;
419 if (ctl) ctl.abort();
420 ctl = null;
421 for (var name in regions) {
422 clearTimeout(regions[name].retry);
423 regions[name].busy = regions[name].queued = false;
424 }
425 }
426
427 // Forms that swap.
428
429 var HOLD_MS = 650; // busy.js's: a quick answer reads as a beat
430 var out = []; // [form, submitter] of each form showing busy
431
432 // Whether this file sends e's form: read at both ends of the dispatch,
433 // since a handler in between may change the form.
434 function plan(e) {
435 var form = e.target, btn = e.submitter || null, to, type, url;
436 if (!ctl || !window.fetch || !form || form.tagName !== "FORM" || !form.hasAttribute("data-live-form")) return null;
437 // getAttribute: a control named "action" or "method" shadows the
438 // form's own properties.
439 function attr(n) {
440 return btn && btn.hasAttribute("form" + n) ? btn.getAttribute("form" + n) : form.getAttribute(n);
441 }
442 to = attr("target");
443 type = (attr("enctype") || "").toLowerCase();
444 try { url = new URL(attr("action") || location.href, document.baseURI); } catch (x) { return null; }
445 if (to && to !== "_self" || !/^post$/i.test(attr("method") || "") ||
446 url.origin !== location.origin || type === "text/plain") return null;
447 return { form: form, btn: btn, url: url, type: type };
448 }
449
450 // Capture: claim the submit (or refuse a second), but send nothing.
451 // Every other handler runs after this one, and one that cancels (a
452 // confirm, its own fetch, pow.js holding its form) must win: the
453 // browser sends nothing for a cancelled submit. e.liveForm tells
454 // busy.js's window listener, in either order, that the form is ours.
455 function claim(e) {
456 if (e.defaultPrevented || !plan(e)) return;
457 if (e.target.getAttribute("aria-busy") === "true") e.preventDefault();
458 else e.liveForm = true;
459 }
460
461 // Window, bubble: the last listener the submit reaches, but for window
462 // listeners added after this file's. One of those (a confirm) may still
463 // cancel, so the native submit is stopped here and the send waits a
464 // tick: their preventDefault or returnValue = false is recorded, and
465 // both read as if this one had not cancelled, until then. A
466 // window.onsubmit set later that returns false is not seen: the browser
467 // records that itself, and the submit is already cancelled.
468 function submitted(e) {
469 var p = !e.defaultPrevented && e.liveForm && plan(e), run = ctl, form, btn, type, url, body, data, later = false, cancel = e.preventDefault;
470 if (!p) return;
471 form = p.form;
472 btn = p.btn;
473 type = p.type;
474 url = p.url;
475 // Before anything is cancelled or disabled: if this throws the
476 // browser still sends the form.
477 body = data = new FormData(form, btn || undefined);
478 if (type !== "multipart/form-data") {
479 body = new URLSearchParams();
480 // A file goes as its name, as the browser sends it urlencoded.
481 data.forEach(function (v, k) { body.append(k, typeof v === "string" ? v : v.name); });
482 }
483 cancel.call(e);
484 e.preventDefault = function () { later = true; cancel.call(e); };
485 Object.defineProperties(e, {
486 defaultPrevented: { get: function () { return later; } },
487 returnValue: { get: function () { return !later; }, set: function (v) { if (!v) e.preventDefault(); } }
488 });
489
490 var own = form.closest("[data-live]"), names = [], entry = [form, btn], settled = false;
491 var had = own && own.contains(document.activeElement) ? document.activeElement : null;
492 ((own ? own.id : "") + " " + form.getAttribute("data-live-form") + " " + NOTICE).split(/\s+/).forEach(function (n) {
493 if (n && names.indexOf(n) < 0) names.push(n);
494 });
495 var hold = new Promise(function (r) { setTimeout(r, HOLD_MS); });
496 // Busy at once: it is what refuses a second submit in this task.
497 busy(form, btn);
498 out.push(entry);
499 // A cancel hands the form back, and lets go a stream navigation
500 // held while it was out: nothing else would resume it.
501 setTimeout(function () {
502 if (!later) return go();
503 release(entry);
504 edited();
505 }, 0);
506
507 // Lets the regions' queued stream fetches go. keep leaves the busy
508 // state up for a navigation, as a native submit's stays up until
509 // the next page.
510 function settle(keep) {
511 if (settled) return;
512 settled = true;
513 if (!keep) release(entry);
514 names.forEach(function (n) {
515 var st = state(n);
516 if (--st.forms || !st.queued) return;
517 st.queued = false;
518 refresh(n);
519 });
520 // A region held back while this was out goes now. A removed
521 // focused element fires no focusout, so one waiting for the
522 // editing to end would wait for the next one.
523 if (!keep) edited();
524 }
525
526 // Not a failure: the POST may have committed and only the redirected
527 // GET failed. Resending could write twice.
528 function unknown() {
529 var n = document.getElementById(NOTICE), text = meta.getAttribute("data-unconfirmed");
530 names.forEach(function (x) { if (x !== NOTICE) state(x).queued = true; });
531 settle();
532 if (run === ctl && n && text) n.textContent = text;
533 }
534
535 function go() {
536 names.forEach(function (n) { state(n).forms++; });
537 send(url.href, names, { method: "POST", body: body, headers: { "Rastrillo-Page": location.pathname } }, own ? own.id : "", hold).then(function (res) {
538 // res.left says send navigated. It may not have: a later form,
539 // which asks for the notice too, superseded this one. Then the
540 // form is handed back, or it would count as out for good.
541 if (res.status === 204) return settle(!!res.left);
542 if (run !== ctl) return settle();
543 if (!res.headers.get("Rastrillo-Regions")) return unknown();
544 settle();
545 var now = own && own.id && document.getElementById(own.id), a = document.activeElement, bad;
546 // Disabling the focused submitter dropped focus to <body>, so the
547 // swap had none to carry over.
548 if (had && now && now !== own && (!a || a === document.body)) land(now, had.id);
549 if (res.status === 400 || res.status === 422) {
550 bad = (now || form).querySelector('[aria-invalid="true"]');
551 if (bad) bad.focus();
552 }
553 }, function (err) {
554 var res = err && err.res;
555 if (run !== ctl || res && res.status === 204) return settle(); // a 204 stays put
556 if (!res || res.status >= 500) return hold.then(unknown);
557 return Promise.all([res.text(), hold]).then(function (r) {
558 whole(r[0], res);
559 settle();
560 }, unknown);
561 });
562 }
563 }
564
565 // As the browser would have shown it. The stream and fetches stop
566 // first: the document is replaced, but this closure lives on. Only
567 // text/html is written as markup: an http.Error is text/plain, often
568 // holding the request's own words, and parsed it would run as HTML.
569 function whole(body, res) {
570 var html = /^text\/html\s*(;|$)/i.test(res.headers.get("Content-Type") || "");
571 stop();
572 if (res.redirected) history.replaceState(null, "", res.url);
573 document.open();
574 document.write(html ? body : "<pre>");
575 document.close();
576 if (!html) document.querySelector("pre").textContent = body;
577 }
578
579 // busy.js's look. disabled waits a tick, as busy.js's does, so other
580 // submit listeners in this dispatch see the submitter as clicked.
581 function busy(form, btn) {
582 form.setAttribute("aria-busy", "true");
583 if (!btn || btn.getAttribute("data-busy") === "false" || form.getAttribute("data-busy") === "false") return;
584 var label = btn.getAttribute("data-busy-label") || form.getAttribute("data-busy-label");
585 var k = btn.tagName === "INPUT" ? "value" : "textContent", spin = document.createElement("span");
586 btn.setAttribute("aria-busy", "true");
587 if (label) {
588 btn.setAttribute("data-idle-label", btn[k]);
589 btn[k] = label;
590 }
591 if (k !== "value") {
592 spin.setAttribute("rst-spin", "");
593 spin.setAttribute("aria-hidden", "true");
594 btn.insertBefore(spin, btn.firstChild);
595 }
596 setTimeout(function () { if (btn.getAttribute("aria-busy") === "true") btn.disabled = true; }, 0);
597 }
598
599 function release(entry) {
600 var i = out.indexOf(entry), form = entry[0], btn = entry[1], spin, idle;
601 if (i < 0) return;
602 out.splice(i, 1);
603 form.removeAttribute("aria-busy");
604 if (!btn || btn.getAttribute("aria-busy") !== "true") return;
605 spin = btn.querySelector("[rst-spin]");
606 idle = btn.getAttribute("data-idle-label");
607 btn.disabled = false;
608 btn.removeAttribute("aria-busy");
609 if (spin) spin.remove();
610 if (idle !== null) btn[btn.tagName === "INPUT" ? "value" : "textContent"] = idle;
611 btn.removeAttribute("data-idle-label");
612 }
613
614 // Regions whose fetches gave up get a fresh start when shown again.
615 function revive() {
616 for (var name in regions) {
617 if (regions[name].failed) { regions[name].failed = false; regions[name].tries = 0; refresh(name); }
618 }
619 }
620
621 // Revives too: a back/forward restore can fire visibilitychange
622 // before pageshow, while ctl is still null and that listener does
623 // nothing.
624 function run() {
625 ctl = new AbortController();
626 wait = 1000;
627 open();
628 revive();
629 if (document.visibilityState === "hidden") hide();
630 }
631
632 function start() {
633 meta = document.querySelector('meta[name="rastrillo-live"]');
634 if (!meta || !window.EventSource || !window.AbortController || !document.querySelector("[data-live]")) return;
635 document.addEventListener("focusout", function () { setTimeout(edited, 0); });
636 document.addEventListener("visibilitychange", function () {
637 if (!ctl) return;
638 if (document.visibilityState === "hidden") { hide(); return; }
639 clearTimeout(hidden);
640 hidden = 0;
641 if (!src && !reconnect) open();
642 revive();
643 });
644 document.addEventListener("submit", claim, true);
645 addEventListener("submit", submitted);
646 addEventListener("pagehide", stop);
647 addEventListener("pageshow", function (e) {
648 if (!e.persisted) return;
649 // Restored as it was left: a form that navigated still looks busy.
650 out.slice().forEach(release);
651 if (!ctl) run();
652 });
653 run();
654 }
655
656 // A prerendered page may never be shown: holding a stream open for a
657 // page someone only hovered a link to costs the server a connection.
658 function begin() {
659 if (document.prerendering) document.addEventListener("prerenderingchange", start, { once: true });
660 else start();
661 }
662
663 // The seam, for Node and for test pages that define module (as
664 // select.js exports its pure half). A browser page has no module.
665 if (typeof module !== "undefined" && module && module.exports) module.exports.send = send;
666
667 if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", begin);
668 else begin();
669})();
670