oficina / fichas Public

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

Plain git — no account needed to clone.

Download

Download this file

1/* busy.js — the busy rule. First-party, dependency-free, and on by
2 default: link it and every submit button in every form that goes
3 somewhere is covered, with no attribute to remember, because a button
4 that changes something should say so while it works, and a form that
5 double-submits on a second click is a bug on every screen. It is
6 app-owned from the moment it is vendored; leave it unlinked to opt the
7 whole app out.
8
9 What a submitted button does: its label gives way to a spinner (the
10 label stays, beside the spinner, under reduced motion or forced
11 colours — tokens.css), it goes aria-busy and then disabled, and its
12 form refuses a second submit. When depends on the method, the
13 submitter's formmethod beating the form's:
14
15 POST the spinner shows at once and for at least HOLD_MS: a
16 response faster than that is held back until then, so a
17 quick save reads as a deliberate beat rather than a flicker.
18 A save changes something, and the beat says it happened.
19 GET the submit goes at once, and the button shows nothing
20 unless the page is still here SHOW_AFTER_MS later. A GET
21 only looks something up (a search, a filter, a view):
22 holding it made every look slower for a spinner nobody
23 needed, and one that flashes on its way out is a glitch.
24 The form refuses a second submit from the start.
25
26 Going Back to the page hands every busy form back. A submit still
27 being held when the page is left is dropped rather than sent
28 later, and a GET's spinner still waiting is never shown. Left means
29 a navigation has started, not that it has finished. A form pow.js
30 protects is pow's to hold: this file arms only pow's re-send and
31 never holds it.
32
33 Vocabulary:
34 data-busy="false" on a <form> or on one submit button: opt OUT
35 of the busy rule. The rule is the default, so
36 any other value — data-busy on its own
37 included — changes nothing
38 data-busy-label="…" on the form or on the button: replacement
39 button text while it works
40 data-live-form on a <form>: live.js's to send, and to show
41 busy, whenever it claims the submit (marking
42 the event e.liveForm); this file arms it only
43 when live.js lets it go natively
44
45 A script that handles a submit itself (a fetch, say) cancels it in a
46 listener on the form or the document, as it would anyway: those run
47 before this file's window listener, which then sees the cancelled
48 submit and leaves it — and its feedback — to that script. Two edges
49 of the hold, on purpose: a handler that stops the submit event's
50 propagation keeps it from the window, so that submit goes at once,
51 unheld; and a form removed from the page during the hold (a polled
52 fragment replacing it) takes its held submit with it. */
53(function () {
54 "use strict";
55
56 // How long a POST's spinner shows, at least. Long enough to read as
57 // an answer to the click, short enough never to feel like waiting.
58 var HOLD_MS = 650;
59
60 // How long a GET may take before its button says it is working.
61 // Under half a second a click and its answer read as one event; past
62 // it, a still button reads as a missed click.
63 var SHOW_AFTER_MS = 500;
64
65 // ── The busy rule ────────────────────────────────────────────────
66 //
67 // A button that CHANGES something says so while it works; a button
68 // that only reveals something — a disclosure, a dropdown, a tab —
69 // does not. So every submit button in every form is covered by
70 // default, with no attribute to remember: the submitted button gets
71 // aria-busy, a spinner and — once the submission is under way —
72 // disabled, and its form gets aria-busy and a guard against a second
73 // submit. The data-busy vocabulary above opts out of either half.
74 //
75 // The guard is the substance, the spinner is the manners, and neither
76 // is a promise: with scripts off the form submits exactly as it
77 // always did, twice if the visitor clicks twice. Idempotency stays
78 // the server's job. One delegated capture-phase listener, for the
79 // reasons light dismiss gives below: fragments, and never double-bind.
80 //
81 // Two traps this shape exists to avoid:
82 //
83 // - A form the browser REFUSED must not sit there looking busy.
84 // Constraint validation fails before the submit event is fired at
85 // all, so an invalid form never reaches this code; a cancelled
86 // one is handed back in the tick below. (formnovalidate skips
87 // validation and really does submit, which should look like it.)
88 // - Nothing that could change the payload happens while the payload
89 // is being read. The entry list is built before submit fires, but
90 // engines have differed, so aria-busy, the spinner and a
91 // <button>'s TEXT (never submitted — a button submits its value
92 // attribute) go on synchronously, while disabled and an
93 // <input type="submit">'s value (which IS what it submits) wait.
94 //
95 // Every busy element in the DOCUMENT, then the ownership test: a
96 // form="id" submit button is owned by a form it does not live in.
97 function busyOff(form) {
98 clearTimeout(reveals.get(form));
99 reveals.delete(form);
100 form.removeAttribute("aria-busy");
101 document.querySelectorAll('[aria-busy="true"]').forEach(function (b) {
102 if (b.form !== form && !form.contains(b)) return;
103 b.disabled = false;
104 b.removeAttribute("aria-busy");
105 var spin = b.querySelector("[rst-spin]");
106 if (spin) spin.remove();
107 var idle = b.getAttribute("data-idle-label");
108 if (idle === null) return;
109 if (b.tagName === "INPUT") { b.value = idle; } else { b.textContent = idle; }
110 b.removeAttribute("data-idle-label");
111 });
112 }
113
114 function busySubmit(e, late) {
115 var form = e.target;
116 if (!form || form.tagName !== "FORM") return;
117 // A swapping form is live.js's whenever live.js claims it: arming it
118 // here too would hand it back a tick after live.js cancels the
119 // submit, clearing live.js's busy state mid-request. Whether this
120 // capture listener runs before live.js's is down to script order, so
121 // it is armed late, from the window listener, and only if live.js
122 // did not claim it (e.liveForm, set in live.js's capture listener)
123 // and nobody cancelled it. One live.js leaves to the browser (a GET,
124 // another origin, a page live.js is not running on) keeps the rule.
125 if (form.hasAttribute("data-live-form") && !late) return;
126 // pow.js owns every submit of a form it protects: it cancels it,
127 // shows its own busy state (this file's vocabulary) while it waits,
128 // and re-sends it marked data-pow-released. Arming here before that
129 // would hand the form back a tick later and wipe pow's feedback, and
130 // a guard armed here would refuse pow's re-send. Arm on the re-send
131 // only.
132 if (form.hasAttribute("data-pow-form") && !form.hasAttribute("data-pow-released")) return;
133 if (form.getAttribute("data-busy") === "false") return;
134 // The button the browser submitted with: the one clicked, or — for
135 // Enter in a field — the default one it implicitly clicked. Only
136 // that one goes busy; every other submit button in the form keeps
137 // its name and its value. An engine with no SubmitEvent.submitter
138 // leaves the buttons alone and keeps the guard, which is the half
139 // that matters.
140 var btn = e.submitter;
141 // A form that opens its result elsewhere, or a submit that closes a
142 // dialog and stays put, has nothing to be busy about and nothing to
143 // clear. The submitter's formmethod beats the form's.
144 //
145 // getAttribute, never the IDL properties. A form is
146 // [LegacyOverrideBuiltIns]: a control named "target" or "method" (a
147 // target date, a method column — ordinary field names) shadows the IDL
148 // attribute with the input itself, so the property form quietly
149 // switches the rule off and hands back the double submit. The busy flag
150 // below is the form's own aria-busy for the same reason: an expando is
151 // shadowable, and under strict mode assigning to a shadowed one throws.
152 var to = (btn && btn.getAttribute("formtarget")) || form.getAttribute("target");
153 if (to && to !== "_self") return;
154 var method = btn && btn.getAttribute("formmethod") || form.getAttribute("method");
155 if (/^dialog$/i.test(method)) return;
156 if (form === releasing) return; // the hold sending the submit it held
157 if (form.getAttribute("aria-busy") === "true") { e.preventDefault(); return; }
158 form.setAttribute("aria-busy", "true");
159 if (!btn || btn.getAttribute("data-busy") === "false") btn = null;
160 // Anything but post is a GET: a missing method, and one HTML does
161 // not know, both submit as one. Its button waits for the reveal, and
162 // with no busy button the hold below leaves its submit alone.
163 var label = btn && (btn.getAttribute("data-busy-label") ||
164 form.getAttribute("data-busy-label"));
165 if (!/^post$/i.test(method || "")) {
166 if (btn) reveals.set(form, setTimeout(function () { reveal(form, btn, label); }, SHOW_AFTER_MS));
167 setTimeout(function () {
168 // Cancelled downstream, as below: hand the form back, and
169 // cancel the reveal with it.
170 if (e.defaultPrevented) busyOff(form);
171 }, 0);
172 return;
173 }
174 if (btn) dress(btn, label);
175 setTimeout(function () {
176 // Someone downstream cancelled the submit — an app handler doing
177 // the work itself, most likely. Nothing is on its way anywhere,
178 // so hand the form back, guard included, and let whoever took the
179 // job own the feedback too.
180 if (e.defaultPrevented && !held.has(e)) { busyOff(form); return; }
181 if (btn) harden(btn, label);
182 }, 0);
183 }
184
185 // The half of the busy state that cannot touch the payload. The
186 // spinner is a child element, not a pseudo-element, so busyOff can
187 // take it away again. An <input type="submit"> has no children,
188 // which is the one shape this cannot draw a spinner on. tokens.css
189 // stops it rotating under reduced motion.
190 function dress(btn, label) {
191 btn.setAttribute("aria-busy", "true");
192 if (btn.tagName !== "BUTTON") return;
193 if (label) {
194 btn.setAttribute("data-idle-label", btn.textContent);
195 btn.textContent = label;
196 }
197 var spin = document.createElement("span");
198 spin.setAttribute("rst-spin", "");
199 spin.setAttribute("aria-hidden", "true");
200 btn.insertBefore(spin, btn.firstChild);
201 }
202
203 // The half that can: a disabled button drops its name and value, and
204 // an <input type="submit">'s value is what it submits.
205 function harden(btn, label) {
206 if (label && btn.tagName === "INPUT") {
207 btn.setAttribute("data-idle-label", btn.value);
208 btn.value = label;
209 }
210 btn.disabled = true;
211 }
212
213 document.addEventListener("submit", busySubmit, true);
214
215 // ── The reveal ───────────────────────────────────────────────────
216 //
217 // A GET's page is still here SHOW_AFTER_MS after the click, so the
218 // answer is slow, and the button says so now: the busy state a POST
219 // shows at once. Nothing here can change the payload any more; the
220 // entry list was built long ago. A button that has left its form
221 // meanwhile (a polled fragment replacing it, a form= changed) is not
222 // the one working, and busyOff would never find it to hand it back.
223 var reveals = new Map(); // form -> the timer that will reveal its button
224 function reveal(form, btn, label) {
225 reveals.delete(form);
226 if (form.getAttribute("aria-busy") !== "true") return;
227 if (!btn.isConnected || btn.form !== form) return;
228 dress(btn, label);
229 harden(btn, label);
230 }
231
232 // Every reveal still waiting is dropped. Not on beforeunload: a GET's
233 // own navigation fires it, and a slow one is exactly when to show.
234 function dropReveals() {
235 reveals.forEach(function (timer) { clearTimeout(timer); });
236 reveals.clear();
237 }
238
239 // ── The hold ─────────────────────────────────────────────────────
240 //
241 // A spinner can only be promised a minimum time by holding the
242 // submit itself: once a fast response arrives the browser navigates
243 // and the spinner is gone. So the submit the busy rule just armed is
244 // cancelled here and sent again, by requestSubmit, once HOLD_MS have
245 // passed since the click.
246 //
247 // This listener is on the window, in the bubble phase — the last place
248 // a submit event reaches — so every handler on the form and the
249 // document has had its say first. One that cancelled the submit owns
250 // it (e.defaultPrevented, and the busy tick above hands the form
251 // back); so does the guard's own refusal of a second submit. Only a
252 // submit nobody else stopped is held, and only if the busy rule armed
253 // it (aria-busy on the form: not opted out, not a dialog, not a new
254 // window) and a button is showing the spinner.
255 var held = new WeakSet(); // submit events this listener cancelled
256 var pending = new Map(); // form -> timer, for a hold still running
257 var releasing = null; // the form whose held submit is going now
258 window.addEventListener("submit", function (e) {
259 var form = e.target;
260 if (!form || form.tagName !== "FORM") return;
261 if (form === releasing) { releasing = null; return; }
262 if (form.hasAttribute("data-live-form")) {
263 if (e.defaultPrevented || e.liveForm) return;
264 busySubmit(e, true);
265 }
266 // Never hold a pow form: pow has already held it while it solved,
267 // and a second hold is a second wait for nothing. Worse, holding it
268 // here and re-sending later would send it back through pow, which
269 // would hold it again with busy.js's guard still armed, and the form
270 // could never submit.
271 if (form.hasAttribute("data-pow-form")) return;
272 if (e.defaultPrevented || form.getAttribute("aria-busy") !== "true") return;
273 // Only a submit with a spinner to show is held: the hold is for the
274 // spinner. A script's requestSubmit() with no submitter, or a button
275 // that opted out, has nothing on screen to keep up, and holding it
276 // would only be a silent 650ms stall. The form is still guarded.
277 var btn = e.submitter || null;
278 if (!btn || btn.getAttribute("aria-busy") !== "true") return;
279 e.preventDefault();
280 held.add(e);
281 pending.set(form, setTimeout(function () { release(form, btn); }, HOLD_MS));
282 // pagehide fires only once a navigation commits, and a slow
283 // destination leaves the hold running until then: a held submit
284 // released meanwhile replaces the navigation the visitor chose.
285 // beforeunload fires as the navigation starts. Attached only while
286 // something is held, so it keeps no page out of the back-forward
287 // cache.
288 if (pending.size === 1) window.addEventListener("beforeunload", dropHeld);
289 });
290
291 // Send the held submit. The submitter goes with it, so its name and
292 // value are in the payload exactly as a click would have sent them —
293 // which means, for the moment the entry list is built, it has to be
294 // enabled and an <input type="submit"> has to carry its own value
295 // again, not the busy label. The form is re-checked first: fields
296 // stay editable during the hold, and a form that is no longer valid
297 // must be handed back with its errors showing, not left spinning.
298 function release(form, btn) {
299 pending.delete(form);
300 if (pending.size === 0) window.removeEventListener("beforeunload", dropHeld);
301 if (!form.isConnected) return;
302 var skip = form.hasAttribute("novalidate") ||
303 (btn && btn.hasAttribute("formnovalidate"));
304 if (!skip && !form.checkValidity()) {
305 busyOff(form);
306 form.reportValidity();
307 return;
308 }
309 // The submitter may have left the form during the hold (moved,
310 // removed, its form= changed): requestSubmit would throw and leave
311 // the form guarded for good. Hand it back instead.
312 if (btn && (!btn.isConnected || btn.form !== form)) {
313 busyOff(form);
314 return;
315 }
316 var busyValue = null;
317 // Restored, not assumed: a button that opted out of the busy state
318 // (data-busy="false") was never disabled, and must not end up so.
319 var wasDisabled = btn ? btn.disabled : false;
320 if (btn) {
321 btn.disabled = false;
322 var idle = btn.getAttribute("data-idle-label");
323 if (btn.tagName === "INPUT" && idle !== null) {
324 busyValue = btn.value;
325 btn.value = idle;
326 }
327 }
328 releasing = form;
329 try {
330 form.requestSubmit(btn || undefined);
331 } finally {
332 releasing = null;
333 if (btn) {
334 btn.disabled = wasDisabled;
335 if (busyValue !== null) btn.value = busyValue;
336 }
337 }
338 }
339
340 // A navigation started while a submit was held: drop every held
341 // submit and hand the forms back, so a navigation that is then
342 // cancelled (a download, a beforeunload prompt) leaves no form
343 // spinning.
344 function dropHeld() {
345 pending.forEach(function (timer, form) {
346 clearTimeout(timer);
347 busyOff(form);
348 });
349 pending.clear();
350 window.removeEventListener("beforeunload", dropHeld);
351 }
352
353 // Leaving the page — a link, Back — while a submit is held drops it:
354 // the visitor has gone somewhere else, and a timer surviving into the
355 // back/forward cache would otherwise send it on their return, or
356 // dress a form they walked away from as busy.
357 window.addEventListener("pagehide", function () { dropHeld(); dropReveals(); });
358
359 // The back/forward cache restores a page's DOM exactly as it was left
360 // — busy buttons still disabled, still wearing the busy label and the
361 // spinner — so a visitor who navigates back finds a dead form. Hand
362 // every busy form back.
363 window.addEventListener("pageshow", function (e) {
364 if (!e.persisted) return;
365 document.querySelectorAll("form[aria-busy]").forEach(busyOff);
366 dropReveals();
367 });
368})();
369