Camera app scan: the big qr rotates every 3 s and one scan with the phone's camera app enrolls or validates a vote (10 s), for browsers with the camera blocked; qr stays big beside the ring during a vote, step by step help on the phone

This commit is contained in:
2026-11-18 00:54:12 +01:00
parent d945c801f7
commit a30618e74c
11 changed files with 436 additions and 125 deletions
+1 -1
View File
@@ -36,7 +36,7 @@ body.entry-big { --dock-qr: clamp(180px, min(58vh, 34vw), 640px); }
body.entry-big .entry { top: 50%; bottom: auto; right: max(4vw, calc((50vw - var(--dock-qr)) / 2 - 2vw)); translate: 0 -46%; padding: 2vh; gap: 1.2vh; }
body.entry-big .entry div { font-size: clamp(.9rem, 1.4vw, 1.6rem); }
body.entry-big .s-main:not(.split) .s-steps { visibility: hidden; }
body.entry-q-on { --dock-qr: clamp(160px, min(46vh, 30vw), 520px); }
body.entry-q-on { --dock-qr: clamp(160px, min(52vh, 32vw), 580px); }
/* width 0 + min-width 100%: a long question wraps to the qr's width instead of widening the block */
.entry-q { display: grid; gap: .6vh; padding-bottom: 1vh; margin-bottom: .4vh; border-bottom: 2px solid var(--bg); width: 0; min-width: 100%; }
.entry-q b { font: 700 clamp(1rem, 1.7vw, 2rem) var(--round); color: var(--ink); line-height: 1.15; }
+10
View File
@@ -82,3 +82,13 @@ dialog .actions button { flex: 1; }
border: 0; color: #fff; background: rgba(20, 22, 36, .55); font: 700 .95rem var(--round);
-webkit-backdrop-filter: blur(6px); backdrop-filter: blur(6px);
}
/* the phone's own camera app reads the projector qr when the browser can't use the camera */
.cam-alt { display: flex; align-items: center; justify-content: center; gap: 8px; margin: 0 0 12px; font-size: .9rem; color: var(--ink-2); text-align: left; }
.cam-alt .icon { flex: none; }
.cam-alt.solo { flex-direction: column; gap: 12px; margin: 4px 0 18px; color: var(--ink); }
.cam-alt.solo .icon { width: 64px; height: 64px; padding: 14px; border-radius: 50%; background: var(--mark); stroke-width: 1.8; }
.cam-alt.solo b { font: 700 1.25rem/1.25 var(--round); text-align: center; }
.cam-alt.solo ol { list-style: none; counter-reset: st; padding: 0; margin: 0; display: grid; gap: 10px; font: 600 1rem/1.35 var(--round); }
.cam-alt.solo li { counter-increment: st; display: grid; grid-template-columns: 28px 1fr; gap: 10px; align-items: start; }
.cam-alt.solo li::before { content: counter(st); display: grid; place-items: center; width: 28px; height: 28px; border-radius: 50%; background: var(--ink); color: var(--surface); font-weight: 700; font-size: .9rem; }
+2
View File
@@ -165,6 +165,8 @@ 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) {
+18 -12
View File
@@ -52,10 +52,14 @@ function layout() {
// qr stays up while enrolling, and during a vote that needs a presence scan
const qrOn = st.enrollment_open || st.presence;
const ring = st.code_style === "ring";
const entryOn = !!(ring && st.enrollment_open && entry);
// a closed vote whose results aren't shown has nothing to say: with the big entry qr on, it steps aside
// the camera app code: enrolls, and proves presence for a vote, so it stays up whenever the ring does
const entryOn = !!(ring && qrOn && entry);
// with the big qr on, a vote waiting for scans (or closed with nothing to show) moves above it
const f = st.focus, idleVote = f && f.state === "closed" && !f.results;
const focus = idleVote && entryOn && st.entry_big ? null : f;
// an upright screen has no room for the question above the qr (.entry-q hidden): it keeps its own block
const openVote = f && f.state === "open" && st.presence && !matchMedia("(max-aspect-ratio: 1/1)").matches;
const big = entryOn && st.entry_big && (!f || idleVote || openVote);
const focus = big ? null : f;
reveal($("#enroll"), qrOn);
reveal($("#focus"), !!focus);
reveal($("#idle"), !qrOn && !focus);
@@ -64,22 +68,24 @@ function layout() {
// a vote waiting for presence scans takes the title, even while late arrivals can still enroll
$("#qr-title").textContent = st.presence || !st.enrollment_open ? (ring ? "Visez le cercle pour voter" : "Scannez pour voter") : "Inscription";
$("#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";
$("#step1").textContent = ring ? "Scannez le QR avec l'appareil photo" : "Scannez avec l'appareil photo";
$("#step2").hidden = !ring;
reveal($("#entry"), entryOn);
document.body.classList.toggle("has-entry", entryOn);
// big entry qr next to the ring (start of a meeting, between votes), back to the corner while a question is up
const big = entryOn && st.entry_big && !focus;
document.body.classList.toggle("entry-big", big);
// the closed vote it replaced stays readable above the qr: question and ballot count
const showQ = big && !!idleVote;
const showQ = big && !!f;
document.body.classList.toggle("entry-q-on", showQ);
$("#entry-q").hidden = !showQ;
if (showQ) {
$("#entry-q-text").textContent = f.text;
$("#entry-q-count").textContent = `Vote clos, ${f.participants} bulletin${f.participants > 1 ? "s" : ""}`;
if (openVote) {
const all = f.participants + (f.extra_ballots || 0);
$("#entry-q-count").textContent = `${all} vote${all > 1 ? "s" : ""} sur ${st.voters + (f.extra_ballots || 0)}`;
} else {
$("#entry-q-count").textContent = `Vote clos, ${f.participants} bulletin${f.participants > 1 ? "s" : ""}`;
}
}
$("#entry-hint").textContent = big ? "Scannez ici, puis visez le cercle" : "Pas encore sur la page ?";
$("#entry-hint").textContent = "Scannez avec l'appareil photo";
$(".qr-wrap").classList.toggle("ring", ring);
flip(entryEl, before);
}
@@ -178,7 +184,7 @@ function animateTick() {
}
let skew = 0;
window.addEventListener("resize", paintQR);
window.addEventListener("resize", () => { paintQR(); layout(); });
$("#fs").addEventListener("click", () => document.documentElement.requestFullscreen?.());
+143 -29
View File
@@ -5,9 +5,15 @@ 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));
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;
@@ -50,6 +56,22 @@ function scanMsg(text, kind = "") {
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) {
@@ -61,6 +83,8 @@ async function startScanner() {
try {
await scanner.start();
$("#start-cam").hidden = true;
$("#dots").hidden = false;
camAlt($("#enroll-alt"), false);
scanMsg("");
navigator.wakeLock?.request("screen").catch(() => {});
} catch (e) {
@@ -68,31 +92,30 @@ async function startScanner() {
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, and where to unblock it on this phone. the browser only tells the kind of failure
// what blocked the camera. no settings walkthrough: the camera app path below works without them
function camError(e) {
const ios = /iPhone|iPad|iPod/.test(navigator.userAgent) || (navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1);
const android = /Android/.test(navigator.userAgent);
switch (e && e.name) {
case "NotAllowedError":
case "SecurityError":
return ios
? "Accès à la caméra refusé. Touchez « aA » dans la barre d'adresse, puis Réglages du site web, Caméra, Autoriser. Si rien ne change, ouvrez Réglages, puis Safari, puis Caméra."
: android
? "Accès à la caméra refusé. Touchez le cadenas à gauche de l'adresse, puis Autorisations, Caméra. Vérifiez aussi l'accès à la caméra dans les réglages de confidentialité du téléphone."
: "Accès à la caméra refusé. Autorisez-la dans les réglages du navigateur pour ce site, puis réessayez.";
return "Ce navigateur n'a pas accès à la caméra.";
case "NotReadableError":
case "AbortError":
return "La caméra est bloquée par le téléphone. Fermez les autres applis qui l'utilisent, ou réactivez l'accès à la caméra dans les réglages de confidentialité.";
return "Caméra occupée ou bloquée par le téléphone.";
case "NotFoundError":
case "OverconstrainedError":
return "Aucune caméra trouvée sur cet appareil.";
return "Aucune caméra trouvée.";
default:
return "Caméra indisponible. Autorisez-la puis réessayez.";
return "Caméra indisponible.";
}
}
@@ -239,12 +262,13 @@ function rankCameras(cams) {
}
// 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 parts = u.pathname.split("/").filter(Boolean);
if (parts[0] !== "v" || parts[1] !== pid) return null;
return decodeURIComponent(u.hash.slice(1)) || null;
const [v, id, tok] = u.pathname.split("/").filter(Boolean);
if (v?.toLowerCase() !== "v" || id?.toLowerCase() !== pid || !tok) return null;
return tok;
}
function stopScanner() {
@@ -258,7 +282,50 @@ function stopScanner() {
function onScan(token) {
if (landing || sent.has(token)) return;
sent.add(token);
submitToken(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) {
@@ -384,6 +451,8 @@ function sel(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();
@@ -450,17 +519,33 @@ async function confirmVote(q) {
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) {
presence = await collectPresence(lastState.vote_scans);
if (!presence) return;
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: s.blank ? [] : choices, presence });
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");
@@ -469,16 +554,29 @@ async function confirmVote(q) {
// 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) {
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();
const sc = makeScanner($("#p-video"), (t) => {
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();
@@ -493,14 +591,20 @@ function collectPresence(n) {
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 at vote time: the desk can still count this vote by hand (votes en plus)
sc.start().catch((e) => { $("#p-msg").textContent = `${camError(e)} Sinon, signalez-vous à la tribune.`; });
// 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;
}
@@ -553,14 +657,24 @@ async function boot() {
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;
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);
if (firstToken && !sent.has(firstToken)) { sent.add(firstToken); submitToken(firstToken); }
}
boot();
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();
+2 -2
View File
@@ -33,7 +33,7 @@
<h2 id="qr-title">Inscription</h2>
<ol id="qr-steps">
<li><span id="step1">Scannez ce code</span></li>
<li><span>Visez l'écran <b id="secs">5</b>&nbsp;s</span></li>
<li id="step2"><span>Ou visez le cercle <b id="secs">5</b>&nbsp;s</span></li>
</ol>
<p id="url-warn" class="notice warn" hidden></p>
</div>
@@ -50,7 +50,7 @@
<aside id="entry" class="entry" hidden>
<div id="entry-q" class="entry-q" hidden><b id="entry-q-text"></b><span id="entry-q-count"></span></div>
<canvas id="entry-qr" aria-label="QR code de la page de vote"></canvas>
<div><b id="entry-hint">Pas encore sur la page ?</b><span id="entry-url"></span></div>
<div><b id="entry-hint">Scannez avec l'appareil photo</b><span id="entry-url"></span></div>
</aside>
<footer class="s-foot">
+7 -3
View File
@@ -28,6 +28,7 @@
<video id="video" playsinline muted></video>
</div>
<p id="scan-msg" class="scan-msg muted"></p>
<div id="enroll-alt" class="cam-alt"></div>
<button id="start-cam" class="primary block" type="button">Activer la caméra</button>
<button id="no-cam" class="link" type="button">Caméra indisponible ?</button>
</div>
@@ -84,10 +85,13 @@
</dialog>
<dialog id="presence">
<h2 tabindex="-1" autofocus>Visez l'écran</h2>
<div id="p-ring" class="dots"></div>
<div class="cam"><video id="p-video" playsinline muted></video></div>
<h2 id="p-title" tabindex="-1" autofocus>Visez le cercle</h2>
<div id="p-scan">
<div id="p-ring" class="dots"></div>
<div class="cam"><video id="p-video" playsinline muted></video></div>
</div>
<p id="p-msg" class="scan-msg bad"></p>
<div id="p-alt" class="cam-alt"></div>
<div class="actions"><button id="p-cancel" type="button">Annuler</button></div>
</dialog>
</body>