Files
gabrielvidal 549f41c3c2 security(web,store,form): harden form UI, uploads, markdown, CSS branding and webhooks
- Preserve immutable data-secret on secret fields so revealed secrets never enter draft storage
- Sniff chunked uploads across initial chunks and block HTML/SVG disguised as text/* or .json
- Cap markdown blockquote recursion, brand CSS depth, image thumbnail dimensions, and spec defaults
- Confine brand CSS asset paths via symlink evaluation and decode CSS escapes against @import/url()
- Restrict webhooks to https:// or loopback/private/Tailscale http:// with redirects disabled
- Fix Store.Delete Wait wakeup, Store.Secret ID validation, and WebRTC/meta-refresh widget hardening
2026-11-23 11:32:50 +01:00

1131 lines
51 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// ask-form answer page — progressive enhancement. The page works without it;
// this adds group paging (on a phone; a desktop shows every group and tracks
// them in the section list), "Other…" niceties, a local draft, the server's
// checks then a confirm step, a fullscreen viewer for pictures and mockups,
// auto-sized html blocks, a fade on a wide table's edges, and the touches a
// print needs (app.css draws it).
(function () {
"use strict";
var root = document.documentElement;
root.classList.add("js");
function $all(sel, el) { return Array.prototype.slice.call((el || document).querySelectorAll(sel)); }
function make(tag, cls, text) {
var e = document.createElement(tag);
if (cls) e.className = cls;
if (text != null) e.textContent = text;
return e;
}
// The page's language: <html data-l10n> is the machine's translation of the
// English strings below (internal/i18n), none on an English page.
var l10n = {};
try { l10n = JSON.parse(root.getAttribute("data-l10n") || "{}"); } catch (e) { /* English */ }
function tr(s, vars) {
s = l10n[s] || s;
for (var k in vars || {}) s = s.split("{" + k + "}").join(vars[k]);
return s;
}
var store = {
get: function (k) { try { return JSON.parse(localStorage.getItem(k) || "null"); } catch (e) { return null; } },
set: function (k, v) { try { localStorage.setItem(k, JSON.stringify(v)); } catch (e) { /* private mode */ } },
del: function (k) { try { localStorage.removeItem(k); } catch (e) { /* ignore */ } }
};
function clearFormStorage(fid) {
if (!fid) return;
store.del("ask-form:draft:" + fid);
var pref = "ask-form:files:" + fid + ":";
try {
for (var i = localStorage.length - 1; i >= 0; i--) {
var k = localStorage.key(i);
if (k && k.indexOf(pref) === 0) localStorage.removeItem(k);
}
} catch (e) { /* ignore */ }
}
// A closed page: the answers went through, the draft and file refs can go.
var closed = document.querySelector("[data-closed]");
if (closed) clearFormStorage(closed.getAttribute("data-closed"));
// In a frame (serve --embed-origins): a site the machine allows — an agent
// hub opening the form over its conversation — hears which page is showing
// (the form, or the page once it went through: the hub closes the frame
// then) and may send its theme tokens, so the form wears the hub's look.
// <html data-embed> lists the allowed origins only on a framed load, and
// frame-ancestors has already made sure the parent is one of them.
var embedders = (root.getAttribute("data-embed") || "").split(" ").filter(Boolean);
if (embedders.length && window.parent !== window) {
// A message page ("Not sent", "Page expired"…) is a main.closed too, but
// only a closed form's own pages carry data-closed.
var main = document.querySelector("main[data-closed]");
var kind = document.getElementById("form") ? "form"
: !main ? "message"
: main.classList.contains("answers") ? "answers" : "closed";
var info = {
type: "ask-form:page", page: kind,
id: (location.pathname.match(/^\/(?:f|forms)\/([^/]+)/) || [])[1] || "",
status: kind === "form" ? "pending" : (main && main.getAttribute("data-status")) || ""
};
embedders.forEach(function (o) {
try { window.parent.postMessage(info, o); } catch (e) { /* not this origin */ }
});
// Only colour tokens and lengths (H S% L%, 0.65rem, #rrggbb): nothing
// that can load a file or reach past the custom property it names.
var TOKEN = /^--[a-z][a-z0-9-]{0,40}$/, VALUE = /^[\w\s.%#,-]{1,80}$/;
window.addEventListener("message", function (e) {
var d = e.data;
if (e.source !== window.parent || embedders.indexOf(e.origin) < 0 || !d || d.type !== "ask-form:theme") return;
var tokens = d.tokens && typeof d.tokens === "object" ? d.tokens : {};
Object.keys(tokens).forEach(function (k) {
if (TOKEN.test(k) && typeof tokens[k] === "string" && VALUE.test(tokens[k])) root.style.setProperty(k, tokens[k]);
});
if (d.scheme === "dark" || d.scheme === "light") {
root.style.colorScheme = d.scheme;
root.setAttribute("data-scheme", d.scheme);
}
tellFrames();
});
}
// What is behind each frame: the colour the page paints there and its
// colour scheme, which a frame keeps (Chromium paints the canvas of a frame
// whose scheme differs opaque). The frame takes the palette of that side
// and draws a mockup written for a light page on a light sheet of its own
// when the page is dark (frameScript, internal/server/frame.go). Told when a
// frame reports in, and again when the hub's theme or the OS's changes.
function rgba(s) {
var m = /^rgba?\(([^)]*)\)$/.exec(s || ""), v;
if (!m) return null;
v = m[1].split(/[\s,\/]+/).map(Number);
return v.length > 2 && v.length < 5 && v.every(isFinite) ? [v[0], v[1], v[2], v.length > 3 ? v[3] : 1] : null;
}
function usedScheme(el) {
var cs = getComputedStyle(el).colorScheme || "", dk = /dark/.test(cs), lt = /light/.test(cs);
var os = false;
try { os = matchMedia("(prefers-color-scheme: dark)").matches; } catch (e) { /* none */ }
return dk && (!lt || os) ? "dark" : "light";
}
function backdrop(f) {
var layers = [], el, c, k, base = usedScheme(root) === "dark" ? [18, 18, 18] : [255, 255, 255];
for (el = f; el && el.nodeType === 1; el = el.parentElement) {
c = rgba(getComputedStyle(el).backgroundColor);
if (c && c[3] > 0) { layers.push(c); if (c[3] >= 1) break; }
}
while (layers.length) {
c = layers.pop(); k = c[3];
base = [c[0] * k + base[0] * (1 - k), c[1] * k + base[1] * (1 - k), c[2] * k + base[2] * (1 - k)];
}
return "rgb(" + base.map(Math.round).join(", ") + ")";
}
function tellFrame(f) {
try {
if (f.contentWindow) f.contentWindow.postMessage({ type: "ask-form:backdrop", color: backdrop(f), scheme: usedScheme(f) }, "*");
} catch (e) { /* gone */ }
}
function tellFrames() { $all("iframe").forEach(tellFrame); }
// A frame that loaded before this script ran has reported its size to no
// one: told now, or once it loads, it reports again.
$all("iframe").forEach(function (f) { f.addEventListener("load", function () { tellFrame(f); }); });
tellFrames();
try {
var osDark = matchMedia("(prefers-color-scheme: dark)");
if (osDark.addEventListener) osDark.addEventListener("change", tellFrames);
else if (osDark.addListener) osDark.addListener(tellFrames);
} catch (e) { /* no media queries */ }
// Frame documents report their size. An html block without a fixed height
// follows its height (and keeps the one it takes on paper for printing); a
// mockup reports the size it is drawn at, which a
// card that fits its content takes as its ratio and the fullscreen view
// as its shape (the frame then scales the mockup to fill either).
window.addEventListener("message", function (e) {
var d = e.data;
if (!d || d.type !== "ask-form:frame" || typeof d.h !== "number") return;
$all("iframe").forEach(function (f) { if (f.contentWindow === e.source) tellFrame(f); });
$all("iframe.frame.autosize").forEach(function (f) {
if (f.contentWindow !== e.source) return;
f.style.height = frameHeight(d.h);
if (d.p > 0) f.setAttribute("data-print-h", frameHeight(d.p));
});
if (!(d.w > 0 && d.h > 0)) return;
$all(".fit-content .mock iframe, .overlay iframe").forEach(function (f) {
if (f.contentWindow !== e.source) return;
f.setAttribute("data-w", d.w);
f.setAttribute("data-h", d.h);
if (d.fluid) f.setAttribute("data-fluid", "");
if (f.closest(".overlay")) fitOverlay(f);
else f.parentNode.style.aspectRatio = d.w + " / " + d.h;
});
});
// Printing: collapsed blocks open, and html blocks take the height they
// have on paper, for as long as the print lasts.
var opened = [];
window.addEventListener("beforeprint", function () {
$all("img[loading=lazy], iframe[loading=lazy]").forEach(function (el) { el.loading = "eager"; });
$all("details.block-details:not([open])").forEach(function (d) { d.open = true; opened.push(d); });
$all("iframe.frame.autosize[data-print-h]").forEach(function (f) {
f.setAttribute("data-screen-h", f.style.height);
f.style.height = f.getAttribute("data-print-h");
});
});
window.addEventListener("afterprint", function () {
opened.forEach(function (d) { d.open = false; });
opened = [];
$all("iframe.frame.autosize[data-screen-h]").forEach(function (f) {
f.style.height = f.getAttribute("data-screen-h");
f.removeAttribute("data-screen-h");
});
});
function frameHeight(h) { return Math.max(40, Math.min(4000, Math.ceil(h) + 2)) + "px"; }
// Pictures and mockups further down load once the page has settled: one
// still waiting for its turn would print blank.
window.addEventListener("load", function () {
setTimeout(function () {
$all("img[loading=lazy], iframe[loading=lazy]").forEach(function (el) { el.loading = "eager"; });
}, 1500);
});
// A table wider than its column scrolls sideways; a fade on the side with
// more of it says so (a phone shows no scrollbar until you scroll).
$all(".md .table").forEach(function (box) {
function edges() {
var more = box.scrollWidth - box.clientWidth - box.scrollLeft;
box.classList.toggle("fade-l", box.scrollLeft > 1);
box.classList.toggle("fade-r", more > 1);
}
box.addEventListener("scroll", edges, { passive: true });
if (window.ResizeObserver) new ResizeObserver(edges).observe(box);
else window.addEventListener("resize", edges);
edges();
});
var form = document.getElementById("form");
if (!form) { setupZoom(); return; }
var id = form.getAttribute("data-form");
var draftKey = "ask-form:draft:" + id;
var hadErrors = form.hasAttribute("data-errors");
form.noValidate = true; // validation happens below, page-aware
var fields = $all(".field", form).filter(function (f) {
return !f.classList.contains("is-display");
});
// Every block and question in the spec's order (the page groups them, which
// can reorder them): conditions look back along this order.
var allFields = $all(".field", form).sort(function (a, b) { return Number(a.id.slice(1)) - Number(b.id.slice(1)); });
var byKey = Object.create(null);
allFields.forEach(function (f) { byKey[f.getAttribute("data-key")] = f; });
var touched = {};
// ── values ────────────────────────────────────────────────────────────────
function inputs(f) { return $all("input, select, textarea", f); }
function otherInput(f) { return f.querySelector("[data-other-for]"); }
// The names of the files attached to the field's text (upload.js lists them).
function attached(f) {
return $all(".attach .file-item.done .file-name", f).map(function (n) { return n.textContent; });
}
// A text box follows its content (up to its CSS max-height).
function grow(ta) {
if (!ta.offsetParent) return; // out of sight: measured once it shows
ta.style.height = "auto";
ta.style.height = Math.min(ta.scrollHeight + 2, 600) + "px";
}
// The text of an "Other…" answer: typed, or the names of the files alone.
function otherText(f) {
var o = otherInput(f);
if (!o || !otherPicked(f)) return "";
return o.value.trim() || attached(f).join(", ");
}
// Tick "Other…": its own box next to a single choice, or (a page from an
// older machine) the choice itself, which replaces the option picked.
function pickOther(f) {
inputs(f).forEach(function (i) {
if (i.value === "__other__" && (i.type === "radio" || i.type === "checkbox")) i.checked = true;
if (i.tagName === "SELECT" && i.querySelector('option[value="__other__"]')) i.value = "__other__";
});
}
function otherPicked(f) {
return inputs(f).some(function (i) {
return (i.value === "__other__" && i.checked) || (i.tagName === "SELECT" && i.value === "__other__");
});
}
function isEmpty(f) {
var t = f.getAttribute("data-type");
var els = inputs(f);
if (t === "checkbox" || t === "slider") return false;
if (t === "list" || t === "daterange") return !els.some(function (i) { return i.value.trim() !== ""; });
if (t === "radio" || t === "rating" || t === "multiselect" || (t === "select" && f.classList.contains("visual-field"))) {
var picked = els.filter(function (i) { return (i.type === "radio" || i.type === "checkbox") && i.checked && i.value !== "__other__"; });
if (picked.length) return false;
return !otherText(f);
}
if (t === "select") {
var s = f.querySelector("select");
if (s && s.value && s.value !== "__other__") return false;
return !otherText(f);
}
var main = els[0];
return !main || !(main.value.trim() || attached(f).length);
}
function unanswered(f) {
if (f.closest(".catchall") || f.hidden) return false;
var t = f.getAttribute("data-type");
if (t === "checkbox" || t === "slider") return !touched[f.getAttribute("data-key")];
return isEmpty(f);
}
// What the server would turn down (form.Parse, same messages), so a send
// never opens the confirm step only to come back with errors: "" = fine.
function problem(f) {
var t = f.getAttribute("data-type");
if (f.hidden) return "";
if (f.hasAttribute("data-uploading")) return tr("Wait for the upload to finish.");
if (t === "checkbox" || t === "slider") return "";
var main = f.querySelector("input:not([type=hidden]):not([data-other-for]), textarea");
// A half-typed number or date reads as "": the browser knows better.
if (main && main.validity && main.validity.badInput) return tr(t === "date" ? "Enter a date (YYYY-MM-DD)." : "Enter a number.");
if (isEmpty(f)) {
if (!f.hasAttribute("data-required")) return "";
if (otherPicked(f)) return tr("Type your answer next to “Other…”.");
if (t === "widget") return tr("Interact with this first.");
return tr(t === "multiselect" ? "Pick at least one." : "This question is required.");
}
if (t === "daterange") {
var dr = inputs(f).map(function (i) { return i.value; });
if (!dr[0] || !dr[1]) return tr("Pick both dates.");
return dr[1] < dr[0] ? tr("The end is before the start.") : "";
}
if (t === "list") {
var need = Number(f.querySelector("[data-list]").getAttribute("data-min") || 0);
return need && filledRows(f) < need ? tr("Add at least {n}.", { n: need }) : "";
}
var v = main ? main.value.trim() : "";
if (t === "number") {
var n = Number(v.replace(",", "."));
if (!isFinite(n)) return tr("Enter a number.");
var min = main.getAttribute("min"), max = main.getAttribute("max");
if (min && n < Number(min)) return tr("At least {n}.", { n: min });
if (max && n > Number(max)) return tr("At most {n}.", { n: max });
}
if (t === "date" && !/^\d{4}-\d{2}-\d{2}$/.test(v)) return tr("Enter a date (YYYY-MM-DD).");
if (t === "email" && !validEmail(v.toLowerCase())) return tr("Enter an email address, like name@example.com.");
if (t === "secret" && v.length > 8000) return tr("That value is too long.");
return "";
}
// form.ValidEmail: one @, something before it, a dotted domain of letters,
// digits and dashes after it, no spaces.
function validEmail(s) {
if (s.length > 254 || /[\s<>(),;:"\[\]\\]/.test(s)) return false;
var at = s.indexOf("@");
var local = s.slice(0, at), domain = s.slice(at + 1);
if (at < 1 || local.length > 64 || domain.indexOf("@") >= 0 || domain.indexOf(".") < 0) return false;
return domain.split(".").every(function (l) {
return l.length > 0 && l.length <= 63 && l[0] !== "-" && l[l.length - 1] !== "-" && /^(?:[a-z0-9-]|[^\x00-\x7f])+$/.test(l);
});
}
// ── lists: rows of inputs, a row more or less ─────────────────────────────
function listBlank(row) { return $all("input, select", row).every(function (i) { return !i.value.trim(); }); }
function filledRows(f) { return $all(".list-row", f).filter(function (r) { return !listBlank(r); }).length; }
function clearRow(row) { $all("input, select", row).forEach(function (i) { i.value = ""; }); }
function syncAdd(list) {
var add = list.parentNode.querySelector(".list-add");
if (add) add.disabled = $all(".list-row", list).length >= Number(list.getAttribute("data-max") || 50);
}
function bindRow(list, row) {
$all(".row-remove", row).forEach(function (b) { b.remove(); });
var rm = make("button", "row-remove", "✕");
rm.type = "button";
rm.setAttribute("aria-label", tr("Remove this row"));
rm.addEventListener("click", function () {
if ($all(".list-row", list).length > 1) row.remove(); else clearRow(row);
syncAdd(list);
list.closest(".field").dispatchEvent(new Event("input", { bubbles: true }));
});
row.appendChild(rm);
}
function addRow(list) {
var rows = $all(".list-row", list);
if (rows.length >= Number(list.getAttribute("data-max") || 50)) return null;
var row = rows[rows.length - 1].cloneNode(true);
clearRow(row);
list.appendChild(row);
bindRow(list, row);
syncAdd(list);
return row;
}
function setupList(list) {
var rows = $all(".list-row", list);
// Without a script the page offers a few blank rows; with one, a row more
// is a tap away, so the blank ones beyond what is needed go.
var keep = Math.max(1, Number(list.getAttribute("data-min") || 0));
while (rows.length > keep && listBlank(rows[rows.length - 1])) rows.pop().remove();
$all(".list-row", list).forEach(function (r) { bindRow(list, r); });
var add = make("button", "list-add", "+ Add");
add.type = "button";
add.addEventListener("click", function () {
var row = addRow(list);
var first = row && row.querySelector("input, select");
if (first) first.focus();
list.closest(".field").dispatchEvent(new Event("input", { bubbles: true }));
});
list.after(add);
syncAdd(list);
// Enter in a cell goes to the next row (adding one) instead of sending.
list.addEventListener("keydown", function (e) {
if (e.key !== "Enter" || !e.target.matches("input")) return;
e.preventDefault();
var all = $all(".list-row", list), at = all.indexOf(e.target.closest(".list-row"));
var next = all[at + 1] || (listBlank(all[at]) ? null : addRow(list));
var el = next && next.querySelector("input, select");
if (el) el.focus();
});
}
$all("[data-list]", form).forEach(setupList);
// ── draft (never a secret, even while revealed via "Show") ───────────────
function isSecretInput(i) {
return i.type === "password" || i.hasAttribute("data-secret") || !!i.closest('[data-type="secret"]');
}
function saveDraft() {
var v = {};
$all("input, select, textarea", form).forEach(function (i) {
if (!/^[foa]\./.test(i.name) || isSecretInput(i)) return;
var had = v[i.name];
if (typeof had === "string") had = had ? [had] : []; // a dropdown before its Other… box
if (i.type === "radio" || i.type === "checkbox") {
if (i.checked) (v[i.name] = had || []).push(i.value);
else v[i.name] = had || [];
} else if (i.closest("[data-list]")) (v[i.name] = had || []).push(i.value);
else if (had) { if (i.value) had.unshift(i.value); v[i.name] = had; }
else v[i.name] = i.value;
});
store.set(draftKey, { v: v, t: touched, seen: seen, at: Date.now() });
}
var seen = {};
var draft = store.get(draftKey);
if (draft && !hadErrors) {
$all("input, select, textarea", form).forEach(function (i) {
if (!(i.name in draft.v) || isSecretInput(i)) return;
var val = draft.v[i.name];
if (i.type === "radio" || i.type === "checkbox") i.checked = Array.isArray(val) && val.indexOf(i.value) >= 0;
else if (typeof val === "string") i.value = val;
else if (i.tagName === "SELECT" && Array.isArray(val) && !i.closest("[data-list]")) {
// A dropdown kept next to its Other… box: the option among the values.
var opt = val.filter(function (x) {
return x !== "__other__" && Array.prototype.some.call(i.options, function (o) { return o.value === x; });
})[0];
i.value = opt || "";
}
});
// A list comes back with as many rows as it had.
$all("[data-list]", form).forEach(function (list) {
var names = $all("input, select", $all(".list-row", list)[0]).map(function (i) { return i.name; });
var arrs = names.map(function (n) { return draft.v[n]; }).filter(Array.isArray);
if (!arrs.length) return;
var n = Math.max(1, Math.max.apply(null, arrs.map(function (a) { return a.length; })));
var rows = $all(".list-row", list);
while (rows.length < n && addRow(list)) rows = $all(".list-row", list);
while (rows.length > n) rows.pop().remove();
rows.forEach(function (row, ri) {
$all("input, select", row).forEach(function (i) {
var a = draft.v[i.name];
i.value = Array.isArray(a) && a[ri] != null ? a[ri] : "";
});
});
syncAdd(list);
});
touched = draft.t || {};
}
if (draft && draft.seen) seen = draft.seen;
// A note to decline with, or files for it, kept in the draft: its section
// opens on them.
var declineNote = form.querySelector(".decline-note");
if (declineNote && $all("textarea, input[data-refs]", declineNote).some(function (i) { return i.value.trim(); })) {
declineNote.closest("details").open = true;
}
// ── per-field behaviour ─────────────────────────────────────────────────
fields.forEach(function (f) {
var key = f.getAttribute("data-key");
var t = f.getAttribute("data-type");
var o = otherInput(f);
if (o) {
// Typing next to "Other…" picks it.
o.addEventListener("input", function () {
if (!o.value.trim()) return;
pickOther(f);
});
inputs(f).forEach(function (i) {
if (i.value === "__other__" || i.tagName === "SELECT") {
i.addEventListener("change", function () {
if (i.tagName === "SELECT" ? i.value !== "__other__" : !i.checked) return;
if (o.tagName === "TEXTAREA") grow(o);
if (!o.value) o.focus();
});
}
});
// A second tap (or Space) on the picked option clears it, so that
// "Other…" alone can answer a single choice.
var was = null;
var note = function () { was = $all("input[type=radio]", f).filter(function (i) { return i.checked; })[0] || null; };
f.addEventListener("pointerdown", note, true);
f.addEventListener("keydown", note, true);
var clear = function (i) {
i.checked = false;
was = null;
i.dispatchEvent(new Event("change", { bubbles: true }));
};
$all("input[type=radio]", f).forEach(function (i) {
if (i.value === "__other__") return; // an older machine's Other… radio
var spaced = false;
i.addEventListener("click", function () {
if (i !== was) { was = i; return; }
clear(i);
});
// Space on the picked radio clears it at once; its click (on key up)
// would tick it again, so the key goes no further.
i.addEventListener("keydown", function (e) {
if (e.key !== " " || !i.checked) return;
e.preventDefault();
spaced = true;
clear(i);
});
i.addEventListener("keyup", function (e) {
if (e.key === " " && spaced) e.preventDefault();
spaced = false;
});
});
// So does attaching a file to it.
var refs = f.querySelector(".other input[data-refs]");
if (refs) refs.addEventListener("change", function () {
if (!refs.value) return;
pickOther(f);
});
}
if (t === "slider") {
var r = f.querySelector("input[type=range]"), out = f.querySelector("output");
var sync = function () { if (out) out.textContent = r.value; };
r.addEventListener("input", sync);
sync();
}
if (t === "secret") {
var p = f.querySelector("input[type=password]");
var b = make("button", "reveal", tr("Show"));
b.type = "button";
b.addEventListener("click", function () {
var show = p.type === "password";
p.type = show ? "text" : "password";
b.textContent = tr(show ? "Hide" : "Show");
});
p.parentNode.appendChild(b);
}
$all("textarea", f).forEach(function (ta) {
ta.addEventListener("input", function () { grow(ta); });
grow(ta);
});
if (t === "daterange") {
var dr = inputs(f);
var span = function () { dr[1].min = dr[0].value || ""; };
dr[0].addEventListener("change", span);
span();
}
f.addEventListener("input", function () { touched[key] = true; clearErr(f); applyConditions(); refresh(); saveDraft(); });
f.addEventListener("change", function () { touched[key] = true; clearErr(f); applyConditions(); refresh(); saveDraft(); });
});
function clearErr(f) {
f.classList.remove("has-error");
$all(".err.js-err", f).forEach(function (e) { e.remove(); });
}
function flag(f, msg) {
clearErr(f);
f.classList.add("has-error");
f.appendChild(make("p", "err js-err", msg));
}
// ── conditions: showIf hides a field (and what tests it), requiredIf asks ──
// The page mirrors form.Cond: a test on a hidden question fails.
var hiddenKey = {}, applying = false;
function rawValue(f) {
var t = f.getAttribute("data-type"), els = inputs(f), key = f.getAttribute("data-key");
if (t === "checkbox") return !!(els[0] && els[0].checked);
if (t === "rating") {
var c = els.filter(function (i) { return i.checked; })[0];
return c ? Number(c.value) : null;
}
if (t === "radio" || t === "select" || t === "multiselect") {
var other = otherText(f);
if (t === "select" && !f.classList.contains("visual-field")) {
var s = f.querySelector("select");
return s.value && s.value !== "__other__" ? s.value : (other || null);
}
var picked = els.filter(function (i) {
return (i.type === "radio" || i.type === "checkbox") && i.checked && i.value !== "__other__";
}).map(function (i) { return i.value; });
if (other) picked.push(other);
return t === "multiselect" ? picked : (picked.length ? picked[0] : null);
}
if (t === "number" || t === "slider") {
var nv = els[0].value.trim().replace(",", ".");
return nv !== "" && isFinite(Number(nv)) ? Number(nv) : null;
}
if (t === "daterange") {
var d = els.map(function (i) { return i.value; });
return d[0] && d[1] ? { start: d[0], end: d[1] } : null;
}
if (t === "widget" || t === "file") {
try {
var j = els[0] && els[0].value ? JSON.parse(els[0].value) : null;
return Array.isArray(j) && !j.length ? null : j;
} catch (e) { return null; }
}
if (t === "list") {
var prefix = "f." + key + ".";
var rows = $all(".list-row", f).map(function (row) {
var cells = $all("input, select", row), obj = {}, texts = [];
cells.forEach(function (i) {
var v = i.value.trim();
if (!v) return;
texts.push(v);
obj[i.name.indexOf(prefix) === 0 ? i.name.slice(prefix.length) : ""] = i.type === "number" ? Number(v.replace(",", ".")) : v;
});
return { texts: texts, obj: obj };
}).filter(function (r) { return r.texts.length; });
var table = $all("input, select", f).some(function (i) { return i.name.indexOf(prefix) === 0; });
return rows.map(function (r) { return table ? r.obj : r.texts[0]; });
}
var v = els[0] ? els[0].value.trim() : "";
if (v !== "" && t === "email") v = v.toLowerCase();
if (v === "" && t === "textarea") v = attached(f).join(", ");
return v === "" ? null : v;
}
function isAnswered(v) {
if (v === null || v === undefined) return false;
if (typeof v === "boolean") return v;
if (typeof v === "string") return v !== "";
if (Array.isArray(v)) return v.length > 0;
return true;
}
function sameValue(a, b) { return a !== null && a !== undefined && typeof a === typeof b && a === b; }
function evalCond(c) {
if (c.all) return c.all.every(evalCond);
if (c.any) return c.any.some(evalCond);
if (c.not) return !evalCond(c.not);
if (!byKey[c.key] || hiddenKey[c.key]) return false;
var v = rawValue(byKey[c.key]);
switch (c.op) {
case "answered": return isAnswered(v) === c.value;
case "equals": return sameValue(v, c.value);
case "notEquals": return !sameValue(v, c.value);
case "in": return c.value.some(function (x) { return sameValue(v, x); });
case "includes":
if (typeof v === "string") return c.value !== "" && v.toLowerCase().indexOf(String(c.value).toLowerCase()) >= 0;
return Array.isArray(v) && v.some(function (x) { return String(x) === String(c.value); });
case "gt": return typeof v === "number" && v > c.value;
case "gte": return typeof v === "number" && v >= c.value;
case "lt": return typeof v === "number" && v < c.value;
case "lte": return typeof v === "number" && v <= c.value;
}
return false;
}
function condOf(f, attr) {
var cache = "_" + attr;
if (!(cache in f)) {
try { f[cache] = f.hasAttribute(attr) ? JSON.parse(f.getAttribute(attr)) : null; } catch (e) { f[cache] = null; }
}
return f[cache];
}
function vis(g) { return !groups[g].classList.contains("group-empty"); }
function applyConditions() {
if (applying) return;
applying = true;
allFields.forEach(function (f) {
var key = f.getAttribute("data-key"), show = condOf(f, "data-show-if");
var hide = !!show && !evalCond(show);
hiddenKey[key] = hide;
if (f.hidden !== hide) {
f.hidden = hide;
inputs(f).forEach(function (i) { i.disabled = hide; });
if (hide) clearErr(f);
}
var need = condOf(f, "data-required-if");
if (need) {
var on = !hide && evalCond(need);
if (on) f.setAttribute("data-required", ""); else f.removeAttribute("data-required");
$all(".if-req", f).forEach(function (m) { m.hidden = !on; });
}
});
// A page whose questions are all hidden goes too.
groups.forEach(function (g) {
var qs = $all(".field", g).filter(function (f) { return !f.classList.contains("is-display"); });
var empty = qs.length > 0 && qs.every(function (f) { return f.hidden; });
g.classList.toggle("group-empty", empty);
});
applying = false;
if (pager && !vis(current)) show(stepGroup(current, 1) !== current ? stepGroup(current, 1) : stepGroup(current, -1), false);
}
function stepGroup(from, dir) {
for (var i = from + dir; i >= 0 && i < groups.length; i += dir) if (vis(i)) return i;
return from;
}
// widget.js (widget fields) drives the page through these.
window.askFormPage = {
touch: function (f) { touched[f.getAttribute("data-key")] = true; clearErr(f); applyConditions(); refresh(); saveDraft(); },
flag: flag,
tr: tr
};
// ── pages ─────────────────────────────────────────────────────────────────
// A phone pages through the groups; a desktop shows them all, with the
// section list (.toc) beside them. CSS picks which: the list is displayed
// exactly when the page is wide enough.
var groups = $all(".group", form);
var current = 0, pager = null, nav = null;
var toc = document.querySelector(".toc"), tocBar = null, tocProgress = null;
applyConditions();
function wide() { return !!toc && getComputedStyle(toc).display !== "none"; }
function groupOf(el) { return groups.indexOf(el.closest(".group")); }
function groupPending(g) {
return $all(".field", groups[g]).some(function (f) { return fields.indexOf(f) >= 0 && unanswered(f); });
}
function show(g, focus) {
current = Math.max(0, Math.min(groups.length - 1, g));
if (!vis(current)) current = stepGroup(current, 1) !== current ? stepGroup(current, 1) : stepGroup(current, -1);
seen[current] = true;
groups.forEach(function (el, i) { el.classList.toggle("current", i === current); });
refresh();
if (focus) {
var first = $all(".field", groups[current]).filter(unanswered)[0];
var el = first && first.querySelector("input:not([type=hidden]), select, textarea");
if (wide()) groups[current].scrollIntoView({ block: "start" });
else window.scrollTo({ top: form.getBoundingClientRect().top + window.scrollY - 8 });
if (el && focus === "field") el.focus({ preventScroll: true });
}
}
if (groups.length > 1) {
form.classList.add("paged");
pager = make("div", "pager");
var row = make("div", "pager-row");
var count = make("span", "pager-count");
var segs = make("div", "pager-segs");
groups.forEach(function (el, i) {
var s = make("button", "pager-seg");
s.type = "button";
var title = el.getAttribute("data-title");
s.setAttribute("aria-label", title ? tr("Page {n}: {title}", { n: i + 1, title: title }) : tr("Page {n}", { n: i + 1 }));
s.addEventListener("click", function () { show(i, true); });
segs.appendChild(s);
});
row.appendChild(count);
row.appendChild(segs);
pager.appendChild(row);
pager.appendChild(make("div", "pager-title"));
form.insertBefore(pager, groups[0]);
nav = make("div", "nav");
var back = make("button", "btn ghost", tr("← Back"));
var next = make("button", "btn", tr("Next →"));
back.type = next.type = "button";
back.addEventListener("click", function () { show(stepGroup(current, -1), true); });
next.addEventListener("click", function () { show(stepGroup(current, 1), "field"); });
nav.appendChild(back);
nav.appendChild(next);
groups[groups.length - 1].after(nav);
nav.back = back;
nav.next = next;
}
if (toc) {
tocProgress = make("p", "toc-progress");
var bar = make("div", "toc-bar");
tocBar = make("i");
bar.appendChild(tocBar);
toc.appendChild(tocProgress);
toc.appendChild(bar);
$all("a[data-toc]", toc).forEach(function (a, i) {
a.addEventListener("click", function (e) {
if (!wide()) return;
e.preventDefault();
var still = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
groups[i].scrollIntoView({ block: "start", behavior: still ? "auto" : "smooth" });
});
});
}
// On a desktop the current group is the one scrolled to (the last whose top
// is above a third of the window, the last one at the bottom of the page).
function spy() {
if (!wide()) return;
var line = window.innerHeight / 3, at = 0;
groups.forEach(function (el, i) { if (vis(i) && el.getBoundingClientRect().top <= line) at = i; });
while (at > 0 && !vis(at)) at--;
if (window.scrollY > 0 && window.innerHeight + window.scrollY >= document.documentElement.scrollHeight - 2) at = stepGroup(groups.length, -1);
if (at === current) return;
current = at;
seen[at] = true;
groups.forEach(function (el, i) { el.classList.toggle("current", i === current); });
refresh();
}
function refresh() {
if (toc) {
$all("a[data-toc]", toc).forEach(function (a, i) {
var qs = $all(".field", groups[i]).filter(function (f) { return fields.indexOf(f) >= 0 && !f.hidden; });
a.parentNode.hidden = !vis(i);
a.className = (i === current ? "current" : "") + (qs.length ? (qs.some(unanswered) ? " pending" : " done") : "");
if (i === current) a.setAttribute("aria-current", "location");
else a.removeAttribute("aria-current");
});
var asked = fields.filter(function (f) { return !f.closest(".catchall") && !f.hidden; });
var n = asked.filter(function (f) { return !unanswered(f); }).length;
tocProgress.textContent = tr("{n} of {m} answered", { n: n, m: asked.length });
tocBar.style.width = (asked.length ? Math.round(100 * n / asked.length) : 0) + "%";
}
fields.forEach(function (f) {
var lab = f.querySelector(".label");
var dot = lab && lab.querySelector(".pending-dot");
var want = !!pager && unanswered(f);
if (want && !dot && lab) lab.appendChild(make("span", "pending-dot"));
if (!want && dot) dot.remove();
});
if (!pager) return;
var shown = groups.map(function (el, i) { return i; }).filter(vis);
pager.querySelector(".pager-count").textContent = (shown.indexOf(current) + 1) + "/" + shown.length;
$all(".pager-seg", pager).forEach(function (s, i) {
s.hidden = !vis(i);
s.className = "pager-seg" + (i === current ? " current" : i < current ? " done" : "") +
(i !== current && groupPending(i) ? " pending" : "");
});
pager.querySelector(".pager-title").textContent = groups[current].getAttribute("data-title") || "";
// No button where it would go nowhere: hidden, not just disabled, so
// the row never shows a greyed dead end (a first or a last page).
nav.back.hidden = stepGroup(current, -1) === current;
nav.next.hidden = stepGroup(current, 1) === current;
}
if (pager) {
var start = 0;
if (hadErrors) {
var bad = form.querySelector(".has-error");
start = bad ? Math.max(0, groupOf(bad)) : 0;
} else {
for (var i = 0; i < groups.length; i++) {
if (vis(i) && (!seen[i] || groupPending(i))) { start = i; break; }
}
}
show(start, false);
spy();
var ticking = false, wasWide = wide();
window.addEventListener("scroll", function () {
if (ticking) return;
ticking = true;
window.requestAnimationFrame(function () { ticking = false; spy(); });
}, { passive: true });
window.addEventListener("resize", function () {
var w = wide();
if (w === wasWide) return;
wasWide = w;
if (w) spy(); else show(current, false);
});
// The error summary's links land on the field's page.
$all(".errors a").forEach(function (a) {
a.addEventListener("click", function (e) {
var target = document.getElementById(a.getAttribute("href").slice(1));
if (!target) return;
e.preventDefault();
var g = groupOf(target);
if (g >= 0) show(g, false);
target.scrollIntoView({ block: "center" });
var el = target.querySelector("input:not([type=hidden]), select, textarea");
if (el) el.focus({ preventScroll: true });
});
});
} else refresh();
// ── print: the paper version of what's on screen ────────────────────────
// A list gets three rows at least (and the blank ones go again after), a
// slider that was moved prints as it stands instead of its values to
// circle, and a question shown only sometimes is printed whole, not greyed.
var printRows = [], printEnabled = [];
window.addEventListener("beforeprint", function () {
$all("[data-list]", form).forEach(function (list) {
var want = Math.max(3, Number(list.getAttribute("data-min") || 0)), row;
while ($all(".list-row", list).length < want && (row = addRow(list))) printRows.push(row);
});
fields.forEach(function (f) {
if (f.getAttribute("data-type") === "slider") f.classList.toggle("print-moved", !!touched[f.getAttribute("data-key")]);
});
$all(".field[hidden] :disabled", form).forEach(function (i) { i.disabled = false; printEnabled.push(i); });
});
window.addEventListener("afterprint", function () {
printRows.forEach(function (row) {
var list = row.parentNode;
if (list && listBlank(row)) { row.remove(); syncAdd(list); }
});
printEnabled.forEach(function (i) { if (i.closest(".field[hidden]")) i.disabled = true; });
printRows = [];
printEnabled = [];
});
// ── submit: the whole form checked, then a confirm step ─────────────────
var confirmed = false;
form.addEventListener("submit", function (e) {
var by = e.submitter;
if (by && by.value === "decline") { lock(); clearFormStorage(id); return; }
if (confirmed) { lock(); return; }
e.preventDefault();
var bad = fields.filter(function (f) {
var msg = problem(f);
if (msg) flag(f, msg);
return !!msg;
});
if (bad.length) {
var g = groupOf(bad[0]);
if (pager && g >= 0) show(g, false);
bad[0].scrollIntoView({ block: "center" });
var el = bad[0].querySelector("input:not([type=hidden]), select, textarea");
if (el) el.focus({ preventScroll: true });
return;
}
openConfirm(by);
});
// Cmd+Enter (Ctrl+Enter off a Mac) in the last box, "Anything else?",
// opens the send step as the Send button does.
var sendBtn = form.querySelector("button[type=submit][value=submit]");
form.addEventListener("keydown", function (e) {
if (e.key !== "Enter" || !(e.metaKey || e.ctrlKey) || e.altKey || e.shiftKey) return;
if (e.repeat || e.isComposing || e.defaultPrevented || !sendBtn || sendBtn.disabled) return;
if (!e.target.closest || !e.target.closest(".catchall")) return;
e.preventDefault();
if (form.requestSubmit) form.requestSubmit(sendBtn);
else sendBtn.click();
});
function lock() {
setTimeout(function () { $all("button[type=submit]", form).forEach(function (b) { b.disabled = true; }); }, 0);
}
function labelOf(f) {
var l = f.querySelector(".label-text") || f.querySelector(".check span");
return l ? l.textContent.trim() : f.getAttribute("data-key");
}
function choiceText(i) {
var lab = i.closest("label");
if (!lab) return i.value;
var c = lab.querySelector(".bar-text span, .choice-text span");
return c ? c.textContent.trim() : i.value;
}
function answerOf(f) {
var t = f.getAttribute("data-type");
if (t === "file") return $all(".file-item.done .file-name", f).map(function (n) { return n.textContent; }).join(", ");
var oText = otherText(f);
if (t === "checkbox") return tr(f.querySelector("input").checked ? "Yes" : "No");
if (t === "secret") {
var p = f.querySelector("input");
return p.value.trim() ? tr("🔒 {n} characters — not shown", { n: p.value.trim().length }) : "";
}
if (t === "select" && !f.classList.contains("visual-field")) {
var s = f.querySelector("select");
var sel = s.value && s.value !== "__other__" ? [s.options[s.selectedIndex].textContent.trim()] : [];
if (oText) sel.push(oText);
return sel.join(", ");
}
if (t === "radio" || t === "rating" || t === "multiselect" || t === "select") {
var parts = inputs(f).filter(function (i) {
return (i.type === "radio" || i.type === "checkbox") && i.checked && i.value !== "__other__";
}).map(choiceText);
if (oText) parts.push(oText);
return parts.join(", ");
}
if (t === "list") {
return $all(".list-row", f).map(function (row) {
return $all("input, select", row).map(function (i) { return i.value.trim(); }).filter(Boolean).join(" · ");
}).filter(Boolean).join("; ");
}
if (t === "daterange") {
var d = inputs(f).map(function (i) { return i.value; });
return d[0] || d[1] ? d[0] + " → " + d[1] : "";
}
var main = f.querySelector("input, textarea");
if (t === "widget" && main) {
var wv = main.value.trim();
try { var j = JSON.parse(wv); wv = typeof j === "string" ? j : JSON.stringify(j); } catch (e) { /* shown as typed */ }
return wv.length > 200 ? wv.slice(0, 200) + "…" : wv;
}
return main ? main.value.trim() : "";
}
function openConfirm(by) {
// Back returns to where the step was opened from: the box Cmd+Enter
// was pressed in, else the Send button.
var from = form.contains(document.activeElement) ? document.activeElement : by;
var wrap = make("div", "confirm");
wrap.setAttribute("role", "dialog");
wrap.setAttribute("aria-modal", "true");
var box = make("div", "confirm-box");
box.appendChild(make("h2", null, tr("Send these answers?")));
box.appendChild(make("p", "help", tr("The form closes once sent — you can't change them afterwards.")));
var dl = make("dl", "recap");
var n = 0;
fields.forEach(function (f) {
if (f.hidden) return;
var a = answerOf(f);
var files = attached(f);
if (files.length && (!otherInput(f) || otherPicked(f))) {
// Files alone answer with their names: said once is enough.
if (a === files.join(", ")) a = "";
a = (a ? a + " · " : "") + "📎 " + files.join(", ");
}
if (!a) return;
dl.appendChild(make("dt", null, labelOf(f)));
dl.appendChild(make("dd", null, a));
n++;
});
if (!n) dl.appendChild(make("dd", null, tr("No answers — the form will be sent empty.")));
box.appendChild(dl);
var acts = make("div", "actions");
var back = make("button", "btn ghost", tr("Back"));
var send = make("button", "btn primary", tr("Confirm & send"));
back.type = send.type = "button";
back.addEventListener("click", function () {
wrap.remove();
document.removeEventListener("keydown", key, true);
if (from) from.focus();
});
send.addEventListener("click", function () {
confirmed = true;
send.disabled = true;
if (form.requestSubmit && by) form.requestSubmit(by);
else {
var h = make("input");
h.type = "hidden"; h.name = "action"; h.value = "submit";
form.appendChild(h);
form.submit();
}
});
// The keyboard answers the step wherever the focus went (a click on the
// recap or the backdrop leaves it on the page): Esc goes back, Enter
// sends — Enter on a focused Back is that button's own — and Tab stays
// on the step's two buttons. Caught before the page's own handlers,
// and never the key press that opened the step (a held key repeats).
function key(e) {
if (!wrap.isConnected || e.defaultPrevented || e.isComposing) return;
if (e.key === "Escape") {
e.preventDefault();
back.click();
} else if (e.key === "Enter") {
if (e.repeat || send.disabled) { e.preventDefault(); return; }
if (document.activeElement === back && !(e.metaKey || e.ctrlKey)) return;
e.preventDefault();
send.click();
} else if (e.key === "Tab") {
e.preventDefault();
var ring = [back, send];
var at = ring.indexOf(document.activeElement);
ring[at < 0 ? (e.shiftKey ? 1 : 0) : 1 - at].focus();
}
}
document.addEventListener("keydown", key, true);
// A click on the dim backdrop goes back too — pressed there, not a
// selection in the recap dragged out of the box.
var downOut = false;
wrap.addEventListener("pointerdown", function (e) { downOut = e.target === wrap; });
wrap.addEventListener("click", function (e) {
if (e.target === wrap && downOut) back.click();
downOut = false;
});
acts.appendChild(back);
acts.appendChild(send);
box.appendChild(acts);
wrap.appendChild(box);
document.body.appendChild(wrap);
send.focus();
}
setupZoom();
// ── fullscreen pictures and mockups ─────────────────────────────────────
function setupZoom() {
$all("a.zoom, a.frame-open").forEach(function (a) {
a.addEventListener("click", function (e) {
e.preventDefault();
e.stopPropagation();
var field = a.closest(".field");
if (a.hasAttribute("data-zoom-frame") || a.classList.contains("frame-open")) {
openOverlay([{ frame: a.getAttribute("href"), label: a.getAttribute("data-zoom-label") || "" }], 0);
return;
}
var imgs = $all("img[data-zoom]", field || document);
var list = imgs.map(function (i) { return { img: i.getAttribute("data-zoom"), label: i.getAttribute("data-zoom-label") || "" }; });
var at = list.map(function (x) { return x.img; }).indexOf(a.getAttribute("href"));
openOverlay(list, Math.max(0, at));
});
});
}
// The fullscreen view of a mockup: its own shape, as large as the screen
// allows below the close button and above the label; a fluid one as wide
// as the view lets it read, as tall as it is.
function fitOverlay(f) {
var w = Number(f.getAttribute("data-w")), h = Number(f.getAttribute("data-h"));
var aw = window.innerWidth - 32, ah = window.innerHeight - 128;
if (!(w > 0 && h > 0 && aw > 0 && ah > 0)) return;
if (f.hasAttribute("data-fluid")) {
f.style.width = Math.min(aw, 1280) + "px";
f.style.height = Math.min(ah, h) + "px";
return;
}
var z = Math.min(aw / w, ah / h);
f.style.width = Math.floor(w * z) + "px";
f.style.height = Math.floor(h * z) + "px";
}
function openOverlay(list, at) {
var ov = make("div", "overlay");
ov.setAttribute("role", "dialog");
ov.setAttribute("aria-modal", "true");
var close = make("button", "overlay-close", "✕");
close.type = "button";
close.setAttribute("aria-label", tr("Close"));
var label = make("div", "overlay-label");
var holder = make("div");
holder.style.display = "contents";
function render() {
holder.textContent = "";
var it = list[at];
if (it.frame) {
var fr = make("iframe");
fr.src = it.frame;
fr.setAttribute("sandbox", "allow-scripts");
fr.setAttribute("referrerpolicy", "no-referrer");
holder.appendChild(fr);
} else {
var im = make("img");
im.src = it.img;
im.alt = it.label;
holder.appendChild(im);
}
label.textContent = list.length > 1 ? (at + 1) + "/" + list.length + (it.label ? " · " + it.label : "") : (it.label || "");
}
function done() { ov.remove(); document.removeEventListener("keydown", key); window.removeEventListener("resize", refit); }
function refit() { var f = holder.querySelector("iframe"); if (f) fitOverlay(f); }
function key(e) {
if (e.key === "Escape") done();
if (e.key === "ArrowLeft" && list.length > 1) { at = (at - 1 + list.length) % list.length; render(); }
if (e.key === "ArrowRight" && list.length > 1) { at = (at + 1) % list.length; render(); }
}
ov.appendChild(holder);
ov.appendChild(close);
ov.appendChild(label);
if (list.length > 1) {
var prev = make("button", "overlay-prev", "‹"), nxt = make("button", "overlay-next", "›");
prev.type = nxt.type = "button";
prev.addEventListener("click", function (e) { e.stopPropagation(); at = (at - 1 + list.length) % list.length; render(); });
nxt.addEventListener("click", function (e) { e.stopPropagation(); at = (at + 1) % list.length; render(); });
ov.appendChild(prev);
ov.appendChild(nxt);
}
close.addEventListener("click", done);
ov.addEventListener("click", function (e) { if (e.target === ov) done(); });
document.addEventListener("keydown", key);
window.addEventListener("resize", refit);
render();
document.body.appendChild(ov);
close.focus();
}
})();