Files
rotatyvote/static/js/admin.js
T

292 lines
12 KiB
JavaScript

import { $, h, api, pollId, takeKey, liveSocket, resultsView, STATE_LABEL, toast, fill, pct, icon } from "./common.js";
const pid = pollId();
const key = takeKey(`rv_admin_${pid}`);
const base = `/api/polls/${pid}`;
const TAB_KEY = "rv_admin_tab";
let state = null;
const TEMPLATES = [
{ label: "Pour / Contre / Abst. / NPPPAV", opts: ["Pour", "Contre", "Abstention", "Ne prend pas part au vote"], blank: false },
{ label: "Pour / Contre / Abstention", opts: ["Pour", "Contre", "Abstention"], blank: false },
{ label: "Oui / Non", opts: ["Oui", "Non"], blank: true },
{ label: "Élection", opts: ["Candidat·e A", "Candidat·e B", "Candidat·e C"], blank: true, text: "Élection : " },
{ label: "Note 1 à 5", opts: ["1", "2", "3", "4", "5"], blank: true },
];
const call = (method, path, data) => api(method, base + path, data, key);
function errMsg(e) {
const m = {
not_draft: "La question n'est plus en brouillon",
not_open: "La question n'est pas ouverte",
not_closed: "La question n'est pas close",
already_shown: "Résultats déjà publiés, le vote ne peut plus être rouvert",
};
return m[e.code] || e.message;
}
function showTab(name) {
for (const b of document.querySelectorAll("[data-tab]")) b.setAttribute("aria-selected", String(b.dataset.tab === name));
for (const p of document.querySelectorAll("[data-panel]")) p.hidden = p.dataset.panel !== name;
try { localStorage.setItem(TAB_KEY, name); } catch { /* private mode */ }
}
for (const b of document.querySelectorAll("[data-tab]")) b.addEventListener("click", () => showTab(b.dataset.tab));
let initialTab = "questions";
try { initialTab = localStorage.getItem(TAB_KEY) || "questions"; } catch { /* private mode */ }
showTab(initialTab);
function render() {
const p = state.poll;
$("#title").textContent = p.title;
document.title = `Admin · ${p.title}`;
$("#voters").textContent = state.voters;
$("#voters-of").textContent = `inscription${state.voters > 1 ? "s" : ""}` + (p.expected ? ` sur ${p.expected}` : "");
const over = p.expected && state.voters > p.expected;
$("#over").hidden = !over;
if (over) $("#over").textContent = `Plus d'inscriptions que de personnes attendues (${state.voters} pour ${p.expected}).`;
const tb = $("#toggle-enroll");
// the switch itself carries the state, no status wording
tb.replaceChildren(h("span", { class: "switch", "aria-hidden": "true" }), "Inscriptions");
tb.className = "enroll-toggle " + (p.enrollment_open ? "on" : "off");
tb.setAttribute("role", "switch");
tb.setAttribute("aria-checked", String(p.enrollment_open));
$("#open-screen").classList.toggle("connected", state.screens > 0);
$("#open-screen").title = state.screens ? "Projecteur connecté" : "Aucun projecteur connecté";
const open = state.questions.filter((q) => q.state === "open").length;
$("#open-count").hidden = !open;
$("#open-count").textContent = open;
renderSettings(p);
renderQuestions();
}
function renderSettings(p) {
// never overwrite a field the admin is typing in
const active = document.activeElement;
const sel = $("#s-interval");
if (![...sel.options].some((o) => +o.value === p.interval_ms)) {
sel.append(h("option", { value: p.interval_ms }, `${(p.interval_ms / 1000).toLocaleString("fr-FR")} s`));
}
if (active !== sel) sel.value = String(p.interval_ms);
if (active !== $("#s-scans")) $("#s-scans").value = p.scans_required;
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);
$("#access-summary").textContent = sum(state.codes.access, "Un code par personne, avec le scan");
$("#rescue-summary").textContent = sum(state.codes.rescue, "Inscription sans caméra");
}
function renderQuestions() {
const box = $("#questions");
box.replaceChildren();
if (!state.questions.length) {
box.append(h("p", { class: "empty" }, "Aucune question pour l'instant."));
return;
}
const order = { open: 0, draft: 1, closed: 2 };
const qs = [...state.questions].sort((a, b) => order[a.state] - order[b.state] || a.id - b.id);
for (const q of qs) box.append(questionCard(q));
}
function questionCard(q) {
const voters = state.voters;
const focused = state.poll.focus_qid === q.id;
const act = (label, action, cls = "small", confirmMsg) =>
h("button", {
class: cls, type: "button",
onclick: async () => {
if (confirmMsg && !confirm(confirmMsg)) return;
try { await call("POST", `/questions/${q.id}/${action}`); } catch (e) { toast(errMsg(e), "bad"); }
},
}, label);
const actions = [];
if (q.state === "draft") {
actions.push(act("Lancer le vote", "open", "small go"));
actions.push(act("Supprimer", "delete", "small danger", "Supprimer ce brouillon ?"));
} else if (q.state === "open") {
actions.push(act("Clore le vote", "close", "small primary", `Clore le vote (${q.participants} vote${q.participants > 1 ? "s" : ""}) ?`));
} else {
actions.push(q.results_public
? act("Masquer les résultats", "unpublish")
: act("Publier les résultats", "publish", "small primary", "Publier les résultats ? Le vote ne pourra plus être rouvert."));
if (!q.shown) actions.push(act("Rouvrir le vote", "reopen"));
}
if (q.state !== "draft" && !focused) actions.push(act([icon("screen", 15), "Afficher à l'écran"], "focus"));
const badges = [h("span", { class: `badge ${q.state}` }, STATE_LABEL[q.state])];
if (q.results_public) badges.push(h("span", { class: "badge public" }, "Publiés"));
if (focused) badges.push(h("span", { class: "focus-mark" }, icon("screen", 14), "À l'écran"));
if (q.kind === "multi") badges.push(h("span", { class: "badge" }, `${q.max_choices} choix max`));
return h("article", { class: `q ${q.state}` },
h("div", { class: "q-head" }, h("div", {}, badges),
q.state !== "draft" ? h("span", { class: "q-meta" }, `${q.participants} / ${voters}`) : null),
h("div", { class: "q-text" }, q.text),
q.state === "closed"
? resultsView(q)
: h("div", { class: "chips" }, q.options.map((o) => h("span", { class: "chip" }, o)),
q.allow_blank ? h("span", { class: "chip ghost" }, "Blanc") : null),
q.state === "open" ? h("div", { class: "progress" }, fill(pct(q.participants, voters), "")) : null,
h("div", { class: "actions" }, actions),
);
}
// composer
const composer = $("#composer");
function applyTemplate(t) {
$("#q-opts").value = t.opts.join("\n");
$("#q-blank").checked = t.blank;
if (t.text && !$("#q-text").value) $("#q-text").value = t.text;
}
$("#new-q").addEventListener("click", () => {
// the first template is the default answer set
if (!$("#q-opts").value.trim()) applyTemplate(TEMPLATES[0]);
composer.showModal();
$("#q-text").focus();
});
for (const t of TEMPLATES) {
$("#templates").append(h("button", {
class: "small", type: "button",
onclick: () => { applyTemplate(t); $("#q-text").focus(); },
}, t.label));
}
$("#q-cancel").addEventListener("click", () => composer.close());
// enter in a field must not submit (and close) the dialog
$("#q-form").addEventListener("submit", (e) => e.preventDefault());
$("#q-kind").addEventListener("change", () => { $("#q-max-box").hidden = $("#q-kind").value !== "multi"; });
async function submitQuestion(open) {
const options = $("#q-opts").value.split("\n").map((s) => s.trim()).filter(Boolean);
const data = {
text: $("#q-text").value.trim(),
options,
kind: $("#q-kind").value,
max_choices: +$("#q-max").value || 1,
allow_blank: $("#q-blank").checked,
open,
};
if (!data.text) return toast("Saisissez la question", "bad");
if (options.length < 2) return toast("Au moins deux réponses", "bad");
try {
await call("POST", "/questions", data);
$("#q-form").reset();
$("#q-max-box").hidden = true;
composer.close();
showTab("questions");
toast(open ? "Vote lancé" : "Brouillon enregistré");
} catch (e) { toast(errMsg(e), "bad"); }
}
$("#q-draft").addEventListener("click", () => submitQuestion(false));
$("#q-push").addEventListener("click", () => submitQuestion(true));
// enrollment + settings, saved as soon as a field changes
$("#toggle-enroll").addEventListener("click", async () => {
const open = !state.poll.enrollment_open;
if (!open && !confirm(`Fermer les inscriptions (${state.voters} inscription${state.voters > 1 ? "s" : ""}) ?`)) return;
try { await call("PATCH", "", { enrollment_open: open }); } catch (e) { toast(errMsg(e), "bad"); }
});
const intOrNull = (v) => (v ? +v : null);
const SETTINGS = {
"#s-interval": (el) => ({ interval_ms: +el.value }),
"#s-scans": (el) => ({ scans_required: +el.value }),
"#s-expected": (el) => ({ expected: intOrNull(el.value) }),
"#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) => {
try { await call("PATCH", "", build(e.target)); toast("Enregistré"); }
catch (err) { toast(errMsg(err), "bad"); }
});
}
const CODE_LABEL = { access: "Codes papier", rescue: "Codes de secours" };
for (const b of document.querySelectorAll("[data-gen]")) {
b.addEventListener("click", async () => {
const kind = b.dataset.gen;
try {
await call("POST", "/codes", { count: +$(`#${kind}-count`).value, rescue: kind === "rescue" });
toast(`${CODE_LABEL[kind]} générés`);
} catch (e) { toast(errMsg(e), "bad"); }
});
}
for (const b of document.querySelectorAll("[data-print]")) {
b.addEventListener("click", async () => {
const kind = b.dataset.print;
const { codes } = await call("GET", "/codes");
const list = codes.filter((c) => Boolean(c.rescue) === (kind === "rescue"));
$("#codes-title").textContent = `${CODE_LABEL[kind]}, ${state.poll.title}`;
$("#codes-grid").replaceChildren(...list.map((c) => h("div", { class: "code-cell" + (c.used ? " used" : "") }, c.code)));
$("#codes-sheet").hidden = false;
$("#codes-sheet").scrollIntoView({ behavior: "smooth" });
});
}
$("#codes-close").addEventListener("click", () => { $("#codes-sheet").hidden = true; });
$("#codes-do-print").addEventListener("click", () => window.print());
// sharing
$("#open-screen").href = `/screen/${pid}#${encodeURIComponent(key)}`;
$("#screen-icon").replaceWith(icon("screen", 16));
async function copy(text, label) {
try { await navigator.clipboard.writeText(text); toast(`${label} copié`); }
catch { prompt(label, text); }
}
// the key is hidden from the address bar, so a bookmark would lose it
$("#copy-admin").addEventListener("click", () =>
copy(`${location.origin}/admin/${pid}#${encodeURIComponent(key)}`, "Lien admin"));
$("#screen-rotate").addEventListener("click", async () => {
if (!confirm("Créer un nouveau lien projecteur ? L'ancien cessera de fonctionner.")) return;
try {
const r = await call("POST", "/screen-key");
await copy(`${location.origin}/screen/${pid}#${r.screen_key}`, "Lien projecteur");
} catch (e) { toast(errMsg(e), "bad"); }
});
$("#export").addEventListener("click", async () => {
try {
const data = await call("GET", "/export");
const blob = new Blob([JSON.stringify(data, null, 2)], { type: "application/json" });
const a = h("a", { href: URL.createObjectURL(blob), download: `rotatyvote-${pid}.json` });
a.click();
setTimeout(() => URL.revokeObjectURL(a.href), 1000);
} catch (e) { toast(errMsg(e), "bad"); }
});
liveSocket(`/ws/${pid}/admin`, {
auth: key,
onMessage(msg) {
if (msg.type !== "state") return;
state = msg;
$("#app").hidden = false;
$("#denied").hidden = true;
render();
},
onStatus(s) {
const c = $("#conn");
if (s.startsWith("denied")) {
$("#denied").hidden = false;
c.className = "conn offline";
c.textContent = "refusé";
return;
}
c.hidden = s === "online";
c.className = "conn offline";
c.textContent = "Reconnexion…";
},
});