Admin: tabs, question composer dialog, settings autosave
Default answers Pour/Contre/Abstention/NPPPAV, svg icons instead of status dots, no live/open status labels, inclusive wording across the UI and docs.
This commit is contained in:
+142
-119
@@ -1,16 +1,17 @@
|
||||
import { $, h, api, pollId, takeKey, liveSocket, resultsView, STATE_LABEL, toast, fill, pct } from "./common.js";
|
||||
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;
|
||||
let settingsDirty = false;
|
||||
|
||||
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 (candidats)", opts: ["Candidat·e A", "Candidat·e B", "Candidat·e C"], blank: true, text: "Élection : " },
|
||||
{ label: "Satisfaction 1–5", opts: ["1", "2", "3", "4", "5"], 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);
|
||||
@@ -24,115 +25,135 @@ function errMsg(e) {
|
||||
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;
|
||||
const parts = [];
|
||||
if (p.expected) parts.push(`sur ${p.expected} attendus`);
|
||||
if (p.max_voters) parts.push(`${p.max_voters} max`);
|
||||
$("#voters-of").textContent = `inscrits${parts.length ? ", " + parts.join(", ") : ""}`;
|
||||
$("#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 es = $("#enroll-state");
|
||||
es.hidden = !p.enrollment_open && !(p.expected && state.voters > p.expected);
|
||||
if (p.enrollment_open) {
|
||||
es.className = "notice ok";
|
||||
es.textContent = "Ouvertes";
|
||||
} else {
|
||||
es.className = "notice info";
|
||||
es.textContent = "Fermées";
|
||||
}
|
||||
if (p.expected && state.voters > p.expected) {
|
||||
es.className = "notice bad";
|
||||
es.textContent = `${state.voters} inscrits pour ${p.expected} attendus`;
|
||||
}
|
||||
const tb = $("#toggle-enroll");
|
||||
tb.textContent = p.enrollment_open ? "Fermer les inscriptions" : "Ouvrir les inscriptions";
|
||||
tb.className = "block " + (p.enrollment_open ? "danger" : "go");
|
||||
// the switch itself carries the state, no status wording
|
||||
tb.textContent = "Inscriptions";
|
||||
tb.className = "enroll-toggle " + (p.enrollment_open ? "on" : "off");
|
||||
tb.setAttribute("aria-pressed", String(p.enrollment_open));
|
||||
|
||||
$("#screens").textContent = state.screens ? `Projecteur connecté (${state.screens})` : "Aucun projecteur connecté";
|
||||
$("#open-screen").classList.toggle("connected", state.screens > 0);
|
||||
$("#open-screen").title = state.screens ? "Projecteur connecté" : "Aucun projecteur connecté";
|
||||
|
||||
if (!settingsDirty) {
|
||||
$("#s-interval").value = p.interval_ms;
|
||||
$("#s-scans").value = p.scans_required;
|
||||
$("#s-expected").value = p.expected ?? "";
|
||||
$("#s-max").value = p.max_voters ?? "";
|
||||
$("#s-code").checked = p.require_code;
|
||||
}
|
||||
$("#codes-card").hidden = !p.require_code && !state.codes.total;
|
||||
$("#codes-summary").textContent = `${state.codes.used} utilisé(s) sur ${state.codes.total}.`;
|
||||
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 ?? "";
|
||||
$("#s-code").checked = p.require_code;
|
||||
$("#codes-box").hidden = !p.require_code;
|
||||
$("#codes-summary").textContent = state.codes.total
|
||||
? `${state.codes.used} utilisé${state.codes.used > 1 ? "s" : ""} sur ${state.codes.total}`
|
||||
: "Aucun code généré";
|
||||
}
|
||||
|
||||
function renderQuestions() {
|
||||
const box = $("#questions");
|
||||
box.replaceChildren();
|
||||
if (!state.questions.length) {
|
||||
box.append(h("p", { class: "muted" }, "Aucune question."));
|
||||
box.append(h("p", { class: "empty" }, "Aucune question pour l'instant."));
|
||||
return;
|
||||
}
|
||||
const voters = state.voters;
|
||||
for (const q of state.questions) {
|
||||
const focused = state.poll.focus_qid === q.id;
|
||||
const badges = [h("span", { class: `badge ${q.state}` }, STATE_LABEL[q.state])];
|
||||
if (q.results_public) badges.push(h("span", { class: "badge public" }, "Résultats publiés"));
|
||||
if (focused) badges.push(h("span", { class: "focus-mark" }, "● à l'écran"));
|
||||
|
||||
const actions = [];
|
||||
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);
|
||||
if (q.state === "draft") {
|
||||
actions.push(act("Lancer le vote", "open", "small go"));
|
||||
actions.push(act("Supprimer", "delete", "small danger", "Supprimer ce brouillon ?"));
|
||||
}
|
||||
if (q.state === "open") {
|
||||
actions.push(act("Clore le vote", "close", "small primary",
|
||||
`Clore le vote (${q.participants} votants) ? Définitif.`));
|
||||
}
|
||||
if (q.state === "closed") {
|
||||
actions.push(q.results_public ? act("Masquer les résultats", "unpublish") : act("Publier les résultats", "publish", "small primary"));
|
||||
}
|
||||
if (q.state !== "draft" && !focused) actions.push(act("Afficher à l'écran", "focus"));
|
||||
|
||||
const turnout = q.state !== "draft"
|
||||
? h("div", {},
|
||||
h("div", { class: "q-meta" }, `${q.participants} / ${voters} votants`),
|
||||
h("div", { class: "progress" }, fill(pct(q.participants, voters), "")))
|
||||
: null;
|
||||
|
||||
box.append(h("article", { class: `q ${q.state}` },
|
||||
h("div", { class: "q-head" }, h("div", {}, badges), h("span", { class: "q-meta" }, `#${q.id}`)),
|
||||
h("div", { class: "q-text" }, q.text),
|
||||
q.state === "closed" ? resultsView(q) : h("ol", { class: "q-opts" }, q.options.map((o) => h("li", {}, o))),
|
||||
h("div", { class: "q-meta" },
|
||||
q.kind === "multi" ? `Max ${q.max_choices} choix` : "",
|
||||
q.kind === "multi" && q.allow_blank ? ", " : "",
|
||||
q.allow_blank ? "blanc possible" : ""),
|
||||
turnout,
|
||||
h("div", { class: "actions" }, actions),
|
||||
));
|
||||
}
|
||||
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" : ""}) ? Définitif.`));
|
||||
} else {
|
||||
actions.push(q.results_public
|
||||
? act("Masquer les résultats", "unpublish")
|
||||
: act("Publier les résultats", "publish", "small primary"));
|
||||
}
|
||||
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: () => {
|
||||
$("#q-opts").value = t.opts.join("\n");
|
||||
$("#q-blank").checked = t.blank;
|
||||
if (t.text && !$("#q-text").value) $("#q-text").value = t.text;
|
||||
$("#q-text").focus();
|
||||
},
|
||||
onclick: () => { applyTemplate(t); $("#q-text").focus(); },
|
||||
}, t.label));
|
||||
}
|
||||
$("#q-kind").addEventListener("change", () => { $("#q-max-box").hidden = $("#q-kind").value !== "multi"; });
|
||||
@@ -151,43 +172,43 @@ async function submitQuestion(open) {
|
||||
if (options.length < 2) return toast("Au moins deux réponses", "bad");
|
||||
try {
|
||||
await call("POST", "/questions", data);
|
||||
$("#q-text").value = "";
|
||||
$("#q-opts").value = "";
|
||||
toast(open ? "Vote lancé" : "Question préparée", "ok");
|
||||
$("#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} inscrits) ?`)) return;
|
||||
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"); }
|
||||
});
|
||||
|
||||
for (const id of ["#s-interval", "#s-scans", "#s-expected", "#s-max", "#s-code"]) {
|
||||
$(id).addEventListener("input", () => { settingsDirty = true; });
|
||||
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 }),
|
||||
};
|
||||
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"); }
|
||||
});
|
||||
}
|
||||
$("#save-settings").addEventListener("click", async () => {
|
||||
try {
|
||||
await call("PATCH", "", {
|
||||
interval_ms: +$("#s-interval").value,
|
||||
scans_required: +$("#s-scans").value,
|
||||
expected: $("#s-expected").value ? +$("#s-expected").value : null,
|
||||
max_voters: $("#s-max").value ? +$("#s-max").value : null,
|
||||
require_code: $("#s-code").checked,
|
||||
});
|
||||
settingsDirty = false;
|
||||
toast("Réglages enregistrés", "ok");
|
||||
} catch (e) { toast(errMsg(e), "bad"); }
|
||||
});
|
||||
|
||||
|
||||
$("#codes-gen").addEventListener("click", async () => {
|
||||
try {
|
||||
await call("POST", "/codes", { count: +$("#codes-count").value });
|
||||
toast("Codes générés", "ok");
|
||||
toast("Codes générés");
|
||||
} catch (e) { toast(errMsg(e), "bad"); }
|
||||
});
|
||||
$("#codes-print").addEventListener("click", async () => {
|
||||
@@ -200,20 +221,22 @@ $("#codes-print").addEventListener("click", async () => {
|
||||
$("#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", async () => {
|
||||
const link = `${location.origin}/admin/${pid}#${encodeURIComponent(key)}`;
|
||||
try { await navigator.clipboard.writeText(link); toast("Lien admin copié"); }
|
||||
catch { prompt("Lien admin", link); }
|
||||
});
|
||||
$("#copy-admin").addEventListener("click", () =>
|
||||
copy(`${location.origin}/admin/${pid}#${encodeURIComponent(key)}`, "Lien admin"));
|
||||
$("#screen-rotate").addEventListener("click", async () => {
|
||||
if (!confirm("Révoquer l'ancien lien projecteur ?")) return;
|
||||
if (!confirm("Créer un nouveau lien projecteur ? L'ancien cessera de fonctionner.")) return;
|
||||
try {
|
||||
const r = await call("POST", "/screen-key");
|
||||
$("#screen-link").value = `${location.origin}/screen/${pid}#${r.screen_key}`;
|
||||
$("#screen-link").select();
|
||||
await copy(`${location.origin}/screen/${pid}#${r.screen_key}`, "Lien projecteur");
|
||||
} catch (e) { toast(errMsg(e), "bad"); }
|
||||
});
|
||||
$("#export").addEventListener("click", async () => {
|
||||
@@ -226,7 +249,6 @@ $("#export").addEventListener("click", async () => {
|
||||
} catch (e) { toast(errMsg(e), "bad"); }
|
||||
});
|
||||
|
||||
|
||||
liveSocket(`/ws/${pid}/admin`, {
|
||||
auth: key,
|
||||
onMessage(msg) {
|
||||
@@ -244,7 +266,8 @@ liveSocket(`/ws/${pid}/admin`, {
|
||||
c.textContent = "refusé";
|
||||
return;
|
||||
}
|
||||
c.className = `conn ${s}`;
|
||||
c.textContent = s === "online" ? "en direct" : "reconnexion…";
|
||||
c.hidden = s === "online";
|
||||
c.className = "conn offline";
|
||||
c.textContent = "Reconnexion…";
|
||||
},
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user