import { $, h, api, pollId, liveSocket, resultsView, toast, ring, icon } 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'inscriptions 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" }, 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; 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.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."); 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(); });