Results export as plain text: procès-verbal, compact, liste, barres, markdown and csv templates with a preview, copy and download, from the share tab or a closed question; tally maths shared with the results bars
This commit is contained in:
@@ -1,9 +1,11 @@
|
||||
import { $, h, api, pollId, takeKey, liveSocket, resultsView, STATE_LABEL, toast, fill, pct, icon } from "./common.js";
|
||||
import { FORMATS, exportText } from "./export.js";
|
||||
|
||||
const pid = pollId();
|
||||
const key = takeKey(`rv_admin_${pid}`);
|
||||
const base = `/api/polls/${pid}`;
|
||||
const TAB_KEY = "rv_admin_tab";
|
||||
const FMT_KEY = "rv_export_fmt";
|
||||
let state = null;
|
||||
|
||||
const TEMPLATES = [
|
||||
@@ -127,6 +129,7 @@ function questionCard(q) {
|
||||
if (!q.shown) actions.push(act("Rouvrir le vote", "reopen"));
|
||||
}
|
||||
if (q.state !== "draft") actions.push(h("button", { class: "small", type: "button", onclick: () => editExtra(q) }, "Votes en plus"));
|
||||
if (q.state === "closed") actions.push(h("button", { class: "small", type: "button", onclick: () => openExport(q.id) }, "Exporter"));
|
||||
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])];
|
||||
@@ -303,6 +306,70 @@ $("#export").addEventListener("click", async () => {
|
||||
} catch (e) { toast(errMsg(e), "bad"); }
|
||||
});
|
||||
|
||||
// text export, built in the browser from the closed tallies the socket already sends
|
||||
|
||||
const exDlg = $("#export-dlg");
|
||||
let fmt = FORMATS[0];
|
||||
try { fmt = FORMATS.find((f) => f.id === localStorage.getItem(FMT_KEY)) || fmt; } catch { /* private mode */ }
|
||||
let exText = "";
|
||||
|
||||
for (const f of FORMATS) {
|
||||
$("#ex-formats").append(h("button", {
|
||||
class: "small", type: "button", role: "radio", dataset: { fmt: f.id },
|
||||
onclick: () => {
|
||||
fmt = f;
|
||||
try { localStorage.setItem(FMT_KEY, f.id); } catch { /* private mode */ }
|
||||
renderExport();
|
||||
},
|
||||
}, f.label));
|
||||
}
|
||||
|
||||
function closedQuestions() {
|
||||
return state.questions.filter((q) => q.state === "closed").sort((a, b) => a.id - b.id);
|
||||
}
|
||||
|
||||
function renderExport() {
|
||||
for (const b of $("#ex-formats").children) b.setAttribute("aria-checked", String(b.dataset.fmt === fmt.id));
|
||||
const scope = $("#ex-scope").value;
|
||||
const qs = closedQuestions().filter((q) => scope === "all" || String(q.id) === scope);
|
||||
const now = new Date().toLocaleString("fr-FR", { dateStyle: "long", timeStyle: "short" });
|
||||
exText = qs.length ? exportText(fmt, state.poll, state.voters, qs, now) : "";
|
||||
const pre = $("#ex-preview");
|
||||
pre.classList.toggle("empty", !exText);
|
||||
pre.textContent = exText || "Aucune question close.";
|
||||
$("#ex-copy").disabled = $("#ex-download").disabled = !exText;
|
||||
}
|
||||
|
||||
function openExport(qid = "all") {
|
||||
const qs = closedQuestions();
|
||||
const sel = $("#ex-scope");
|
||||
sel.replaceChildren(h("option", { value: "all" }, "Toutes les questions closes"),
|
||||
...qs.map((q) => h("option", { value: String(q.id) }, q.text)));
|
||||
sel.value = String(qid);
|
||||
sel.hidden = qs.length < 2;
|
||||
renderExport();
|
||||
exDlg.showModal();
|
||||
}
|
||||
|
||||
$("#ex-scope").addEventListener("change", renderExport);
|
||||
$("#export-text").addEventListener("click", () => openExport());
|
||||
$("#ex-copy").addEventListener("click", async () => {
|
||||
try { await navigator.clipboard.writeText(exText); toast("Copié"); }
|
||||
catch {
|
||||
// prompt() would flatten the lines, select the preview so cmd+c works
|
||||
getSelection().selectAllChildren($("#ex-preview"));
|
||||
toast("Texte sélectionné");
|
||||
}
|
||||
});
|
||||
$("#ex-download").addEventListener("click", () => {
|
||||
// bom so excel reads the accents in the csv
|
||||
const body = fmt.ext === "csv" ? "\ufeff" + exText : exText;
|
||||
const blob = new Blob([body], { type: `${fmt.mime};charset=utf-8` });
|
||||
const a = h("a", { href: URL.createObjectURL(blob), download: `rotatyvote-${pid}.${fmt.ext}` });
|
||||
a.click();
|
||||
setTimeout(() => URL.revokeObjectURL(a.href), 1000);
|
||||
});
|
||||
|
||||
liveSocket(`/ws/${pid}/admin`, {
|
||||
auth: key,
|
||||
onMessage(msg) {
|
||||
|
||||
+7
-10
@@ -1,3 +1,6 @@
|
||||
import { tally, pct } from "./export.js";
|
||||
|
||||
export { pct };
|
||||
export const $ = (sel, root = document) => root.querySelector(sel);
|
||||
|
||||
// tiny element builder, children are always text nodes or elements so no html injection
|
||||
@@ -103,9 +106,6 @@ export function drawQR(canvas, modules, px) {
|
||||
}
|
||||
}
|
||||
|
||||
export function pct(n, d) {
|
||||
return d ? Math.round((n / d) * 1000) / 10 : 0;
|
||||
}
|
||||
|
||||
// CSSOM write, a style="" attribute would be blocked by the CSP
|
||||
export function fill(percent, cls = "bar-fill") {
|
||||
@@ -115,16 +115,13 @@ export function fill(percent, cls = "bar-fill") {
|
||||
}
|
||||
|
||||
export function resultsView(q) {
|
||||
const r = q.results;
|
||||
if (!r) return null;
|
||||
if (!q.results) return null;
|
||||
// votes added by hand ride at the end of each bar, hatched orange, so nobody mistakes them for phone ballots
|
||||
const ex = r.extra || { counts: r.counts.map(() => 0), blank: 0, ballots: 0 };
|
||||
const tot = r.counts.map((c, i) => c + (ex.counts[i] || 0));
|
||||
const ballots = r.ballots + ex.ballots, blank = r.blank + ex.blank, base = ballots - blank;
|
||||
const { phone, extra, tot, ballots, blank, base, exBallots } = tally(q);
|
||||
const max = Math.max(1, ...tot);
|
||||
const rows = q.options.map((label, i) => {
|
||||
const stack = h("div", { class: "bar-stack" },
|
||||
seg("bar-fill", r.counts[i]), ex.counts[i] ? seg("bar-extra", ex.counts[i]) : null);
|
||||
seg("bar-fill", phone[i]), extra[i] ? seg("bar-extra", extra[i]) : null);
|
||||
stack.style.width = `${pct(tot[i], max)}%`;
|
||||
return h("div", { class: "bar-row" + (tot[i] === max && tot[i] > 0 ? " lead" : "") },
|
||||
h("div", { class: "bar-label" }, label),
|
||||
@@ -137,7 +134,7 @@ export function resultsView(q) {
|
||||
h("p", { class: "results-foot" },
|
||||
`${ballots} bulletin${ballots > 1 ? "s" : ""}`,
|
||||
q.allow_blank ? `, dont ${blank} blanc${blank > 1 ? "s" : ""}` : "",
|
||||
ex.ballots ? h("span", { class: "extra-note" }, `, dont ${ex.ballots} ajouté${ex.ballots > 1 ? "s" : ""} à la main`) : "",
|
||||
exBallots ? h("span", { class: "extra-note" }, `, dont ${exBallots} ajouté${exBallots > 1 ? "s" : ""} à la main`) : "",
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
// plain text results export, pure functions (no dom) so node can run them too
|
||||
|
||||
export function tally(q) {
|
||||
const r = q.results;
|
||||
const ex = r.extra || { counts: r.counts.map(() => 0), blank: 0, ballots: 0 };
|
||||
const extra = r.counts.map((_, i) => ex.counts[i] || 0);
|
||||
const tot = r.counts.map((c, i) => c + extra[i]);
|
||||
const ballots = r.ballots + ex.ballots, blank = r.blank + ex.blank;
|
||||
return { phone: r.counts, extra, tot, ballots, blank, base: ballots - blank, exBallots: ex.ballots, exBlank: ex.blank };
|
||||
}
|
||||
|
||||
export function pct(n, d) {
|
||||
return d ? Math.round((n / d) * 1000) / 10 : 0;
|
||||
}
|
||||
|
||||
// fr-FR toLocaleString puts a narrow nbsp in thousands, which breaks column alignment
|
||||
const num = (n) => String(n).replace(".", ",");
|
||||
const pctTxt = (n, d) => `${num(pct(n, d))} %`;
|
||||
const plural = (n, word) => `${n} ${word}${n > 1 ? "s" : ""}`;
|
||||
|
||||
function foot(q, t) {
|
||||
let s = plural(t.ballots, "bulletin");
|
||||
if (q.allow_blank) s += `, dont ${plural(t.blank, "blanc")}`;
|
||||
if (t.exBallots) s += `, dont ${t.exBallots} ajouté${t.exBallots > 1 ? "s" : ""} à la main`;
|
||||
return s;
|
||||
}
|
||||
|
||||
const nb = (qs, k) => (qs.length > 1 ? `${k + 1}. ` : "");
|
||||
const kindNote = (q) => (q.kind === "multi" ? `Choix multiple, ${q.max_choices} max` : "");
|
||||
|
||||
function header(poll, voters, now) {
|
||||
return [poll.title, `Résultats du ${now} · ${plural(voters, "inscription")}`];
|
||||
}
|
||||
|
||||
// visible length, emoji and accents count as one column
|
||||
const width = (s) => [...s].length;
|
||||
const padEnd = (s, n) => s + " ".repeat(Math.max(0, n - width(s)));
|
||||
const padStart = (s, n) => " ".repeat(Math.max(0, n - width(s))) + s;
|
||||
|
||||
function rows(q, t) {
|
||||
const out = q.options.map((label, i) => ({ label, n: t.tot[i], p: pctTxt(t.tot[i], t.base) }));
|
||||
if (q.allow_blank) out.push({ label: "Blanc", n: t.blank, p: "" });
|
||||
return out;
|
||||
}
|
||||
|
||||
function minutes(poll, voters, qs, now) {
|
||||
const out = [...header(poll, voters, now)];
|
||||
qs.forEach((q, k) => {
|
||||
const t = tally(q), rs = rows(q, t);
|
||||
const lw = Math.max(...rs.map((r) => width(r.label)));
|
||||
const nw = Math.max(...rs.map((r) => String(r.n).length));
|
||||
out.push("", `${nb(qs, k)}${q.text}`);
|
||||
if (kindNote(q)) out.push(` ${kindNote(q)}`);
|
||||
for (const r of rs) out.push(` ${padEnd(r.label, lw)} ${padStart(String(r.n), nw)} ${padStart(r.p, 7)}`.trimEnd());
|
||||
out.push(` ${foot(q, t)}`);
|
||||
});
|
||||
return out.join("\n");
|
||||
}
|
||||
|
||||
// no column alignment, survives a paste in an email or a chat
|
||||
function compact(poll, voters, qs) {
|
||||
const out = [poll.title];
|
||||
for (const q of qs) {
|
||||
const t = tally(q);
|
||||
const parts = rows(q, t).map((r) => (r.p ? `${r.label} ${r.n} (${r.p})` : `${r.label} ${r.n}`));
|
||||
out.push("", q.text + (kindNote(q) ? ` (${kindNote(q).toLowerCase()})` : ""),
|
||||
`${parts.join(" · ")} · ${plural(t.ballots, "bulletin")}`);
|
||||
}
|
||||
return out.join("\n");
|
||||
}
|
||||
|
||||
// the long npppav label would eat the whole line
|
||||
const SHORT = { "ne prend pas part au vote": "NPPPAV" };
|
||||
|
||||
function list(poll, voters, qs) {
|
||||
const out = [poll.title];
|
||||
for (const q of qs) {
|
||||
const t = tally(q);
|
||||
const parts = rows(q, t).map((r) => `${SHORT[r.label.toLowerCase()] || r.label} (${r.n})`);
|
||||
out.push("", `${q.text} [${plural(t.ballots, "bulletin")}]`, parts.join(" / "));
|
||||
}
|
||||
return out.join("\n");
|
||||
}
|
||||
|
||||
function bars(poll, voters, qs) {
|
||||
const out = [poll.title];
|
||||
const W = 20;
|
||||
for (const q of qs) {
|
||||
const t = tally(q), rs = rows(q, t);
|
||||
const lw = Math.max(...rs.map((r) => width(r.label)));
|
||||
out.push("", q.text);
|
||||
for (const r of rs) {
|
||||
const full = Math.round((t.base ? r.n / t.base : 0) * W);
|
||||
const bar = r.p ? "█".repeat(Math.min(W, full)) + "░".repeat(Math.max(0, W - full)) : " ".repeat(W);
|
||||
out.push(`${padEnd(r.label, lw)} ${bar} ${r.n}${r.p ? ` · ${r.p}` : ""}`);
|
||||
}
|
||||
out.push(foot(q, t));
|
||||
}
|
||||
return out.join("\n");
|
||||
}
|
||||
|
||||
const mdCell = (s) => String(s).replace(/\|/g, "\\|");
|
||||
|
||||
function markdown(poll, voters, qs, now) {
|
||||
const [title, sub] = header(poll, voters, now);
|
||||
const out = [`# ${mdCell(title)}`, "", sub];
|
||||
qs.forEach((q, k) => {
|
||||
const t = tally(q);
|
||||
out.push("", `## ${nb(qs, k)}${q.text}`, "");
|
||||
if (kindNote(q)) out.push(`*${kindNote(q)}*`, "");
|
||||
out.push("| Réponse | Voix | % |", "| --- | ---: | ---: |");
|
||||
for (const r of rows(q, t)) out.push(`| ${mdCell(r.label)} | ${r.n} | ${r.p} |`);
|
||||
out.push("", `${foot(q, t)}.`);
|
||||
});
|
||||
return out.join("\n");
|
||||
}
|
||||
|
||||
// semicolons, the decimal comma makes plain commas ambiguous in french spreadsheets
|
||||
const csvCell = (v) => {
|
||||
const s = String(v);
|
||||
return /[;"\n\r]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
|
||||
};
|
||||
|
||||
function csv(poll, voters, qs) {
|
||||
const out = [["n", "question", "réponse", "voix", "dont ajoutées", "% exprimés"]];
|
||||
qs.forEach((q, k) => {
|
||||
const t = tally(q);
|
||||
q.options.forEach((o, i) => out.push([k + 1, q.text, o, t.tot[i], t.extra[i], num(pct(t.tot[i], t.base))]));
|
||||
if (q.allow_blank) out.push([k + 1, q.text, "Blanc", t.blank, t.exBlank, ""]);
|
||||
out.push([k + 1, q.text, "Bulletins", t.ballots, t.exBallots, ""]);
|
||||
});
|
||||
return out.map((r) => r.map(csvCell).join(";")).join("\n");
|
||||
}
|
||||
|
||||
export const FORMATS = [
|
||||
{ id: "pv", label: "Procès-verbal", ext: "txt", mime: "text/plain", build: minutes },
|
||||
{ id: "compact", label: "Compact", ext: "txt", mime: "text/plain", build: compact },
|
||||
{ id: "list", label: "Liste", ext: "txt", mime: "text/plain", build: list },
|
||||
{ id: "bars", label: "Barres", ext: "txt", mime: "text/plain", build: bars },
|
||||
{ id: "md", label: "Markdown", ext: "md", mime: "text/markdown", build: markdown },
|
||||
{ id: "csv", label: "CSV", ext: "csv", mime: "text/csv", build: csv },
|
||||
];
|
||||
|
||||
// closed questions only (nobody sees open tallies), in the order they were asked
|
||||
export function exportText(fmt, poll, voters, questions, now) {
|
||||
const qs = questions.filter((q) => q.state === "closed" && q.results).sort((a, b) => a.id - b.id);
|
||||
return fmt.build(poll, voters, qs, now);
|
||||
}
|
||||
Reference in New Issue
Block a user