Starlette backend with sqlite, rotating HMAC QR tokens pushed to a key-protected projector page, multi-scan enrollment, optional one-time paper codes, anonymous ballots split from participation, live question push over websockets, e2e tests over HTTP and TLS.
176 lines
6.3 KiB
JavaScript
176 lines
6.3 KiB
JavaScript
export const $ = (sel, root = document) => root.querySelector(sel);
|
|
|
|
// tiny element builder, children are always text nodes or elements so no html injection
|
|
export function h(tag, attrs = {}, ...children) {
|
|
const el = document.createElement(tag);
|
|
for (const [k, v] of Object.entries(attrs || {})) {
|
|
if (v === null || v === undefined || v === false) continue;
|
|
if (k === "class") el.className = v;
|
|
else if (k.startsWith("on")) el.addEventListener(k.slice(2), v);
|
|
else if (k === "dataset") Object.assign(el.dataset, v);
|
|
else if (v === true) el.setAttribute(k, "");
|
|
else el.setAttribute(k, v);
|
|
}
|
|
for (const c of children.flat(Infinity)) {
|
|
if (c === null || c === undefined || c === false) continue;
|
|
el.append(c instanceof Node ? c : document.createTextNode(String(c)));
|
|
}
|
|
return el;
|
|
}
|
|
|
|
export const pollId = () => location.pathname.split("/").filter(Boolean)[1];
|
|
export const hashKey = () => decodeURIComponent(location.hash.slice(1));
|
|
|
|
// read the secret from the url fragment once, then hide it: the projector is photographed
|
|
export function takeKey(name) {
|
|
let k = hashKey();
|
|
if (k) {
|
|
try { sessionStorage.setItem(name, k); } catch { /* private mode */ }
|
|
history.replaceState(null, "", location.pathname);
|
|
} else {
|
|
try { k = sessionStorage.getItem(name) || ""; } catch { k = ""; }
|
|
}
|
|
return k;
|
|
}
|
|
|
|
export async function api(method, url, data, key) {
|
|
const headers = { "content-type": "application/json" };
|
|
if (key) headers.authorization = `Bearer ${key}`;
|
|
const res = await fetch(url, {
|
|
method,
|
|
headers,
|
|
body: data === undefined ? undefined : JSON.stringify(data),
|
|
credentials: "same-origin",
|
|
cache: "no-store",
|
|
});
|
|
let json = {};
|
|
try { json = await res.json(); } catch { /* empty body */ }
|
|
if (!res.ok) {
|
|
const e = new Error(json.error || `HTTP ${res.status}`);
|
|
e.status = res.status;
|
|
e.code = json.error;
|
|
throw e;
|
|
}
|
|
return json;
|
|
}
|
|
|
|
// websocket w/ reconnect. auth msg is sent first when given
|
|
export function liveSocket(path, { auth, onMessage, onStatus }) {
|
|
let ws, retry = 0, closed = false, timer;
|
|
const proto = location.protocol === "https:" ? "wss:" : "ws:";
|
|
function open() {
|
|
ws = new WebSocket(`${proto}//${location.host}${path}`);
|
|
ws.onopen = () => {
|
|
retry = 0;
|
|
if (auth) ws.send(JSON.stringify({ key: auth }));
|
|
onStatus?.("online");
|
|
};
|
|
ws.onmessage = (ev) => {
|
|
try { onMessage(JSON.parse(ev.data)); } catch (e) { console.error(e); }
|
|
};
|
|
ws.onclose = (ev) => {
|
|
onStatus?.(ev.code >= 4000 ? `denied:${ev.code}` : "offline");
|
|
if (closed || ev.code === 4003 || ev.code === 4004) return;
|
|
timer = setTimeout(open, Math.min(8000, 400 * 2 ** retry++));
|
|
};
|
|
}
|
|
open();
|
|
// phones kill sockets in background, reconnect as soon as visible again
|
|
document.addEventListener("visibilitychange", () => {
|
|
if (document.visibilityState === "visible" && ws.readyState > 1 && !closed) {
|
|
clearTimeout(timer);
|
|
open();
|
|
}
|
|
});
|
|
return { close() { closed = true; ws.close(); } };
|
|
}
|
|
|
|
export function drawQR(canvas, modules, px) {
|
|
const n = modules.length;
|
|
const quiet = 4;
|
|
const size = n + quiet * 2;
|
|
const scale = Math.max(1, Math.floor(px / size));
|
|
canvas.width = canvas.height = size * scale;
|
|
const ctx = canvas.getContext("2d");
|
|
ctx.fillStyle = "#fff";
|
|
ctx.fillRect(0, 0, canvas.width, canvas.height);
|
|
ctx.fillStyle = "#000";
|
|
for (let y = 0; y < n; y++) {
|
|
const row = modules[y];
|
|
for (let x = 0; x < n; x++) {
|
|
if (row.charCodeAt(x) === 49) ctx.fillRect((x + quiet) * scale, (y + quiet) * scale, scale, scale);
|
|
}
|
|
}
|
|
}
|
|
|
|
export function pct(n, d) {
|
|
return d ? Math.round((n / d) * 1000) / 10 : 0;
|
|
}
|
|
|
|
// CSSOM write, a style="" attribute would be blocked by the CSP
|
|
export function fill(percent, cls = "bar-fill") {
|
|
const el = h("div", { class: cls });
|
|
el.style.width = `${percent}%`;
|
|
return el;
|
|
}
|
|
|
|
export function resultsView(q) {
|
|
const r = q.results;
|
|
if (!r) return null;
|
|
const base = r.ballots - r.blank;
|
|
const max = Math.max(1, ...r.counts);
|
|
const rows = q.options.map((label, i) =>
|
|
h("div", { class: "bar-row" + (r.counts[i] === max && r.counts[i] > 0 ? " lead" : "") },
|
|
h("div", { class: "bar-label" }, label),
|
|
h("div", { class: "bar-track" }, fill(pct(r.counts[i], max))),
|
|
h("div", { class: "bar-num" }, r.counts[i], h("small", {}, ` ${pct(r.counts[i], base).toLocaleString("fr-FR")} %`)),
|
|
));
|
|
return h("div", { class: "results" },
|
|
rows,
|
|
h("p", { class: "results-foot" },
|
|
`${r.ballots} bulletin${r.ballots > 1 ? "s" : ""}`,
|
|
q.allow_blank ? `, dont ${r.blank} blanc${r.blank > 1 ? "s" : ""}` : "",
|
|
),
|
|
);
|
|
}
|
|
|
|
export const STATE_LABEL = { draft: "Brouillon", open: "Vote ouvert", closed: "Clos" };
|
|
|
|
export function toast(msg, kind = "info") {
|
|
let box = $("#toasts");
|
|
if (!box) { box = h("div", { id: "toasts", role: "status", "aria-live": "polite" }); document.body.append(box); }
|
|
const t = h("div", { class: `toast ${kind}` }, msg);
|
|
box.append(t);
|
|
setTimeout(() => t.remove(), 4000);
|
|
}
|
|
|
|
const SVGNS = "http://www.w3.org/2000/svg";
|
|
|
|
// segmented ring: n of total segments lit, the newest one in highlighter yellow
|
|
export function ring(n, total, size = 160, label = `${n}/${total}`) {
|
|
const svg = document.createElementNS(SVGNS, "svg");
|
|
svg.setAttribute("viewBox", "0 0 100 100");
|
|
svg.setAttribute("width", size);
|
|
svg.setAttribute("height", size);
|
|
svg.setAttribute("class", "ring");
|
|
const r = 40, sw = 10, c = 2 * Math.PI * r;
|
|
// round caps overhang sw/2 on each side, so shorten each dash by sw
|
|
const slot = c / total, gap = total > 1 ? 5 : 0, seg = slot - gap - sw;
|
|
for (let i = 0; i < total; i++) {
|
|
const el = document.createElementNS(SVGNS, "circle");
|
|
el.setAttribute("cx", 50); el.setAttribute("cy", 50); el.setAttribute("r", r);
|
|
el.setAttribute("stroke-width", sw);
|
|
el.setAttribute("stroke-dasharray", `${seg} ${c - seg}`);
|
|
// start at 12 o'clock
|
|
el.setAttribute("stroke-dashoffset", String(c / 4 - i * slot - (gap + sw) / 2));
|
|
el.setAttribute("class", "seg" + (i < n ? " on" : "") + (i === n - 1 && n < total ? " last" : ""));
|
|
svg.append(el);
|
|
}
|
|
const t = document.createElementNS(SVGNS, "text");
|
|
t.setAttribute("x", 50); t.setAttribute("y", 50);
|
|
t.setAttribute("text-anchor", "middle"); t.setAttribute("dominant-baseline", "central");
|
|
t.textContent = label;
|
|
svg.append(t);
|
|
return svg;
|
|
}
|