Files
rotatyvote/static/js/common.js
T

244 lines
9.0 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;
// votes added by hand ride at the end of each bar, hatched orange, so nobody mistakes them for phone ballots
const ex = r.extra || { counts: r.counts.map(() => 0), blank: 0, ballots: 0 };
const tot = r.counts.map((c, i) => c + (ex.counts[i] || 0));
const ballots = r.ballots + ex.ballots, blank = r.blank + ex.blank, base = ballots - blank;
const max = Math.max(1, ...tot);
const rows = q.options.map((label, i) => {
const stack = h("div", { class: "bar-stack" },
seg("bar-fill", r.counts[i]), ex.counts[i] ? seg("bar-extra", ex.counts[i]) : null);
stack.style.width = `${pct(tot[i], max)}%`;
return h("div", { class: "bar-row" + (tot[i] === max && tot[i] > 0 ? " lead" : "") },
h("div", { class: "bar-label" }, label),
h("div", { class: "bar-track" }, stack),
h("div", { class: "bar-num" }, tot[i], h("small", {}, ` ${pct(tot[i], base).toLocaleString("fr-FR")} %`)),
);
});
return h("div", { class: "results" },
rows,
h("p", { class: "results-foot" },
`${ballots} bulletin${ballots > 1 ? "s" : ""}`,
q.allow_blank ? `, dont ${blank} blanc${blank > 1 ? "s" : ""}` : "",
ex.ballots ? h("span", { class: "extra-note" }, `, dont ${ex.ballots} ajouté${ex.ballots > 1 ? "s" : ""} à la main`) : "",
),
);
}
// a flex share of a bar (CSSOM write, the CSP blocks style="")
function seg(cls, n) {
const el = h("div", { class: cls });
el.style.flexGrow = String(n);
return el;
}
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";
const ICONS = {
screen: ["M3 5h18v11H3z", "M8 20h8", "M12 16v4"],
check: ["M5 12.5l4.5 4.5L19 7.5"],
swap: ["M4 9h13l-3.5-3.5", "M20 15H7l3.5 3.5"],
camera: ["M3 8.5A2.5 2.5 0 0 1 5.5 6h2L9 4h6l1.5 2h2A2.5 2.5 0 0 1 21 8.5v9a2.5 2.5 0 0 1-2.5 2.5h-13A2.5 2.5 0 0 1 3 17.5z",
"M12 9.5a3.5 3.5 0 1 0 0 7a3.5 3.5 0 1 0 0-7"],
};
export function icon(name, size = 16) {
const svg = document.createElementNS(SVGNS, "svg");
for (const [k, v] of Object.entries({ viewBox: "0 0 24 24", width: size, height: size, fill: "none",
stroke: "currentColor", "stroke-width": 2, "stroke-linecap": "round", "stroke-linejoin": "round",
class: "icon", "aria-hidden": "true" })) svg.setAttribute(k, v);
for (const d of ICONS[name]) {
const p = document.createElementNS(SVGNS, "path");
p.setAttribute("d", d);
svg.append(p);
}
return 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;
const at = (len) => { const a = -Math.PI / 2 + len / r; return `${50 + r * Math.cos(a)} ${50 + r * Math.sin(a)}`; };
const fills = [];
for (let i = 0; i < total; i++) {
const s0 = i * slot + (gap + sw) / 2;
const d = `M ${at(s0)} A ${r} ${r} 0 ${seg / r > Math.PI ? 1 : 0} 1 ${at(s0 + seg)}`;
// track underneath, fill on top sweeps clockwise. dash lengths in real units: some android webviews
// mishandle pathLength and draw the fill whole or not at all
for (const cls of ["seg", "fill"]) {
const el = document.createElementNS(SVGNS, "path");
el.setAttribute("d", d);
el.setAttribute("stroke-width", sw);
el.setAttribute("class", cls);
if (cls === "fill") {
el.style.strokeDasharray = `${seg} ${seg + sw * 2}`;
el.style.strokeDashoffset = String(seg);
fills.push(el);
}
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");
svg.append(t);
// updates in place so the css transitions run
svg.set = (k, text = `${k}/${total}`) => {
fills.forEach((el, i) => {
el.classList.toggle("on", i < k);
el.classList.toggle("last", i === k - 1 && k < total);
el.style.strokeDashoffset = String(i < k ? 0 : seg);
});
t.textContent = text;
};
svg.total = total;
svg.set(n, label);
return svg;
}
// keeps the same svg between counts so each new segment fills instead of popping in
export function paintRing(box, n, total, size) {
let svg = box.querySelector("svg.ring");
if (!svg || svg.total !== total) {
svg = ring(0, total, size);
box.replaceChildren(svg);
// one frame at the old count, so the first fill animates too
svg.getBoundingClientRect();
}
svg.set(n);
}