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:
2026-11-19 01:01:54 +01:00
parent 3ebbb67817
commit 41b4ac1a78
5 changed files with 258 additions and 18 deletions
+20 -2
View File
@@ -126,8 +126,11 @@
<a id="open-present" class="btn small" href="#" target="_blank" rel="noopener">Ouvrir</a> <a id="open-present" class="btn small" href="#" target="_blank" rel="noopener">Ouvrir</a>
</div> </div>
<div class="share-row"> <div class="share-row">
<div><b>Résultats</b><span class="muted">Bulletins anonymes et décomptes</span></div> <div><b>Résultats</b><span class="muted">Exporter en texte ou JSON (anonyme)</span></div>
<button id="export" class="small" type="button">Exporter</button> <div class="code-actions">
<button id="export-text" class="small" type="button">Texte</button>
<button id="export" class="small" type="button">JSON</button>
</div>
</div> </div>
</div> </div>
</section> </section>
@@ -154,6 +157,21 @@
</form> </form>
</dialog> </dialog>
<dialog id="export-dlg">
<form method="dialog">
<h2>Exporter les résultats</h2>
<select id="ex-scope" aria-label="Questions"></select>
<div class="templates" id="ex-formats" role="radiogroup" aria-label="Modèle"></div>
<pre id="ex-preview" tabindex="0"></pre>
<div class="actions">
<button value="cancel" type="submit">Fermer</button>
<span class="spacer"></span>
<button id="ex-download" type="button">Télécharger</button>
<button id="ex-copy" class="primary" type="button">Copier</button>
</div>
</form>
</dialog>
<dialog id="composer"> <dialog id="composer">
<form method="dialog" id="q-form"> <form method="dialog" id="q-form">
<h2>Nouvelle question</h2> <h2>Nouvelle question</h2>
+16 -6
View File
@@ -54,18 +54,28 @@
.share-row > div:first-child { display: grid; } .share-row > div:first-child { display: grid; }
.share-row .muted { font-size: .85rem; } .share-row .muted { font-size: .85rem; }
#composer, #extra-dlg { border: none; border-radius: 24px; padding: 24px; width: min(94vw, 560px); background: var(--surface); color: var(--ink); } #composer, #extra-dlg, #export-dlg { border: none; border-radius: 24px; padding: 24px; width: min(94vw, 560px); background: var(--surface); color: var(--ink); }
#composer::backdrop, #extra-dlg::backdrop { background: rgba(28, 32, 54, .45); backdrop-filter: blur(2px); } #composer::backdrop, #extra-dlg::backdrop, #export-dlg::backdrop { background: rgba(28, 32, 54, .45); backdrop-filter: blur(2px); }
#composer[open], #extra-dlg[open] { animation: rise .2s ease-out; } #composer[open], #extra-dlg[open], #export-dlg[open] { animation: rise .2s ease-out; }
#composer h2, #extra-dlg h2 { font-size: 1.3rem; } #composer h2, #extra-dlg h2, #export-dlg h2 { font-size: 1.3rem; }
.spacer { flex: 1; } .spacer { flex: 1; }
@media (max-width: 560px) { @media (max-width: 560px) {
.summary-row > * { flex: 1 1 auto; } .summary-row > * { flex: 1 1 auto; }
#composer .actions button, #extra-dlg .actions button { flex: 1 1 100%; } #composer .actions button, #extra-dlg .actions button, #export-dlg .actions button { flex: 1 1 100%; }
#composer .spacer, #extra-dlg .spacer { display: none; } #composer .spacer, #extra-dlg .spacer, #export-dlg .spacer { display: none; }
} }
#q-opts { min-height: 132px; } #q-opts { min-height: 132px; }
.extra-row { margin: 8px 0; display: grid; grid-template-columns: 1fr 110px; gap: 12px; align-items: center; font-weight: 600; } .extra-row { margin: 8px 0; display: grid; grid-template-columns: 1fr 110px; gap: 12px; align-items: center; font-weight: 600; }
.extra-row input { text-align: right; } .extra-row input { text-align: right; }
#export-dlg { width: min(94vw, 720px); }
#ex-scope { margin-bottom: 12px; }
#ex-scope[hidden] { display: none; }
#ex-formats button[aria-checked="true"] { background: var(--mark); border-color: var(--mark); color: var(--ink); }
#ex-preview {
margin: 12px 0 0; padding: 14px 16px; max-height: 50vh; overflow: auto; background: var(--bg); border-radius: var(--r-field);
font: .82rem/1.5 ui-monospace, "SF Mono", Menlo, Consolas, monospace; white-space: pre; tab-size: 4;
}
#ex-preview.empty { white-space: normal; color: var(--ink-3); font-family: var(--sans); text-align: center; padding: 32px 16px; }
+67
View File
@@ -1,9 +1,11 @@
import { $, h, api, pollId, takeKey, liveSocket, resultsView, STATE_LABEL, toast, fill, pct, icon } from "./common.js"; 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 pid = pollId();
const key = takeKey(`rv_admin_${pid}`); const key = takeKey(`rv_admin_${pid}`);
const base = `/api/polls/${pid}`; const base = `/api/polls/${pid}`;
const TAB_KEY = "rv_admin_tab"; const TAB_KEY = "rv_admin_tab";
const FMT_KEY = "rv_export_fmt";
let state = null; let state = null;
const TEMPLATES = [ const TEMPLATES = [
@@ -127,6 +129,7 @@ function questionCard(q) {
if (!q.shown) actions.push(act("Rouvrir le vote", "reopen")); 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 !== "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")); 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])]; 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"); } } 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`, { liveSocket(`/ws/${pid}/admin`, {
auth: key, auth: key,
onMessage(msg) { onMessage(msg) {
+7 -10
View File
@@ -1,3 +1,6 @@
import { tally, pct } from "./export.js";
export { pct };
export const $ = (sel, root = document) => root.querySelector(sel); export const $ = (sel, root = document) => root.querySelector(sel);
// tiny element builder, children are always text nodes or elements so no html injection // 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 // CSSOM write, a style="" attribute would be blocked by the CSP
export function fill(percent, cls = "bar-fill") { export function fill(percent, cls = "bar-fill") {
@@ -115,16 +115,13 @@ export function fill(percent, cls = "bar-fill") {
} }
export function resultsView(q) { export function resultsView(q) {
const r = q.results; if (!q.results) return null;
if (!r) return null;
// votes added by hand ride at the end of each bar, hatched orange, so nobody mistakes them for phone ballots // 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 { phone, extra, tot, ballots, blank, base, exBallots } = tally(q);
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 max = Math.max(1, ...tot); const max = Math.max(1, ...tot);
const rows = q.options.map((label, i) => { const rows = q.options.map((label, i) => {
const stack = h("div", { class: "bar-stack" }, 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)}%`; stack.style.width = `${pct(tot[i], max)}%`;
return h("div", { class: "bar-row" + (tot[i] === max && tot[i] > 0 ? " lead" : "") }, return h("div", { class: "bar-row" + (tot[i] === max && tot[i] > 0 ? " lead" : "") },
h("div", { class: "bar-label" }, label), h("div", { class: "bar-label" }, label),
@@ -137,7 +134,7 @@ export function resultsView(q) {
h("p", { class: "results-foot" }, h("p", { class: "results-foot" },
`${ballots} bulletin${ballots > 1 ? "s" : ""}`, `${ballots} bulletin${ballots > 1 ? "s" : ""}`,
q.allow_blank ? `, dont ${blank} blanc${blank > 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`) : "",
), ),
); );
} }
+148
View File
@@ -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);
}