RotatyVote: in-person anonymous voting with rotating QR enrollment
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.
This commit is contained in:
@@ -0,0 +1,250 @@
|
||||
import { $, h, api, pollId, takeKey, liveSocket, resultsView, STATE_LABEL, toast, fill, pct } from "./common.js";
|
||||
|
||||
const pid = pollId();
|
||||
const key = takeKey(`rv_admin_${pid}`);
|
||||
const base = `/api/polls/${pid}`;
|
||||
let state = null;
|
||||
let settingsDirty = false;
|
||||
|
||||
const TEMPLATES = [
|
||||
{ label: "Pour / Contre / Abstention", opts: ["Pour", "Contre", "Abstention"], blank: false },
|
||||
{ label: "Oui / Non", opts: ["Oui", "Non"], blank: true },
|
||||
{ label: "Élection (candidats)", opts: ["Candidat·e A", "Candidat·e B", "Candidat·e C"], blank: true, text: "Élection : " },
|
||||
{ label: "Satisfaction 1–5", opts: ["1", "2", "3", "4", "5"], blank: true },
|
||||
];
|
||||
|
||||
const call = (method, path, data) => api(method, base + path, data, key);
|
||||
|
||||
function errMsg(e) {
|
||||
const m = {
|
||||
not_draft: "La question n'est plus en brouillon",
|
||||
not_open: "La question n'est pas ouverte",
|
||||
not_closed: "La question n'est pas close",
|
||||
};
|
||||
return m[e.code] || e.message;
|
||||
}
|
||||
|
||||
|
||||
function render() {
|
||||
const p = state.poll;
|
||||
$("#title").textContent = p.title;
|
||||
document.title = `Admin · ${p.title}`;
|
||||
$("#voters").textContent = state.voters;
|
||||
const parts = [];
|
||||
if (p.expected) parts.push(`sur ${p.expected} attendus`);
|
||||
if (p.max_voters) parts.push(`${p.max_voters} max`);
|
||||
$("#voters-of").textContent = `inscrits${parts.length ? ", " + parts.join(", ") : ""}`;
|
||||
|
||||
const es = $("#enroll-state");
|
||||
es.hidden = !p.enrollment_open && !(p.expected && state.voters > p.expected);
|
||||
if (p.enrollment_open) {
|
||||
es.className = "notice ok";
|
||||
es.textContent = "Ouvertes";
|
||||
} else {
|
||||
es.className = "notice info";
|
||||
es.textContent = "Fermées";
|
||||
}
|
||||
if (p.expected && state.voters > p.expected) {
|
||||
es.className = "notice bad";
|
||||
es.textContent = `${state.voters} inscrits pour ${p.expected} attendus`;
|
||||
}
|
||||
const tb = $("#toggle-enroll");
|
||||
tb.textContent = p.enrollment_open ? "Fermer les inscriptions" : "Ouvrir les inscriptions";
|
||||
tb.className = "block " + (p.enrollment_open ? "danger" : "go");
|
||||
|
||||
$("#screens").textContent = state.screens ? `Projecteur connecté (${state.screens})` : "Aucun projecteur connecté";
|
||||
|
||||
if (!settingsDirty) {
|
||||
$("#s-interval").value = p.interval_ms;
|
||||
$("#s-scans").value = p.scans_required;
|
||||
$("#s-expected").value = p.expected ?? "";
|
||||
$("#s-max").value = p.max_voters ?? "";
|
||||
$("#s-code").checked = p.require_code;
|
||||
}
|
||||
$("#codes-card").hidden = !p.require_code && !state.codes.total;
|
||||
$("#codes-summary").textContent = `${state.codes.used} utilisé(s) sur ${state.codes.total}.`;
|
||||
|
||||
renderQuestions();
|
||||
}
|
||||
|
||||
function renderQuestions() {
|
||||
const box = $("#questions");
|
||||
box.replaceChildren();
|
||||
if (!state.questions.length) {
|
||||
box.append(h("p", { class: "muted" }, "Aucune question."));
|
||||
return;
|
||||
}
|
||||
const voters = state.voters;
|
||||
for (const q of state.questions) {
|
||||
const focused = state.poll.focus_qid === q.id;
|
||||
const badges = [h("span", { class: `badge ${q.state}` }, STATE_LABEL[q.state])];
|
||||
if (q.results_public) badges.push(h("span", { class: "badge public" }, "Résultats publiés"));
|
||||
if (focused) badges.push(h("span", { class: "focus-mark" }, "● à l'écran"));
|
||||
|
||||
const actions = [];
|
||||
const act = (label, action, cls = "small", confirmMsg) =>
|
||||
h("button", {
|
||||
class: cls, type: "button",
|
||||
onclick: async () => {
|
||||
if (confirmMsg && !confirm(confirmMsg)) return;
|
||||
try { await call("POST", `/questions/${q.id}/${action}`); } catch (e) { toast(errMsg(e), "bad"); }
|
||||
},
|
||||
}, label);
|
||||
if (q.state === "draft") {
|
||||
actions.push(act("Lancer le vote", "open", "small go"));
|
||||
actions.push(act("Supprimer", "delete", "small danger", "Supprimer ce brouillon ?"));
|
||||
}
|
||||
if (q.state === "open") {
|
||||
actions.push(act("Clore le vote", "close", "small primary",
|
||||
`Clore le vote (${q.participants} votants) ? Définitif.`));
|
||||
}
|
||||
if (q.state === "closed") {
|
||||
actions.push(q.results_public ? act("Masquer les résultats", "unpublish") : act("Publier les résultats", "publish", "small primary"));
|
||||
}
|
||||
if (q.state !== "draft" && !focused) actions.push(act("Afficher à l'écran", "focus"));
|
||||
|
||||
const turnout = q.state !== "draft"
|
||||
? h("div", {},
|
||||
h("div", { class: "q-meta" }, `${q.participants} / ${voters} votants`),
|
||||
h("div", { class: "progress" }, fill(pct(q.participants, voters), "")))
|
||||
: null;
|
||||
|
||||
box.append(h("article", { class: `q ${q.state}` },
|
||||
h("div", { class: "q-head" }, h("div", {}, badges), h("span", { class: "q-meta" }, `#${q.id}`)),
|
||||
h("div", { class: "q-text" }, q.text),
|
||||
q.state === "closed" ? resultsView(q) : h("ol", { class: "q-opts" }, q.options.map((o) => h("li", {}, o))),
|
||||
h("div", { class: "q-meta" },
|
||||
q.kind === "multi" ? `Max ${q.max_choices} choix` : "",
|
||||
q.kind === "multi" && q.allow_blank ? ", " : "",
|
||||
q.allow_blank ? "blanc possible" : ""),
|
||||
turnout,
|
||||
h("div", { class: "actions" }, actions),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
for (const t of TEMPLATES) {
|
||||
$("#templates").append(h("button", {
|
||||
class: "small", type: "button",
|
||||
onclick: () => {
|
||||
$("#q-opts").value = t.opts.join("\n");
|
||||
$("#q-blank").checked = t.blank;
|
||||
if (t.text && !$("#q-text").value) $("#q-text").value = t.text;
|
||||
$("#q-text").focus();
|
||||
},
|
||||
}, t.label));
|
||||
}
|
||||
$("#q-kind").addEventListener("change", () => { $("#q-max-box").hidden = $("#q-kind").value !== "multi"; });
|
||||
|
||||
async function submitQuestion(open) {
|
||||
const options = $("#q-opts").value.split("\n").map((s) => s.trim()).filter(Boolean);
|
||||
const data = {
|
||||
text: $("#q-text").value.trim(),
|
||||
options,
|
||||
kind: $("#q-kind").value,
|
||||
max_choices: +$("#q-max").value || 1,
|
||||
allow_blank: $("#q-blank").checked,
|
||||
open,
|
||||
};
|
||||
if (!data.text) return toast("Saisissez la question", "bad");
|
||||
if (options.length < 2) return toast("Au moins deux réponses", "bad");
|
||||
try {
|
||||
await call("POST", "/questions", data);
|
||||
$("#q-text").value = "";
|
||||
$("#q-opts").value = "";
|
||||
toast(open ? "Vote lancé" : "Question préparée", "ok");
|
||||
} catch (e) { toast(errMsg(e), "bad"); }
|
||||
}
|
||||
$("#q-draft").addEventListener("click", () => submitQuestion(false));
|
||||
$("#q-push").addEventListener("click", () => submitQuestion(true));
|
||||
|
||||
|
||||
$("#toggle-enroll").addEventListener("click", async () => {
|
||||
const open = !state.poll.enrollment_open;
|
||||
if (!open && !confirm(`Fermer les inscriptions (${state.voters} inscrits) ?`)) return;
|
||||
try { await call("PATCH", "", { enrollment_open: open }); } catch (e) { toast(errMsg(e), "bad"); }
|
||||
});
|
||||
|
||||
for (const id of ["#s-interval", "#s-scans", "#s-expected", "#s-max", "#s-code"]) {
|
||||
$(id).addEventListener("input", () => { settingsDirty = true; });
|
||||
}
|
||||
$("#save-settings").addEventListener("click", async () => {
|
||||
try {
|
||||
await call("PATCH", "", {
|
||||
interval_ms: +$("#s-interval").value,
|
||||
scans_required: +$("#s-scans").value,
|
||||
expected: $("#s-expected").value ? +$("#s-expected").value : null,
|
||||
max_voters: $("#s-max").value ? +$("#s-max").value : null,
|
||||
require_code: $("#s-code").checked,
|
||||
});
|
||||
settingsDirty = false;
|
||||
toast("Réglages enregistrés", "ok");
|
||||
} catch (e) { toast(errMsg(e), "bad"); }
|
||||
});
|
||||
|
||||
|
||||
$("#codes-gen").addEventListener("click", async () => {
|
||||
try {
|
||||
await call("POST", "/codes", { count: +$("#codes-count").value });
|
||||
toast("Codes générés", "ok");
|
||||
} catch (e) { toast(errMsg(e), "bad"); }
|
||||
});
|
||||
$("#codes-print").addEventListener("click", async () => {
|
||||
const { codes } = await call("GET", "/codes");
|
||||
$("#codes-title").textContent = `Codes d'accès, ${state.poll.title}`;
|
||||
$("#codes-grid").replaceChildren(...codes.map((c) => h("div", { class: "code-cell" + (c.used ? " used" : "") }, c.code)));
|
||||
$("#codes-sheet").hidden = false;
|
||||
$("#codes-sheet").scrollIntoView({ behavior: "smooth" });
|
||||
});
|
||||
$("#codes-close").addEventListener("click", () => { $("#codes-sheet").hidden = true; });
|
||||
$("#codes-do-print").addEventListener("click", () => window.print());
|
||||
|
||||
|
||||
$("#open-screen").href = `/screen/${pid}#${encodeURIComponent(key)}`;
|
||||
// the key is hidden from the address bar, so a bookmark would lose it
|
||||
$("#copy-admin").addEventListener("click", async () => {
|
||||
const link = `${location.origin}/admin/${pid}#${encodeURIComponent(key)}`;
|
||||
try { await navigator.clipboard.writeText(link); toast("Lien admin copié"); }
|
||||
catch { prompt("Lien admin", link); }
|
||||
});
|
||||
$("#screen-rotate").addEventListener("click", async () => {
|
||||
if (!confirm("Révoquer l'ancien lien projecteur ?")) return;
|
||||
try {
|
||||
const r = await call("POST", "/screen-key");
|
||||
$("#screen-link").value = `${location.origin}/screen/${pid}#${r.screen_key}`;
|
||||
$("#screen-link").select();
|
||||
} catch (e) { toast(errMsg(e), "bad"); }
|
||||
});
|
||||
$("#export").addEventListener("click", async () => {
|
||||
try {
|
||||
const data = await call("GET", "/export");
|
||||
const blob = new Blob([JSON.stringify(data, null, 2)], { type: "application/json" });
|
||||
const a = h("a", { href: URL.createObjectURL(blob), download: `rotatyvote-${pid}.json` });
|
||||
a.click();
|
||||
setTimeout(() => URL.revokeObjectURL(a.href), 1000);
|
||||
} catch (e) { toast(errMsg(e), "bad"); }
|
||||
});
|
||||
|
||||
|
||||
liveSocket(`/ws/${pid}/admin`, {
|
||||
auth: key,
|
||||
onMessage(msg) {
|
||||
if (msg.type !== "state") return;
|
||||
state = msg;
|
||||
$("#app").hidden = false;
|
||||
$("#denied").hidden = true;
|
||||
render();
|
||||
},
|
||||
onStatus(s) {
|
||||
const c = $("#conn");
|
||||
if (s.startsWith("denied")) {
|
||||
$("#denied").hidden = false;
|
||||
c.className = "conn offline";
|
||||
c.textContent = "refusé";
|
||||
return;
|
||||
}
|
||||
c.className = `conn ${s}`;
|
||||
c.textContent = s === "online" ? "en direct" : "reconnexion…";
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,175 @@
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { $, api, toast } from "./common.js";
|
||||
|
||||
const cfg = await api("GET", "/api/config").catch(() => ({}));
|
||||
$("#pw-box").hidden = !cfg.create_password;
|
||||
|
||||
function hint() {
|
||||
const s = (+$("#interval").value * +$("#scans").value) / 1000;
|
||||
$("#duration-hint").textContent = `≈ ${s.toLocaleString("fr-FR")} s de scan`;
|
||||
}
|
||||
$("#interval").addEventListener("change", hint);
|
||||
$("#scans").addEventListener("input", hint);
|
||||
hint();
|
||||
|
||||
$("#codes-on").addEventListener("change", (e) => { $("#codes-box").hidden = !e.target.checked; });
|
||||
|
||||
$("#form").addEventListener("submit", async (e) => {
|
||||
e.preventDefault();
|
||||
const btn = e.submitter;
|
||||
btn.disabled = true;
|
||||
try {
|
||||
const res = await api("POST", "/api/polls", {
|
||||
title: $("#title").value,
|
||||
interval_ms: +$("#interval").value,
|
||||
scans_required: +$("#scans").value,
|
||||
expected: $("#expected").value ? +$("#expected").value : null,
|
||||
max_voters: $("#maxv").value ? +$("#maxv").value : null,
|
||||
require_code: $("#codes-on").checked,
|
||||
codes: $("#codes-on").checked ? +$("#codes").value : 0,
|
||||
password: $("#pw").value || undefined,
|
||||
});
|
||||
const admin = `${location.origin}/admin/${res.id}#${res.admin_key}`;
|
||||
const screen = `${location.origin}/screen/${res.id}#${res.screen_key}`;
|
||||
$("#admin-link").value = admin;
|
||||
$("#screen-link").value = screen;
|
||||
$("#go-admin").href = admin;
|
||||
$("#create").hidden = true;
|
||||
$("#done").hidden = false;
|
||||
} catch (err) {
|
||||
toast(err.code === "bad_password" ? "Mot de passe incorrect" : `Erreur : ${err.message}`, "bad");
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
}
|
||||
});
|
||||
|
||||
for (const [btn, input] of [["#copy-admin", "#admin-link"], ["#copy-screen", "#screen-link"]]) {
|
||||
$(btn).addEventListener("click", async () => {
|
||||
try { await navigator.clipboard.writeText($(input).value); toast("Copié", "ok"); }
|
||||
catch { $(input).select(); }
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
import { $, h, pollId, takeKey, liveSocket, drawQR, resultsView, fill, pct } from "./common.js";
|
||||
|
||||
const pid = pollId();
|
||||
const key = takeKey(`rv_screen_${pid}`);
|
||||
let st = null;
|
||||
let qr = null;
|
||||
let raf = 0;
|
||||
|
||||
function layout() {
|
||||
if (!st) return;
|
||||
const enroll = st.enrollment_open;
|
||||
const focus = st.focus;
|
||||
$("#enroll").hidden = !enroll;
|
||||
$("#focus").hidden = !focus;
|
||||
$("#idle").hidden = enroll || !!focus;
|
||||
$(".s-main").classList.toggle("split", enroll && !!focus);
|
||||
}
|
||||
|
||||
function render() {
|
||||
$("#s-title").textContent = st.title;
|
||||
$("#idle-title").textContent = st.title;
|
||||
document.title = st.title;
|
||||
$("#voters").textContent = st.voters;
|
||||
$("#voters-label").textContent =
|
||||
`inscrit${st.voters > 1 ? "s" : ""}` + (st.expected ? ` / ${st.expected}` : "");
|
||||
$("#secs").textContent = Math.ceil((st.scans_required * st.interval_ms) / 1000);
|
||||
const b = $("#enroll-badge");
|
||||
b.className = `badge ${st.enrollment_open ? "open" : "closed"}`;
|
||||
b.textContent = st.enrollment_open ? "Inscriptions ouvertes" : "Inscriptions closes";
|
||||
|
||||
const f = st.focus;
|
||||
const box = $("#focus");
|
||||
box.replaceChildren();
|
||||
if (f) {
|
||||
box.append(h("div", { class: "q-text" }, f.text));
|
||||
if (f.state === "open") {
|
||||
box.append(
|
||||
h("ul", { class: "opts" }, f.options.map((o) => h("li", {}, o))),
|
||||
h("div", { class: "turnout" },
|
||||
h("b", {}, f.participants), ` vote${f.participants > 1 ? "s" : ""} sur ${st.voters}`,
|
||||
h("div", { class: "progress" }, fill(pct(f.participants, st.voters), ""))),
|
||||
);
|
||||
} else if (f.results) {
|
||||
box.append(resultsView(f));
|
||||
} else {
|
||||
box.append(h("p", { class: "status" }, `Vote clos, ${f.participants} votant${f.participants > 1 ? "s" : ""}`));
|
||||
}
|
||||
}
|
||||
layout();
|
||||
}
|
||||
|
||||
function paintQR() {
|
||||
if (!qr) return;
|
||||
const c = $("#qr");
|
||||
const px = Math.min(c.clientWidth || 600, c.clientHeight || 600) * (window.devicePixelRatio || 1);
|
||||
drawQR(c, qr.modules, px);
|
||||
}
|
||||
|
||||
function animateTick() {
|
||||
cancelAnimationFrame(raf);
|
||||
const bar = $("#tick-bar");
|
||||
const step = () => {
|
||||
if (!qr) return;
|
||||
const left = qr.valid_until - (Date.now() - skew);
|
||||
bar.style.width = `${Math.max(0, Math.min(100, (left / qr.interval_ms) * 100))}%`;
|
||||
raf = requestAnimationFrame(step);
|
||||
};
|
||||
step();
|
||||
}
|
||||
|
||||
let skew = 0;
|
||||
window.addEventListener("resize", paintQR);
|
||||
|
||||
$("#fs").addEventListener("click", () => document.documentElement.requestFullscreen?.());
|
||||
|
||||
liveSocket(`/ws/${pid}/screen`, {
|
||||
auth: key,
|
||||
onMessage(msg) {
|
||||
if (msg.type === "state") {
|
||||
st = msg;
|
||||
if (!st.enrollment_open) qr = null;
|
||||
render();
|
||||
} else if (msg.type === "qr") {
|
||||
// server clock drives validity, estimate offset so the countdown bar is right
|
||||
skew = Date.now() - msg.slot * msg.interval_ms;
|
||||
qr = msg;
|
||||
paintQR();
|
||||
animateTick();
|
||||
const host = new URL(msg.url).hostname;
|
||||
const local = ["localhost", "127.0.0.1", "::1", "[::1]"].includes(host);
|
||||
const w = $("#url-warn");
|
||||
w.hidden = !local;
|
||||
if (local) w.textContent = `QR vers ${host} : injoignable depuis un téléphone. Définissez PUBLIC_URL.`;
|
||||
}
|
||||
},
|
||||
onStatus(s) {
|
||||
const c = $("#conn");
|
||||
if (s.startsWith("denied")) {
|
||||
$("#denied").hidden = false;
|
||||
return;
|
||||
}
|
||||
c.className = `conn ${s}`;
|
||||
c.textContent = s === "online" ? "en direct" : "reconnexion…";
|
||||
if (s !== "online") { qr = null; const cv = $("#qr"); cv.getContext("2d").clearRect(0, 0, cv.width, cv.height); }
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,312 @@
|
||||
import { $, h, api, pollId, liveSocket, resultsView, toast, ring } from "./common.js";
|
||||
|
||||
const pid = pollId();
|
||||
const DONE_KEY = `rv_done_${pid}`;
|
||||
const apiBase = `/api/v/${pid}`;
|
||||
|
||||
// token from the QR that opened this page, then drop it from the url bar so it isn't shared
|
||||
const firstToken = decodeURIComponent(location.hash.slice(1));
|
||||
if (location.hash) history.replaceState(null, "", location.pathname);
|
||||
|
||||
let scanner = null;
|
||||
let required = 5;
|
||||
let socket = null;
|
||||
const sent = new Set();
|
||||
const selections = new Map();
|
||||
let queue = Promise.resolve();
|
||||
let lastState = null;
|
||||
let lastJson = "";
|
||||
|
||||
function show(id) {
|
||||
for (const s of ["#v-loading", "#v-enroll", "#v-code", "#v-blocked", "#v-vote"]) $(s).hidden = s !== id;
|
||||
}
|
||||
|
||||
function block(msg) {
|
||||
stopScanner();
|
||||
$("#blocked-msg").textContent = msg;
|
||||
show("#v-blocked");
|
||||
}
|
||||
|
||||
function lsGet(k) { try { return localStorage.getItem(k); } catch { return null; } }
|
||||
function lsSet(k, v) { try { localStorage.setItem(k, v); } catch { /* private mode */ } }
|
||||
|
||||
|
||||
function renderDots(n) {
|
||||
const box = $("#dots");
|
||||
box.replaceChildren(ring(n, required, 150));
|
||||
box.setAttribute("aria-label", `${n} codes lus sur ${required}`);
|
||||
}
|
||||
|
||||
function scanMsg(text, kind = "") {
|
||||
const m = $("#scan-msg");
|
||||
m.textContent = text;
|
||||
m.className = `scan-msg ${kind || "muted"}`;
|
||||
}
|
||||
|
||||
async function startScanner() {
|
||||
if (scanner) return;
|
||||
if (!window.isSecureContext) {
|
||||
scanMsg("Caméra impossible sans HTTPS.", "bad");
|
||||
return;
|
||||
}
|
||||
$("#cam-box").hidden = false;
|
||||
scanner = new window.QrScanner($("#video"), (r) => onScan(r.data), {
|
||||
returnDetailedScanResult: true,
|
||||
preferredCamera: "environment",
|
||||
maxScansPerSecond: 15,
|
||||
// whole frame, the projected code is often small and off-center
|
||||
calculateScanRegion: (v) => {
|
||||
const w = Math.min(960, v.videoWidth);
|
||||
return { x: 0, y: 0, width: v.videoWidth, height: v.videoHeight,
|
||||
downScaledWidth: w, downScaledHeight: Math.round((w * v.videoHeight) / v.videoWidth) };
|
||||
},
|
||||
});
|
||||
try {
|
||||
await scanner.start();
|
||||
$("#start-cam").hidden = true;
|
||||
scanMsg("");
|
||||
navigator.wakeLock?.request("screen").catch(() => {});
|
||||
} catch (e) {
|
||||
console.warn(e);
|
||||
scanner.destroy();
|
||||
scanner = null;
|
||||
$("#cam-box").hidden = true;
|
||||
$("#start-cam").hidden = false;
|
||||
scanMsg("Autorisez la caméra puis réessayez.", "bad");
|
||||
}
|
||||
}
|
||||
|
||||
function stopScanner() {
|
||||
if (!scanner) return;
|
||||
scanner.stop();
|
||||
scanner.destroy();
|
||||
scanner = null;
|
||||
$("#cam-box").hidden = true;
|
||||
}
|
||||
|
||||
function onScan(data) {
|
||||
let u;
|
||||
try { u = new URL(data); } catch { return; }
|
||||
const parts = u.pathname.split("/").filter(Boolean);
|
||||
if (parts[0] !== "v" || parts[1] !== pid) {
|
||||
scanMsg("QR d'un autre scrutin.", "bad");
|
||||
return;
|
||||
}
|
||||
const token = decodeURIComponent(u.hash.slice(1));
|
||||
if (!token || sent.has(token)) return;
|
||||
sent.add(token);
|
||||
submitToken(token);
|
||||
}
|
||||
|
||||
function submitToken(token) {
|
||||
// serialized so progress never goes backwards on out of order responses
|
||||
queue = queue.then(async () => {
|
||||
let r;
|
||||
try { r = await api("POST", `${apiBase}/scan`, { token }); }
|
||||
catch { scanMsg("Réseau instable…", "bad"); return; }
|
||||
handleScan(r);
|
||||
});
|
||||
}
|
||||
|
||||
function handleScan(r) {
|
||||
if (r.required) required = r.required;
|
||||
switch (r.status) {
|
||||
case "progress":
|
||||
renderDots(r.count);
|
||||
scanMsg(r.accepted || r.valid ? "" : "Code expiré, continuez…");
|
||||
navigator.vibrate?.(15);
|
||||
break;
|
||||
case "need_code":
|
||||
stopScanner();
|
||||
show("#v-code");
|
||||
$("#code").focus();
|
||||
break;
|
||||
case "enrolled":
|
||||
enrolled();
|
||||
break;
|
||||
case "closed":
|
||||
block("Inscriptions closes.");
|
||||
break;
|
||||
case "full":
|
||||
block("Nombre maximal d'inscrits atteint.");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
function enrolled() {
|
||||
stopScanner();
|
||||
lsSet(DONE_KEY, "1");
|
||||
navigator.vibrate?.([40, 60, 40]);
|
||||
boot();
|
||||
}
|
||||
|
||||
$("#start-cam").addEventListener("click", startScanner);
|
||||
|
||||
$("#code-form").addEventListener("submit", async (e) => {
|
||||
e.preventDefault();
|
||||
const msg = $("#code-msg");
|
||||
try {
|
||||
const r = await api("POST", `${apiBase}/code`, { code: $("#code").value });
|
||||
if (r.status === "enrolled") return enrolled();
|
||||
if (r.status === "bad_code") {
|
||||
msg.className = "scan-msg bad";
|
||||
msg.textContent = `Code invalide (${r.tries_left} essai(s) restant(s))`;
|
||||
} else if (r.status === "rescan") {
|
||||
sent.clear();
|
||||
toast("Délai dépassé, rescannez.", "bad");
|
||||
startEnroll(0);
|
||||
} else handleScan(r);
|
||||
} catch (err) {
|
||||
msg.className = "scan-msg bad";
|
||||
msg.textContent = `Erreur : ${err.message}`;
|
||||
}
|
||||
});
|
||||
|
||||
function startEnroll(count) {
|
||||
show("#v-enroll");
|
||||
renderDots(count);
|
||||
startScanner();
|
||||
}
|
||||
|
||||
|
||||
function sel(qid) {
|
||||
if (!selections.has(qid)) selections.set(qid, { set: new Set(), blank: false });
|
||||
return selections.get(qid);
|
||||
}
|
||||
|
||||
function renderVote(st) {
|
||||
lastState = st;
|
||||
const box = $("#questions");
|
||||
box.replaceChildren();
|
||||
let pending = 0;
|
||||
const todo = (q) => q.state === "open" && !q.voted;
|
||||
for (const q of [...st.questions.filter(todo), ...st.questions.filter((q) => !todo(q))]) {
|
||||
if (todo(q)) pending++;
|
||||
box.append(questionCard(q));
|
||||
}
|
||||
$("#waiting").hidden = pending > 0;
|
||||
}
|
||||
|
||||
function questionCard(q) {
|
||||
const card = h("article", { class: `vq ${q.state === "open" && !q.voted ? "open" : ""}` });
|
||||
card.append(h("div", { class: "q-text" }, q.text));
|
||||
if (q.state === "closed") {
|
||||
card.append(h("span", { class: "badge public" }, "Résultats"), resultsView(q));
|
||||
return card;
|
||||
}
|
||||
if (q.voted) {
|
||||
card.append(h("p", { class: "voted" }, "Vote enregistré"));
|
||||
return card;
|
||||
}
|
||||
const s = sel(q.id);
|
||||
const multi = q.kind === "multi";
|
||||
const group = h("div", { role: multi ? "group" : "radiogroup", "aria-label": q.text });
|
||||
q.options.forEach((label, i) => {
|
||||
group.append(h("button", {
|
||||
type: "button", class: `choice ${multi ? "multi" : ""}`, role: multi ? "checkbox" : "radio",
|
||||
"aria-checked": String(s.set.has(i)),
|
||||
onclick: () => {
|
||||
s.blank = false;
|
||||
if (multi) {
|
||||
if (s.set.has(i)) s.set.delete(i);
|
||||
else if (s.set.size < q.max_choices) s.set.add(i);
|
||||
else toast(`${q.max_choices} choix maximum`, "bad");
|
||||
} else {
|
||||
s.set = new Set([i]);
|
||||
}
|
||||
renderVote(lastState);
|
||||
},
|
||||
}, h("span", { class: "mark" }), label));
|
||||
});
|
||||
if (q.allow_blank) {
|
||||
group.append(h("button", {
|
||||
type: "button", class: "choice blank", role: multi ? "checkbox" : "radio", "aria-checked": String(s.blank),
|
||||
onclick: () => { s.blank = !s.blank; s.set.clear(); renderVote(lastState); },
|
||||
}, h("span", { class: "mark" }), "Vote blanc"));
|
||||
}
|
||||
card.append(group);
|
||||
if (multi) card.append(h("p", { class: "hint" }, `${q.max_choices} choix max`));
|
||||
const ready = s.blank || s.set.size > 0;
|
||||
card.append(h("button", { class: "go block", type: "button", disabled: !ready, onclick: () => confirmVote(q) }, "Voter"));
|
||||
return card;
|
||||
}
|
||||
|
||||
async function confirmVote(q) {
|
||||
const s = sel(q.id);
|
||||
const choices = [...s.set].sort((a, b) => a - b);
|
||||
$("#confirm-q").textContent = q.text;
|
||||
$("#confirm-choices").replaceChildren(...(s.blank ? [h("li", {}, "Vote blanc")] : choices.map((i) => h("li", {}, q.options[i]))));
|
||||
const dlg = $("#confirm");
|
||||
dlg.returnValue = "";
|
||||
dlg.showModal();
|
||||
await new Promise((res) => dlg.addEventListener("close", res, { once: true }));
|
||||
if (dlg.returnValue !== "ok") return;
|
||||
try {
|
||||
await api("POST", `${apiBase}/vote`, { question_id: q.id, choices: s.blank ? [] : choices });
|
||||
selections.delete(q.id);
|
||||
toast("Vote enregistré", "ok");
|
||||
navigator.vibrate?.(60);
|
||||
} catch (e) {
|
||||
const m = { already_voted: "Déjà voté.", not_open: "Vote clos.", not_enrolled: "Appareil non inscrit." };
|
||||
toast(m[e.code] || `Erreur : ${e.message}`, "bad");
|
||||
}
|
||||
}
|
||||
|
||||
function connect() {
|
||||
if (socket) return;
|
||||
$("#conn").hidden = false;
|
||||
socket = liveSocket(`/ws/${pid}/voter`, {
|
||||
onMessage(msg) {
|
||||
if (msg.type === "state") {
|
||||
// identical state -> keep the dom, a rebuild under the finger eats the tap
|
||||
const j = JSON.stringify(msg);
|
||||
if (j === lastJson) return;
|
||||
lastJson = j;
|
||||
show("#v-vote");
|
||||
$("#title").textContent = msg.title;
|
||||
renderVote(msg);
|
||||
}
|
||||
else if (msg.type === "not_enrolled") { socket?.close(); socket = null; boot(); }
|
||||
},
|
||||
onStatus(s) {
|
||||
const c = $("#conn");
|
||||
c.className = `conn ${s === "online" ? "online" : "offline"}`;
|
||||
c.textContent = s === "online" ? "en direct" : "reconnexion…";
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
async function boot() {
|
||||
let me;
|
||||
try { me = await api("GET", `${apiBase}/me`); }
|
||||
catch (e) {
|
||||
show("#v-blocked");
|
||||
$("#blocked-msg").textContent = e.status === 404 ? "Scrutin introuvable." : "Serveur injoignable.";
|
||||
return;
|
||||
}
|
||||
$("#title").textContent = me.title;
|
||||
document.title = me.title;
|
||||
if (me.enrolled) {
|
||||
lsSet(DONE_KEY, "1");
|
||||
show("#v-vote");
|
||||
lastJson = JSON.stringify(me);
|
||||
renderVote(me);
|
||||
connect();
|
||||
return;
|
||||
}
|
||||
if (lsGet(DONE_KEY)) {
|
||||
return block("Appareil déjà inscrit à ce scrutin (accès perdu). Voyez l'organisateur.");
|
||||
}
|
||||
if (!me.enrollment_open) return block("Inscriptions closes.");
|
||||
required = me.scans_required;
|
||||
if (me.need_code) { show("#v-code"); return; }
|
||||
startEnroll(me.count);
|
||||
if (firstToken && !sent.has(firstToken)) { sent.add(firstToken); submitToken(firstToken); }
|
||||
}
|
||||
|
||||
boot();
|
||||
// a socket can look open after sleep while being dead, so refetch on wake
|
||||
document.addEventListener("visibilitychange", () => {
|
||||
if (document.visibilityState === "visible" && lastState) boot();
|
||||
});
|
||||
Reference in New Issue
Block a user