Jobley / website / assets / forms.js
| 1 | // The board moderator form posts JSON to its data-api endpoint and shows field messages next |
| 2 | // to the fields, and swaps to the confirmation when it is stored. Cloudflare Turnstile loads only |
| 3 | // when the API reports a site key (appearance "interaction-only", so most people never see it). |
| 4 | // The hidden "website" field is the honeypot: people never see it, and the API ignores any |
| 5 | // submission that fills it. |
| 6 | (function () { |
| 7 | var form = document.querySelector('form[data-api]'); |
| 8 | if (!form) return; |
| 9 | var status = form.querySelector('.form-status'); |
| 10 | var submit = form.querySelector('button[type="submit"]'); |
| 11 | var done = document.querySelector('[data-done]'); |
| 12 | var widget = form.querySelector('.turnstile'); |
| 13 | var siteKey = null, widgetId = null, token = ''; |
| 14 | |
| 15 | // Field choices come from the API so the form and the apps always agree. |
| 16 | fetch('/api/meta', { headers: { accept: 'application/json' } }) |
| 17 | .then(function (r) { if (!r.ok) throw new Error(); return r.json(); }) |
| 18 | .then(function (m) { |
| 19 | form.querySelectorAll('select[data-options]').forEach(function (sel) { |
| 20 | var map = m[sel.dataset.options] || {}; |
| 21 | var keys = Array.isArray(map) ? map : Object.keys(map); |
| 22 | keys.forEach(function (k) { |
| 23 | var o = document.createElement('option'); |
| 24 | o.value = k; o.textContent = Array.isArray(map) ? (k === 'hour' ? 'an ' : 'a ') + k : map[k]; |
| 25 | if (sel.dataset.default === k) o.selected = true; |
| 26 | sel.appendChild(o); |
| 27 | }); |
| 28 | }); |
| 29 | siteKey = m.turnstile_site_key; |
| 30 | if (siteKey && widget) loadTurnstile(); |
| 31 | }) |
| 32 | .catch(function () { say('We couldn’t reach the server just now. You can still fill this in; try sending again in a moment.'); }); |
| 33 | |
| 34 | function loadTurnstile() { |
| 35 | window.onAppTurnstile = function () { |
| 36 | widgetId = window.turnstile.render(widget, { |
| 37 | sitekey: siteKey, appearance: 'interaction-only', |
| 38 | callback: function (t) { token = t; }, |
| 39 | 'expired-callback': function () { token = ''; }, |
| 40 | 'error-callback': function () { token = ''; } |
| 41 | }); |
| 42 | }; |
| 43 | var s = document.createElement('script'); |
| 44 | s.src = 'https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit&onload=onAppTurnstile'; |
| 45 | s.async = true; s.defer = true; |
| 46 | document.head.appendChild(s); |
| 47 | } |
| 48 | |
| 49 | function say(text) { status.textContent = text || ''; } |
| 50 | function clearErrors() { |
| 51 | form.querySelectorAll('.error').forEach(function (e) { e.textContent = ''; }); |
| 52 | form.querySelectorAll('[aria-invalid]').forEach(function (e) { e.removeAttribute('aria-invalid'); }); |
| 53 | } |
| 54 | function collect() { |
| 55 | var body = {}; |
| 56 | Array.prototype.forEach.call(form.elements, function (el) { |
| 57 | if (!el.name) return; |
| 58 | if (el.type === 'checkbox') body[el.name] = el.checked; |
| 59 | else if (el.dataset.kind === 'int') { if (el.value.trim() !== '') body[el.name] = /^\d+$/.test(el.value.trim().replace(/[,\s]/g, '')) ? Number(el.value.trim().replace(/[,\s]/g, '')) : el.value.trim(); } |
| 60 | else if (el.dataset.kind === 'links') body[el.name] = el.value.split(/\s+/).filter(Boolean); |
| 61 | else if (el.value.trim() !== '') body[el.name] = el.value; |
| 62 | }); |
| 63 | if (token) body.turnstile_token = token; |
| 64 | return body; |
| 65 | } |
| 66 | form.addEventListener('submit', function (e) { |
| 67 | e.preventDefault(); |
| 68 | clearErrors(); say(''); |
| 69 | var missing = null; |
| 70 | [['name', 'Please add your name.'], ['email', 'Please add a valid email.'], ['message', 'Please write a short message.']].forEach(function (pair) { |
| 71 | var el = form.elements[pair[0]]; |
| 72 | if (!el || missing) return; |
| 73 | var v = el.value.trim(); |
| 74 | var bad = !v || (pair[0] === 'email' && !/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(v)); |
| 75 | if (bad) { missing = el; var slot = form.querySelector('[data-error="' + pair[0] + '"]'); if (slot) slot.textContent = pair[1]; el.setAttribute('aria-invalid', 'true'); say(pair[1]); } |
| 76 | }); |
| 77 | if (missing) { missing.focus(); return; } |
| 78 | if (siteKey && !token) { say('One moment: we’re checking you’re a person. Please try again in a few seconds.'); return; } |
| 79 | submit.disabled = true; |
| 80 | var label = submit.textContent; |
| 81 | submit.textContent = 'Sending…'; |
| 82 | fetch(form.dataset.api, { method: 'POST', headers: { 'content-type': 'application/json', accept: 'application/json' }, body: JSON.stringify(collect()) }) |
| 83 | .then(function (r) { return r.json().then(function (d) { return { status: r.status, data: d }; }); }) |
| 84 | .then(function (res) { |
| 85 | if (res.data && res.data.ok) return finish(res.data); |
| 86 | if (res.status === 422 && res.data.fields) { |
| 87 | var first = null; |
| 88 | Object.keys(res.data.fields).forEach(function (name) { |
| 89 | var el = form.elements[name]; |
| 90 | var slot = form.querySelector('[data-error="' + name + '"]'); |
| 91 | if (slot) slot.textContent = res.data.fields[name]; |
| 92 | if (el && el.setAttribute) { el.setAttribute('aria-invalid', 'true'); first = first || el; } |
| 93 | }); |
| 94 | say('Please fix the marked fields.'); |
| 95 | if (first && first.focus) first.focus(); |
| 96 | } else { |
| 97 | say((res.data && res.data.message) || 'Something went wrong. Please try again.'); |
| 98 | } |
| 99 | if (window.turnstile && widgetId !== null) { token = ''; window.turnstile.reset(widgetId); } |
| 100 | }) |
| 101 | .catch(function () { say('We couldn’t reach the server. Your answers are still here; please try again.'); }) |
| 102 | .then(function () { submit.disabled = false; submit.textContent = label; }); |
| 103 | }); |
| 104 | |
| 105 | function finish(data) { |
| 106 | form.hidden = true; |
| 107 | var ref = done.querySelector('[data-ref]'); |
| 108 | if (ref && data.id) ref.textContent = data.id; |
| 109 | done.hidden = false; |
| 110 | done.setAttribute('tabindex', '-1'); |
| 111 | done.focus(); |
| 112 | done.scrollIntoView({ block: 'start' }); |
| 113 | } |
| 114 | })(); |