Files
rotatyvote/static/js/screen.js
T

185 lines
6.8 KiB
JavaScript

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; // current code message, qr or ring
let raf = 0;
let entry = null;
let prevBits = null, switchedAt = 0;
let focusView = "";
// shows at once (css plays the entrance), hides after a short exit so blocks don't just vanish
function reveal(el, on) {
if (on) {
clearTimeout(el._leave);
el.classList.remove("leaving");
el.hidden = false;
return;
}
if (el.hidden || el.classList.contains("leaving")) return;
el.classList.add("leaving");
el._leave = setTimeout(() => { el.hidden = true; el.classList.remove("leaving"); }, 220);
}
// restarts a css animation class on an element that stays in the dom
function replay(el, cls) {
el.classList.remove(cls);
void el.offsetWidth;
el.classList.add(cls);
}
function layout() {
if (!st) return;
// qr stays up while enrolling, and during a vote that needs a presence scan
const qrOn = st.enrollment_open || st.presence;
const focus = st.focus;
reveal($("#enroll"), qrOn);
reveal($("#focus"), !!focus);
reveal($("#idle"), !qrOn && !focus);
$(".s-main").classList.toggle("split", qrOn && !!focus);
const ring = st.code_style === "ring";
// 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";
reveal($("#entry"), !!(ring && st.enrollment_open && entry));
$(".qr-wrap").classList.toggle("ring", ring);
}
function render() {
$("#s-title").textContent = st.title;
$("#idle-title").textContent = st.title;
document.title = st.title;
if ($("#voters").textContent !== String(st.voters)) {
$("#voters").textContent = st.voters;
replay($("#voters"), "bump");
}
$("#voters-label").textContent =
`inscription${st.voters > 1 ? "s" : ""}` + (st.expected ? ` sur ${st.expected}` : "");
$("#secs").textContent = Math.ceil((st.scans_required * st.interval_ms) / 1000);
const f = st.focus;
const box = $("#focus");
const view = f ? `${f.id}|${f.state}|${f.results ? 1 : 0}|${f.text}` : "";
if (f && view === focusView && f.state === "open") {
// same question still open: only the turnout moves, in place so the bar slides
const t = box.querySelector(".turnout");
t.querySelector("b").textContent = f.participants;
t.querySelector(".t-of").textContent = ` vote${f.participants > 1 ? "s" : ""} sur ${st.voters}`;
t.querySelector(".progress > div").style.width = `${pct(f.participants, st.voters)}%`;
} else if (view !== focusView) {
focusView = view;
if (f) {
// the old question fades with the section when there is no new one
box.replaceChildren(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), h("span", { class: "t-of" }, ` 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} vote${f.participants > 1 ? "s" : ""}`));
}
replay(box, "enter");
}
}
layout();
}
function paintQR() {
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(700, qr.interval_ms * 0.7);
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, seed: qr.slot } : null);
requestAnimationFrame(ringLoop);
}
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 && !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;
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.hidden = s === "online";
c.className = "conn offline";
c.textContent = "Reconnexion…";
if (s !== "online") { qr = null; const cv = $("#qr"); cv.getContext("2d").clearRect(0, 0, cv.width, cv.height); }
},
});