Wire the ring code into the app: per-poll code style (ring default for new polls), projector rings + entry qr, voter camera loop, both token formats

This commit is contained in:
2026-11-16 18:39:58 +01:00
parent d29ca34b9a
commit 1b5bdf9d00
13 changed files with 250 additions and 51 deletions
+2
View File
@@ -76,6 +76,7 @@ function renderSettings(p) {
if (active !== $("#s-expected")) $("#s-expected").value = p.expected ?? "";
if (active !== $("#s-max")) $("#s-max").value = p.max_voters ?? "";
if (active !== $("#s-vote-scans")) $("#s-vote-scans").value = String(p.vote_scans);
if (active !== $("#s-code-style")) $("#s-code-style").value = p.code_style;
$("#s-code").checked = p.require_code;
$("#access-row").hidden = !p.require_code && !state.codes.access.total;
const sum = (c, none) => (c.total ? `${c.used} utilisé${c.used > 1 ? "s" : ""} sur ${c.total}` : none);
@@ -203,6 +204,7 @@ const SETTINGS = {
"#s-max": (el) => ({ max_voters: intOrNull(el.value) }),
"#s-code": (el) => ({ require_code: el.checked }),
"#s-vote-scans": (el) => ({ vote_scans: +el.value }),
"#s-code-style": (el) => ({ code_style: el.value }),
};
for (const [sel, build] of Object.entries(SETTINGS)) {
$(sel).addEventListener("change", async (e) => {
+44 -3
View File
@@ -1,10 +1,13 @@
import { $, h, pollId, takeKey, liveSocket, drawQR, resultsView, fill, pct } from "./common.js";
import { render as drawRing, DISC } from "./ringcode.js";
const pid = pollId();
const key = takeKey(`rv_screen_${pid}`);
let st = null;
let qr = null;
let qr = null; // current code message, qr or ring
let raf = 0;
let entry = null;
let prevBits = null, switchedAt = 0;
function layout() {
if (!st) return;
@@ -15,8 +18,13 @@ function layout() {
$("#focus").hidden = !focus;
$("#idle").hidden = qrOn || !!focus;
$(".s-main").classList.toggle("split", qrOn && !!focus);
$("#qr-title").textContent = st.enrollment_open ? "Inscription" : "Scannez pour voter";
const ring = st.code_style === "ring";
$("#qr-title").textContent = st.enrollment_open ? "Inscription" : ring ? "Visez le cercle pour voter" : "Scannez pour voter";
$("#qr-steps").hidden = !st.enrollment_open;
// rings can't be opened by the camera app, so a small fixed qr leads to the page
$("#step1").textContent = ring ? "Ouvrez la page de vote" : "Scannez ce code";
$("#entry").hidden = !(ring && st.enrollment_open && entry);
$(".qr-wrap").classList.toggle("ring", ring);
}
function render() {
@@ -50,12 +58,33 @@ function render() {
}
function paintQR() {
if (!qr) return;
if (!qr || qr.type !== "qr") return;
const c = $("#qr");
const px = Math.min(c.clientWidth || 600, c.clientHeight || 600) * (window.devicePixelRatio || 1);
drawQR(c, qr.modules, px);
}
function paintEntry() {
if (!entry) return;
drawQR($("#entry-qr"), entry.modules, 220 * (window.devicePixelRatio || 1));
$("#entry-url").textContent = entry.url.replace(/^https?:\/\//, "");
}
// rings rotate continuously (one turn every 45 s); changed dashes cross-fade when the code switches
function ringLoop(t) {
if (!qr || qr.type !== "ring") return;
const c = $("#qr"), dpr = window.devicePixelRatio || 1;
const size = Math.round(Math.min(c.clientWidth || 600, c.clientHeight || 600) * dpr);
if (c.width !== size) { c.width = c.height = size; }
const ctx = c.getContext("2d");
ctx.clearRect(0, 0, size, size);
const fadeMs = Math.min(220, qr.interval_ms * 0.25);
const k = prevBits ? Math.min(1, (t - switchedAt) / fadeMs) : 1;
drawRing(ctx, size / 2, size / 2, (size / 2) / DISC * 0.98, (t / 1000) * (2 * Math.PI / 45), qr.bits, t / 1000,
prevBits ? { from: prevBits, k } : null);
requestAnimationFrame(ringLoop);
}
function animateTick() {
cancelAnimationFrame(raf);
const bar = $("#tick-bar");
@@ -80,6 +109,18 @@ liveSocket(`/ws/${pid}/screen`, {
st = msg;
if (!st.enrollment_open && !st.presence) qr = null;
render();
} else if (msg.type === "entry") {
entry = msg;
paintEntry();
if (st) layout();
} else if (msg.type === "ring") {
skew = Date.now() - msg.slot * msg.interval_ms;
const wasRing = qr && qr.type === "ring";
prevBits = wasRing ? qr.bits : null;
switchedAt = performance.now();
qr = msg;
if (!wasRing) requestAnimationFrame(ringLoop);
animateTick();
} 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;
+53 -21
View File
@@ -1,4 +1,5 @@
import { $, h, api, pollId, liveSocket, resultsView, toast, ring, icon } from "./common.js";
import { decodeFrame, grayOf } from "./ringcode.js";
const pid = pollId();
const DONE_KEY = `rv_done_${pid}`;
@@ -15,6 +16,8 @@ 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) {
@@ -50,7 +53,7 @@ async function startScanner() {
return;
}
$("#cam-box").hidden = false;
scanner = makeScanner($("#video"), onScan);
scanner = makeScanner($("#video"), onScan, () => scanMsg("QR d'un autre scrutin.", "bad"));
try {
await scanner.start();
$("#start-cam").hidden = true;
@@ -66,18 +69,51 @@ async function startScanner() {
}
}
function makeScanner(video, onData) {
return new window.QrScanner(video, (r) => onData(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) };
// 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", { willReadFrequently: true });
async function loop() {
if (!running) return;
const t0 = performance.now();
if (video.readyState >= 2 && video.videoWidth) {
// 960 px is plenty 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);
try {
if (codeStyle === "ring") {
const d = decodeFrame(grayOf(ctx.getImageData(0, 0, canvas.width, canvas.height)));
if (d.token) onToken(d.token);
} else {
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)));
}
return {
async start() {
stream = await navigator.mediaDevices.getUserMedia({
audio: false, video: { facingMode: { ideal: "environment" }, width: { ideal: 1280 }, height: { ideal: 720 } },
});
video.srcObject = stream;
await video.play();
running = true;
loop();
},
});
stop() {
running = false;
stream?.getTracks().forEach((t) => t.stop());
video.srcObject = null;
},
destroy() {},
};
}
// token of a code shown for this poll, null for anything else
@@ -97,12 +133,7 @@ function stopScanner() {
$("#cam-box").hidden = true;
}
function onScan(data) {
const token = tokenOf(data);
if (!token) {
scanMsg("QR d'un autre scrutin.", "bad");
return;
}
function onScan(token) {
if (sent.has(token)) return;
sent.add(token);
submitToken(token);
@@ -202,6 +233,7 @@ function sel(qid) {
function renderVote(st) {
lastState = st;
if (st.code_style) codeStyle = st.code_style;
const box = $("#questions");
box.replaceChildren();
let pending = 0;
@@ -293,9 +325,8 @@ function collectPresence(n) {
paint();
$("#p-msg").textContent = "";
dlg.showModal();
const sc = makeScanner($("#p-video"), (data) => {
const t = tokenOf(data);
if (!t || got.includes(t)) return;
const sc = makeScanner($("#p-video"), (t) => {
if (got.includes(t)) return;
got.push(t);
paint();
navigator.vibrate?.(15);
@@ -366,6 +397,7 @@ async function boot() {
}
if (!me.enrollment_open) return block("Inscriptions closes.");
required = me.scans_required;
codeStyle = me.code_style || "qr";
if (me.need_code) { show("#v-code"); return; }
startEnroll(me.count);
if (firstToken && !sent.has(firstToken)) { sent.add(firstToken); submitToken(firstToken); }