Files
rotatyvote/static/js/vote.js
T

682 lines
25 KiB
JavaScript
Raw 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.
import { $, h, api, pollId, liveSocket, resultsView, toast, paintRing, icon } from "./common.js";
import { makeRingScanner } from "./ringscan.js";
const pid = pollId();
const DONE_KEY = `rv_done_${pid}`;
const apiBase = `/api/v/${pid}`;
const PENDING_KEY = `rv_pending_${pid}`;
// the camera app redirect leaves a one-time claim (or why there is none) in the hash. off the url bar at once
const hash = new URLSearchParams(location.hash.slice(1));
const claim = hash.get("c"), camExpired = hash.get("cam") === "expired";
if (location.hash) history.replaceState(null, "", location.pathname);
// a camera app scan covers votes for a few seconds (server PASS_HOLD_MS, minus the round trip)
let passUntil = 0;
let presenceFor = null;
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 codeStyle = "qr"; // what the projector shows: rotating qr or ring code
let qrEngine = null;
let lastJson = "";
function show(id) {
for (const s of ["#v-loading", "#v-enroll", "#v-code", "#v-rescue", "#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 */ } }
// the segment fill in app.css takes .5 s, plus a beat to see the ring complete
const FILL_MS = 650;
let landing = false;
function renderDots(n) {
const box = $("#dots");
paintRing(box, 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"}`;
}
// the camera app way: a quiet line under a working scanner, step by step without one.
// people are already on the page, so it has to say why they leave it and what happens after
function camAlt(el, solo, vote = false) {
el.classList.toggle("solo", solo);
if (!solo) {
el.replaceChildren(icon("camera", 18), h("span", {}, "Ça ne marche pas ? Scannez le grand QR de l'écran avec l'appareil photo."));
return;
}
// the vote dialog has the heading in its own title
el.replaceChildren(icon("camera", 36), vote ? "" : h("b", {}, "Inscrivez-vous avec l'appareil photo"),
h("ol", {},
h("li", {}, "Quittez cette page et ouvrez l'appareil photo du téléphone."),
h("li", {}, "Scannez le grand QR de l'écran."),
h("li", {}, vote ? "Touchez le lien qui s'affiche. Votre vote part tout seul." : "Touchez le lien qui s'affiche. Vous êtes inscrit·e.")));
}
async function startScanner() {
if (scanner) return;
if (!window.isSecureContext) {
scanMsg("Caméra impossible sans HTTPS.", "bad");
return;
}
$("#cam-box").hidden = false;
scanner = makeScanner($("#video"), onScan, () => scanMsg("QR d'un autre scrutin.", "bad"));
try {
await scanner.start();
$("#start-cam").hidden = true;
$("#dots").hidden = false;
camAlt($("#enroll-alt"), false);
scanMsg("");
navigator.wakeLock?.request("screen").catch(() => {});
} catch (e) {
console.warn(e);
scanner.destroy();
scanner = null;
$("#cam-box").hidden = true;
// the camera app is the way now: the ring and a big retry button would only compete with it
$("#dots").hidden = true;
$("#start-cam").hidden = false;
$("#start-cam").className = "link";
$("#start-cam").textContent = "Réessayer la caméra";
scanMsg(camError(e), "bad");
camAlt($("#enroll-alt"), true);
}
}
// what blocked the camera. no settings walkthrough: the camera app path below works without them
function camError(e) {
switch (e && e.name) {
case "NotAllowedError":
case "SecurityError":
return "Ce navigateur n'a pas accès à la caméra.";
case "NotReadableError":
case "AbortError":
return "Caméra occupée ou bloquée par le téléphone.";
case "NotFoundError":
case "OverconstrainedError":
return "Aucune caméra trouvée.";
default:
return "Caméra indisponible.";
}
}
// own camera loop: decodes the ring code, or the classic qr through qr-scanner's engine.
// calls onToken(token) for every code of this poll it reads
function makeScanner(video, onToken, onOther) {
let stream = null, running = false;
const canvas = document.createElement("canvas"), ctx = canvas.getContext("2d");
const rings = makeRingScanner();
async function loop() {
if (!running) return;
const t0 = performance.now();
if (video.readyState >= 2 && video.videoWidth) {
try {
if (codeStyle === "ring") {
// reads a crop at sensor resolution: a far code keeps all its pixels
const ts = performance.now(), d = rings.scan(video, video.videoWidth, video.videoHeight);
if (d.token) onToken(d.token);
steer(d);
pace(performance.now() - ts);
} else {
// 960 px is plenty for a qr and keeps low-end phones near 7 fps
const k = Math.min(1, 960 / video.videoWidth);
canvas.width = Math.round(video.videoWidth * k);
canvas.height = Math.round(video.videoHeight * k);
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
qrEngine ||= await window.QrScanner.createQrEngine();
const r = await window.QrScanner.scanImage(canvas, { qrEngine, returnDetailedScanResult: true }).catch(() => null);
if (r) { const tok = tokenOf(r.data); if (tok) onToken(tok); else onOther?.(); }
}
} catch (e) { console.warn(e); }
}
// ~15 fps cap, saves battery on fast phones
setTimeout(loop, Math.max(0, 66 - (performance.now() - t0)));
}
const swap = h("button", { class: "cam-switch", type: "button", "aria-label": "Changer de caméra", hidden: true }, icon("swap", 20));
// sensor zoom, by hand only: an automatic one made the preview jump and shook too much on cheap phones.
// the far ring gets its pixels from the full sensor resolution instead (openCamera, ringscan)
const zoom = h("button", { class: "cam-zoom", type: "button", "aria-label": "Zoom", hidden: true }, "1×");
video.parentElement.append(swap, zoom);
let zs = null;
function setZoom(z) {
const track = stream?.getVideoTracks()[0];
if (!track || !zs) return;
zs.now = z;
zoom.textContent = `${(Math.round(z * 10) / 10).toLocaleString("fr-FR")}×`;
track.applyConstraints({ advanced: [{ zoom: z }] }).catch(() => { zs = null; zoom.hidden = true; });
}
// a slow phone reads few frames and misses codes: past ~300 ms a frame, drop the stream to 720p once
let slow = 0, frames = 0, dropped = false;
function pace(ms) {
slow = frames++ ? slow * 0.8 + ms * 0.2 : ms;
if (dropped || frames < 6 || slow < 300 || video.videoWidth * video.videoHeight <= 1280 * 720) return;
dropped = true;
stream?.getVideoTracks()[0]?.applyConstraints({ width: { ideal: 1280 }, height: { ideal: 720 } }).catch(() => {});
}
function steer(d) {
// people keep their seat between votes: a zoom that read the ring is where the next scan starts
if (zs && d.token) lsSet(ZOOM_KEY, String(zs.now));
}
async function attach(s) {
stream = s;
const track = s.getVideoTracks()[0];
// not every browser knows focusMode, those ignore it
track?.applyConstraints({ advanced: [{ focusMode: "continuous" }] }).catch(() => {});
const cap = track?.getCapabilities?.().zoom;
zs = cap && cap.max >= 1.5 ? { base: Math.max(1, cap.min), max: Math.min(cap.max, 3), now: Math.max(1, cap.min) } : null;
zoom.hidden = !zs;
zoom.textContent = "1×";
video.srcObject = s;
await video.play();
const saved = +lsGet(ZOOM_KEY);
if (zs && saved > zs.base) setZoom(Math.min(zs.max, saved));
}
zoom.onclick = () => {
if (!zs) return;
const steps = [zs.base, 2, 3].filter((z) => z >= zs.base && z <= zs.max);
setZoom(steps.find((z) => z > zs.now + 0.05) ?? zs.base);
};
swap.onclick = async () => {
const cams = rankCameras(await videoInputs());
if (cams.length < 2) return;
const cur = stream?.getVideoTracks()[0]?.getSettings().deviceId;
const next = cams[(cams.findIndex((d) => d.deviceId === cur) + 1) % cams.length];
stream?.getTracks().forEach((t) => t.stop());
try { await attach(await openCamera(next.deviceId)); lsSet(CAM_KEY, next.deviceId); }
catch { await attach(await openCamera(null)); }
};
return {
async start() {
const saved = lsGet(CAM_KEY);
let s = null;
if (saved) s = await openCamera(saved).catch(() => null);
s ||= await openCamera(null);
// some browsers ignore facingMode or hand over the ultra wide: switch to the main back lens when labels say so
const track = s.getVideoTracks()[0], cams = await videoInputs();
if (!saved && cams.length > 1 && (track.getSettings().facingMode === "user" || !isMainBack(track.label))) {
const best = rankCameras(cams)[0];
if (best && best.deviceId !== track.getSettings().deviceId) {
s.getTracks().forEach((t) => t.stop());
s = await openCamera(best.deviceId).catch(() => null) || await openCamera(null);
}
}
swap.hidden = cams.length < 2;
await attach(s);
running = true;
loop();
},
stop() {
running = false;
stream?.getTracks().forEach((t) => t.stop());
video.srcObject = null;
},
destroy() { swap.remove(); zoom.remove(); },
};
}
const CAM_KEY = "rv_cam";
const ZOOM_KEY = `rv_zoom_${pid}`;
const FRONT = /front|user|avant|facetime|selfie/i, ODD = /ultra|wide|grand.angle|macro|tele|télé|depth|infra|dual|triple|double/i, BACK = /back|rear|arri[eè]re|environment/i;
function openCamera(deviceId) {
// rings from the back of a room are a few dozen pixels wide at 720p. 4k was tried: a mid-range android took
// it and fell to one frame every 2 s, so 1080p, and 720p on phones too slow for that (pace)
const [w, h] = codeStyle === "ring" ? [1920, 1080] : [1280, 720];
const base = { width: { ideal: w }, height: { ideal: h } };
return navigator.mediaDevices.getUserMedia({
audio: false, video: deviceId ? { ...base, deviceId: { exact: deviceId } } : { ...base, facingMode: { ideal: "environment" } },
});
}
async function videoInputs() {
try { return (await navigator.mediaDevices.enumerateDevices()).filter((d) => d.kind === "videoinput"); }
catch { return []; }
}
// without a label we can't tell, so trust what facingMode gave
const isMainBack = (label) => !label || (!FRONT.test(label) && !ODD.test(label));
// main back lens first, other back lenses next, front last. android lists its main back camera first
function rankCameras(cams) {
const score = (d) => (FRONT.test(d.label) ? -4 : 0) + (ODD.test(d.label) ? -2 : 0) + (BACK.test(d.label) ? 1 : 0);
return cams.map((d, i) => ({ d, i, s: score(d) })).sort((a, b) => b.s - a.s || a.i - b.i).map((x) => x.d);
}
// token of a code shown for this poll, null for anything else
// the classic qr is the camera app code: /V/<poll>/<code>, upper case
function tokenOf(data) {
let u;
try { u = new URL(data); } catch { return null; }
const [v, id, tok] = u.pathname.split("/").filter(Boolean);
if (v?.toLowerCase() !== "v" || id?.toLowerCase() !== pid || !tok) return null;
return tok;
}
function stopScanner() {
if (!scanner) return;
scanner.stop();
scanner.destroy();
scanner = null;
$("#cam-box").hidden = true;
}
function onScan(token) {
if (landing || sent.has(token)) return;
sent.add(token);
if (codeStyle === "qr") redeem({ token }).then(afterPass);
else submitToken(token);
}
async function redeem(body) {
try { return await api("POST", `${apiBase}/pass`, body); }
catch { return { status: "network" }; }
}
function pendingVote() {
let p;
try { p = JSON.parse(lsGet(PENDING_KEY)); } catch { return null; }
return p && Date.now() - p.at < 5 * 60e3 ? p : null;
}
// what one camera app scan gave: enrolled, votes covered for a moment, or why not
async function afterPass(r) {
switch (r.status) {
case "enrolled":
passUntil = Date.now() + 8000;
enrolled();
break;
case "pass": {
passUntil = Date.now() + (r.hold_ms || 10000) - 1500;
// the choice made before going to the camera app goes through on its own
const p = pendingVote();
const q = p && lastState?.questions.find((x) => x.id === p.qid && x.state === "open" && !x.voted);
if (q) castVote(q, p.choices);
break;
}
case "need_code":
stopScanner();
show("#v-code");
break;
case "closed":
if (!lastState) block("Inscriptions closes. Inscrit·e dans un autre navigateur ? Revenez-y pour voter.");
break;
case "full":
block("Nombre maximal d'inscriptions atteint.");
break;
case "expired":
toast("QR expiré, scannez-le à nouveau.", "bad");
break;
}
}
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":
// the 5th code answers "enrolled" straight away: fill the last segment and let it land first
if (landing) break;
landing = true;
renderDots(required);
setTimeout(() => { landing = false; enrolled(); }, FILL_MS);
break;
case "closed":
block("Inscriptions closes.");
break;
case "full":
block("Nombre maximal d'inscriptions atteint.");
break;
}
}
function enrolled() {
stopScanner();
lsSet(DONE_KEY, "1");
navigator.vibrate?.([40, 60, 40]);
celebrate("Inscription validée");
boot();
}
// the projector's center mark with its check, drawn in, held a moment, then gone
const MARK_NS = "http://www.w3.org/2000/svg";
function celebrate(text) {
const svg = document.createElementNS(MARK_NS, "svg");
svg.setAttribute("viewBox", "0 0 32 32");
svg.setAttribute("aria-hidden", "true");
const g = document.createElementNS(MARK_NS, "g");
g.setAttribute("transform", "rotate(-90 16 16)");
for (const [stroke, dash] of [["currentColor", "4.52 7"], ["#ffcc00", "4.52 64.6"]]) {
const c = document.createElementNS(MARK_NS, "circle");
for (const [k, v] of Object.entries({ cx: 16, cy: 16, r: 11, fill: "none", stroke, "stroke-width": 5,
"stroke-linecap": "round", "stroke-dasharray": dash, "stroke-dashoffset": -3.5 })) c.setAttribute(k, v);
g.append(c);
}
const tick = document.createElementNS(MARK_NS, "path");
for (const [k, v] of Object.entries({ d: "M12.8 16.15l2.3 2.3 4.25-4.75", fill: "none", stroke: "currentColor", "stroke-width": 2.4,
"stroke-linecap": "round", "stroke-linejoin": "round", pathLength: 1, class: "tick" })) tick.setAttribute(k, v);
svg.append(g, tick);
const el = h("div", { class: "celebrate", role: "status" }, svg, h("p", {}, text));
document.body.append(el);
setTimeout(() => el.classList.add("out"), 1300);
setTimeout(() => el.remove(), 1700);
}
$("#start-cam").addEventListener("click", startScanner);
$("#no-cam").addEventListener("click", () => { stopScanner(); show("#v-rescue"); $("#rescue-code").focus(); });
$("#rescue-back").addEventListener("click", () => startEnroll(0));
$("#rescue-form").addEventListener("submit", async (e) => {
e.preventDefault();
const msg = $("#rescue-msg");
try {
const r = await api("POST", `${apiBase}/rescue`, { code: $("#rescue-code").value });
if (r.status === "enrolled") return enrolled();
msg.className = "scan-msg bad";
msg.textContent = { bad_code: "Code invalide ou déjà utilisé.", closed: "Inscriptions closes.", full: "Nombre maximal d'inscriptions atteint." }[r.status] || r.status;
} catch (err) {
msg.className = "scan-msg bad";
msg.textContent = `Erreur : ${err.message}`;
}
});
$("#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;
// voted from the tab the camera app opened: nothing left to scan here
if (presenceFor && st.questions.some((q) => q.id === presenceFor && q.voted)) $("#presence").close();
if (st.code_style) codeStyle = st.code_style;
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" }, h("span", { class: "voted-mark" }, icon("check", 16)), "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;
castVote(q, s.blank ? [] : choices);
}
async function castVote(q, choices, retried = false) {
let presence;
if (lastState.vote_scans > 0 && Date.now() > passUntil) {
// kept for the tab the camera app opens, which sends it on its own
lsSet(PENDING_KEY, JSON.stringify({ qid: q.id, choices, at: Date.now() }));
presence = await collectPresence(lastState.vote_scans, q.id);
// cancelled (or voted from the other tab): a later scan must not cast a choice left behind
if (!presence) {
try { localStorage.removeItem(PENDING_KEY); } catch { /* private mode */ }
return;
}
}
try {
await api("POST", `${apiBase}/vote`, { question_id: q.id, choices, presence });
try { localStorage.removeItem(PENDING_KEY); } catch { /* private mode */ }
selections.delete(q.id);
celebrate("Vote enregistré");
navigator.vibrate?.(60);
} catch (e) {
// the camera app scan ran out on the server side: scan again
if (e.code === "presence_required" && !presence && !retried) {
passUntil = 0;
return castVote(q, choices, true);
}
const m = { already_voted: "Déjà voté.", not_open: "Vote clos.", not_enrolled: "Appareil non inscrit.",
presence_required: "Scan expiré, revotez en visant l'écran." };
toast(m[e.code] || `Erreur : ${e.message}`, "bad");
}
}
// proof of presence at vote time: read n distinct codes off the projector, resolve with them
// (or null if cancelled). the server checks freshness
function collectPresence(n, qid) {
const dlg = $("#presence");
const got = [];
// the classic qr is the camera app code: one read is enough, the server then covers the vote
if (codeStyle === "qr") n = 1;
const paint = () => paintRing($("#p-ring"), got.length, n, 120);
paint();
$("#p-title").textContent = codeStyle === "ring" ? "Visez le cercle" : "Scannez le QR";
$("#p-scan").hidden = false;
$("#p-msg").textContent = "";
camAlt($("#p-alt"), false);
presenceFor = qid;
dlg.showModal();
const seenAt = new Map(), tried = new Set();
const sc = makeScanner($("#p-video"), async (t) => {
if (got.length >= n || got.includes(t)) return;
if (codeStyle === "qr") {
if (tried.has(t)) return;
tried.add(t);
const r = await redeem({ token: t });
if (r.status === "pass" && !got.length) { got.push(t); paint(); setTimeout(() => finish([]), FILL_MS); }
return;
}
// the server takes codes spread over ~8 s + n intervals: on a slow phone the oldest ones lapse, drop them
const now = performance.now();
while (got.length && now - seenAt.get(got[0]) > 9000) got.shift();
got.push(t);
seenAt.set(t, now);
paint();
navigator.vibrate?.(15);
if (got.length >= n) setTimeout(() => finish(got), FILL_MS);
});
let done, finished = false;
const result = new Promise((res) => { done = res; });
function finish(value) {
if (finished) return;
finished = true;
presenceFor = null;
sc.stop();
sc.destroy();
if (dlg.open) dlg.close();
done(value);
}
dlg.addEventListener("close", () => finish(null), { once: true });
// no camera here: the camera app opens a new tab that sends the kept choice
sc.start().catch((e) => {
$("#p-title").textContent = "Validez avec l'appareil photo";
$("#p-msg").textContent = camError(e);
$("#p-scan").hidden = true;
camAlt($("#p-alt"), true, true);
});
return result;
}
$("#p-cancel").addEventListener("click", () => $("#presence").close());
function connect() {
if (socket) return;
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.hidden = s === "online";
c.className = "conn offline";
c.textContent = "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). Adressez-vous à l'équipe organisatrice.");
}
if (!me.enrollment_open) return block("Inscriptions closes.");
codeStyle = me.code_style || "qr";
// the classic qr is read once (camera app code), the ring several times
required = codeStyle === "qr" ? 1 : me.scans_required;
if (me.need_code) { show("#v-code"); return; }
startEnroll(me.count);
}
async function start() {
// the claim goes first: it may enroll this phone before the page asks who it is
const r = claim ? await redeem({ claim }) : null;
if (r?.status === "enrolled") { lsSet(DONE_KEY, "1"); celebrate("Inscription validée"); passUntil = Date.now() + 8000; }
await boot();
if (r && r.status !== "enrolled") afterPass(r);
else if (camExpired) afterPass({ status: "expired" });
}
camAlt($("#enroll-alt"), false);
start();
// a socket can look open after sleep while being dead, so refetch on wake
document.addEventListener("visibilitychange", () => {
if (document.visibilityState === "visible" && lastState) boot();
});