import { $, h, pollId, takeKey, liveSocket, drawQR, resultsView, pct } from "./common.js"; import { render as drawRing, DISC } from "./ringcode.js"; const pid = pollId(); // /present/: duplicated screen, the laptop shows what the projector shows. admin key, admin in a drawer const present = location.pathname.startsWith("/present/"); const key = takeKey(present ? `rv_present_${pid}` : `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); } // the entry qr jumps between the corner and the big spot: slide and grow it from where it was (flip) function flip(el, before) { if (!before || el.hidden || matchMedia("(prefers-reduced-motion: reduce)").matches) return; const after = el.getBoundingClientRect(); if (!after.width || !after.height) return; const dx = before.left - after.left, dy = before.top - after.top, sx = before.width / after.width, sy = before.height / after.height; if (Math.abs(dx) < 2 && Math.abs(dy) < 2 && Math.abs(sx - 1) < 0.02 && Math.abs(sy - 1) < 0.02) return; el.animate([ { transformOrigin: "0 0", transform: `translate(${dx}px, ${dy}px) scale(${sx}, ${sy})` }, { transformOrigin: "0 0", transform: "none" }, ], { duration: 600, easing: "cubic-bezier(.2, .7, .2, 1)" }); } function layout() { if (!st) return; const entryEl = $("#entry"); const before = !entryEl.hidden && !entryEl.classList.contains("leaving") ? entryEl.getBoundingClientRect() : null; // 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"; // the camera app code: enrolls, and proves presence for a vote, so it stays up whenever the ring does const cam = st.camera_pass !== false; const entryOn = !!(ring && entry && (st.enrollment_open || (cam && st.presence))); // 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; // an upright screen has no room for the question above the qr (.entry-q hidden): it keeps its own block const openVote = cam && 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); $(".s-main").classList.toggle("split", qrOn && !!focus); document.body.classList.toggle("split-on", qrOn && !!focus); // 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; $("#step1").textContent = ring ? (cam ? "Scannez le QR avec l'appareil photo" : "Ouvrez la page de vote") : "Scannez avec l'appareil photo"; $("#step2").hidden = !ring; reveal($("#entry"), entryOn); document.body.classList.toggle("has-entry", entryOn); document.body.classList.toggle("entry-big", big); const showQ = big && !!f; document.body.classList.toggle("entry-q-on", showQ); $("#entry-q").hidden = !showQ; // an open vote keeps its options and turnout bar on screen, just above the qr const opts = showQ && !!openVote; document.body.classList.toggle("entry-opts-on", opts); $("#entry-q-opts").hidden = !opts; $("#entry-q-turnout").hidden = !opts; $("#entry-q-count").hidden = opts; if (showQ) { $("#entry-q-text").textContent = f.text; if (opts) { const ul = $("#entry-q-opts"), key = JSON.stringify(f.options); if (ul.dataset.key !== key) { ul.dataset.key = key; ul.replaceChildren(...f.options.map((o) => h("li", {}, o))); } paintTurnout($("#entry-q-turnout"), f); } else { $("#entry-q-count").textContent = `Vote clos, ${f.participants} bulletin${f.participants > 1 ? "s" : ""}`; } } $("#entry-hint").textContent = cam ? "Scannez avec l'appareil photo" : big ? "Scannez ici, puis visez le cercle" : "Pas encore sur la page ?"; $(".qr-wrap").classList.toggle("ring", ring); flip(entryEl, before); } 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 ? JSON.stringify(f.results) : 0}|${f.text}` : ""; if (f && view === focusView && f.state === "open") { // same question still open: only the turnout moves, in place so the bar slides paintTurnout(box.querySelector(".turnout"), f); } 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))), paintTurnout(h("div", { class: "turnout" }, h("b", {}), h("span", { class: "t-of" }), h("div", { class: "progress" }, h("div", {}), h("div", { class: "p-extra" }))), f), ); } 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(); } // "9 votes sur 10, dont 3 ajoutés": hand-added votes count in, and show hatched at the end of the bar function paintTurnout(t, f) { const extra = f.extra_ballots || 0, all = f.participants + extra, of = st.voters + extra; t.querySelector("b").textContent = all; t.querySelector(".t-of").textContent = ` vote${all > 1 ? "s" : ""} sur ${of}` + (extra ? `, dont ${extra} ajouté${extra > 1 ? "s" : ""}` : ""); const [phone, added] = t.querySelectorAll(".progress > div"); phone.style.width = `${pct(f.participants, of)}%`; added.style.width = `${pct(extra, of)}%`; return t; } 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(); layout(); }); $("#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); } }, }); if (present) { const btn = h("button", { class: "small ctl-btn", type: "button", "aria-expanded": "false" }, "Gérer"); const close = h("button", { class: "small", type: "button" }, "Fermer"); const drawer = h("aside", { class: "ctl", "aria-label": "Gestion du scrutin" }, h("div", { class: "ctl-head" }, h("b", {}, "Gestion"), close)); document.body.append(drawer); $(".s-tools").prepend(btn); const toggle = (open) => { // the admin page loads on first open only, and keeps its state when the drawer closes if (open && !drawer.querySelector("iframe")) { drawer.append(h("iframe", { src: `/admin/${pid}#${encodeURIComponent(key)}`, title: "Administration" })); } // the projection folds into the room the drawer leaves, the entry qr slides along const entryEl = $("#entry"), before = entryEl.hidden ? null : entryEl.getBoundingClientRect(); drawer.classList.toggle("open", open); document.body.classList.toggle("ctl-open", open); btn.setAttribute("aria-expanded", String(open)); flip(entryEl, before); }; btn.addEventListener("click", () => toggle(!drawer.classList.contains("open"))); close.addEventListener("click", () => toggle(false)); document.addEventListener("keydown", (e) => { if (e.key === "Escape") toggle(false); }); }