From 60dcf887cf6709412bce022b29a4ff87ca7fa5a2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A1ssio?= Date: Thu, 26 Nov 2026 21:41:20 +0000 Subject: [PATCH] =?UTF-8?q?feat:=20vota=C3=A7=C3=A3o=20com=20pergunta=20e?= =?UTF-8?q?=20m=C3=BAltipla=20escolha?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Um slide pode definir `poll: { question, options }` (2 a 6 opções). Com ela, P abre a votação com a pergunta escrita: a plateia vê a lista de opções, o telão e o passador mostram uma barra por opção, e as métricas guardam a pergunta e os votos de cada opção. Sem `poll`, continua o 👍/👎 de sempre. O voto passa a ser o índice da opção; "up"/"down" ainda são aceitos como 0/1. Métricas antigas (up/down) continuam aparecendo no relatório. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RTybDNU1NDt27r8RzXc996 --- AGENTS.md | 3 +- backstage/README.md | 15 +++++---- backstage/i18n.ts | 4 +++ backstage/metrics.ts | 19 +++++++---- backstage/protocol.ts | 11 +++--- backstage/public/index.html | 42 +++++++++++++++++------ backstage/report.ts | 19 ++++++++--- backstage/server.ts | 43 ++++++++++++++++++------ backstage/test/server.test.ts | 52 +++++++++++++++++++++++++---- deck/README.md | 2 +- deck/app/globals.css | 14 ++++++++ deck/components/Deck.tsx | 2 +- deck/components/Live.tsx | 43 ++++++++++++++++-------- deck/components/Remote.tsx | 25 ++++++++++---- deck/components/i18n.ts | 4 +++ deck/components/poll.ts | 11 ++++++ deck/components/types.ts | 5 +-- deck/talks/starter/slides/index.tsx | 5 +-- 18 files changed, 246 insertions(+), 73 deletions(-) create mode 100644 deck/components/poll.ts diff --git a/AGENTS.md b/AGENTS.md index 1cc5749..109705e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -55,6 +55,7 @@ motor enxerga a apresentação só por `components/content.ts`, e o contrato est kind: "title", // opcional: "title" | "statement" | "final" top: true, // opcional: alinha ao topo e reduz o título (slide com muito conteúdo) links: [{ label: "Texto", url: "https://..." }], // liberados para a plateia a partir deste slide + poll: { question: "Qual você usa?", options: ["A", "B", "C"] }, // opcional: votação deste slide (2 a 6 opções); sem ela, P abre 👍/👎 content: (<>

Título

Texto

), notes:

Lembrete para o apresentador.

, } @@ -90,7 +91,7 @@ Todo slide tem, por cima do conteúdo e sem você escrever nada: - **o autor** (`author.name` e `author.tagline` do config), no canto inferior esquerdo. Não repita o nome no slide: no título e no encerramento, use a linha de assinatura para outra coisa (cargo, contato, link dos slides). - **o QR da plateia**, pequeno (112 px) no canto inferior direito, com o endereço e o contador `04 / 12` ao lado. - em `title` e `final`, **o QR grande** ocupa a metade direita, o contador some e o texto fica limitado a 940 px de largura. -- **o placar da votação**, enquanto ela está aberta, numa faixa no rodapé central. A pergunta pode estar escrita no slide ou só ser falada; não ponha nada essencial nos últimos 120 px do slide de uma votação. +- **o placar da votação**, enquanto ela está aberta, no rodapé central. Sem `poll` no slide, é uma faixa 👍/👎 e a pergunta é falada; não ponha nada essencial nos últimos 120 px do slide de uma votação. Com `poll`, o painel mostra a pergunta e uma barra por opção e cresce com elas (cerca de 300 px com quatro opções): deixe a metade de baixo do slide livre, ou use um slide só para a pergunta. O QR só existe com o backstage no ar. No PDF ele sai apenas se houver endereço fixo, então para conferir se algum conteúdo passa por baixo dele gere com `NEXT_PUBLIC_QR_URL=https://example.com TALK= npm run png`. diff --git a/backstage/README.md b/backstage/README.md index 18e347c..2fb09a6 100644 --- a/backstage/README.md +++ b/backstage/README.md @@ -1,8 +1,9 @@ # Backstage ao vivo Página que a plateia abre pelo QR (grande no primeiro e no último slide, pequeno no canto dos -outros): vê o slide atual, os links já citados, reage (as reações vêm do `deck.config.json`) e vota 👍/👎 quando o -apresentador abre uma votação, em qualquer slide e sem pergunta escrita (a pergunta é falada). +outros): vê o slide atual, os links já citados, reage (as reações vêm do `deck.config.json`) e vota quando o +apresentador abre uma votação, em qualquer slide: 👍/👎 com a pergunta falada, ou a pergunta e as +opções que o slide define em `poll`. As reações aparecem flutuando no projetor. Quantas pessoas estão conectadas e se o robô está ligado aparecem **só no passador** do @@ -86,7 +87,7 @@ Se o celular sumir no meio de um gesto, o ponteiro apaga sozinho em 5 s. `/apresentador/metricas` mostra, para consultar depois da palestra: pico de pessoas (com horário), celulares únicos, visitas à página, reações da plateia por tipo (as do robô contadas à parte), -cada votação (slide, 👍, 👎, horário, duração), cliques em cada link, tempo/reações/pico por slide +cada votação (slide, pergunta, votos por opção, horário, duração), cliques em cada link, tempo/reações/pico por slide e uma linha do tempo a cada 10 s. `metricas.json` baixa tudo em JSON. Fica em `metrics.json` dentro de `DATA_DIR` (no compose, o volume `data` em `/data`), gravado a @@ -107,7 +108,7 @@ Sem dado pessoal: "celular" é um id aleatório que a página da plateia gera e ## Teclas no deck - `L` liga/desliga o robô: se a plateia fica em silêncio por 20 s (`BOT_SILENCE_MS`), ele solta uma rajada curta de reações, indistinguíveis das da plateia. -- `P` abre/fecha a votação 👍/👎, em qualquer slide (também pelo passador). Reabrir zera o placar. +- `P` abre/fecha a votação (👍/👎, ou a `poll` do slide), em qualquer slide (também pelo passador). Reabrir zera o placar. ## Código @@ -124,12 +125,12 @@ no Docker). O idioma das páginas e do terminal é o `lang` do mesmo arquivo. Os tipos estão em [`protocol.ts`](protocol.ts), que o deck também importa; o resumo: -Plateia → servidor (`/ws`): `{type:"react", kind}` · `{type:"vote", choice:"up"|"down", cid}` (dá para trocar de voto; `cid` é o id do celular, guardado no navegador, e um voto por `cid` sobrevive a reconexões) -Deck → servidor (`/apresentador/ws`): `{type:"slide", index, title, links}` · `{type:"view", index, step, steps, black, notes, full, elapsed}` · `{type:"shot", data}` (data URL JPEG, até 2 MB, só com o envio ligado) · `{type:"bot", on}` · `{type:"poll", open}` +Plateia → servidor (`/ws`): `{type:"react", kind}` · `{type:"vote", choice, cid}` (`choice` é o índice da opção; `"up"`/`"down"` ainda valem como 0/1) (dá para trocar de voto; `cid` é o id do celular, guardado no navegador, e um voto por `cid` sobrevive a reconexões) +Deck → servidor (`/apresentador/ws`): `{type:"slide", index, title, links, poll?}` (`poll` = `{question, options}` do slide, 2 a 6 opções) · `{type:"view", index, step, steps, black, notes, full, elapsed}` · `{type:"shot", data}` (data URL JPEG, até 2 MB, só com o envio ligado) · `{type:"bot", on}` · `{type:"poll", open}` Passador → servidor (`/apresentador/ws`): `{type:"hello", as:"remote"}` · `{type:"key", key}` (`ArrowRight`, `ArrowLeft`, `b`, `v`, `f`) · `{type:"share", on}` · `{type:"pointer", x, y, mode, tap}` / `{type:"pointer", off:true}` · `{type:"bot"}` · `{type:"poll"}` Servidor → deck: `{type:"key", key}` (só para a janela sem notas) · `{type:"pointer", ...}` Servidor → passador: `{type:"view", ..., decks}` -Servidor → plateia: `{type:"state", state:{slide, links, poll:{id, open, up, down}, share:{on, v}}}` (`v` muda a cada foto; a plateia busca `/tela.jpg?v=`) (quando muda slide, link ou votação; votos no máximo a cada 250 ms) +Servidor → plateia: `{type:"state", state:{slide, links, poll:{id, open, question, options, counts}, share:{on, v}}}` (`v` muda a cada foto; a plateia busca `/tela.jpg?v=`) (quando muda slide, link ou votação; votos no máximo a cada 250 ms) Servidor → palco (deck e passador): o mesmo `state` com `connected`, `bot` e `publicUrl` (o endereço do QR), e de novo a cada entrada e saída de alguém Servidor → todos: `{type:"burst", h:{clap:n,...}}` a cada 250 ms (plateia e robô no mesmo lote) diff --git a/backstage/i18n.ts b/backstage/i18n.ts index c5f8769..cb11bc3 100644 --- a/backstage/i18n.ts +++ b/backstage/i18n.ts @@ -64,6 +64,8 @@ const ptBR = { enteredAt: "entrou às", noSlides: "nenhum slide registrado ainda", pollsTitle: "Votações", + question: "pergunta", + result: "resultado", openedAt: "aberta às", duration: "duração", open: "aberta", @@ -146,6 +148,8 @@ const en: Messages = { enteredAt: "entered at", noSlides: "no slide recorded yet", pollsTitle: "Polls", + question: "question", + result: "result", openedAt: "opened at", duration: "duration", open: "open", diff --git a/backstage/metrics.ts b/backstage/metrics.ts index 92389c6..9142ad6 100644 --- a/backstage/metrics.ts +++ b/backstage/metrics.ts @@ -5,7 +5,11 @@ const TIMELINE_MAX = 20000; const iso = (t = Date.now()) => new Date(t).toISOString(); type SlideRecord = { title: string; timeMs: number; reactions: number; peakAudience: number; firstAt: string }; -export type PollRecord = { n: number; slide: number | null; slideTitle: string; openedAt: string; closedAt: string | null; up: number; down: number }; +// `up`/`down` só existem em métricas gravadas antes da votação com opções +export type PollRecord = { + n: number; slide: number | null; slideTitle: string; openedAt: string; closedAt: string | null; + question?: string; options?: string[]; counts?: number[]; up?: number; down?: number; +}; export type TimelinePoint = { t: string; a: number; r: number; b: number; v: number; s: number | null }; type Stored = { @@ -29,7 +33,7 @@ export type Report = Omit & { archives: string[]; }; -type Tally = { up: number; down: number }; +type Tally = { question: string; options: string[]; counts: number[] }; function blank(): Stored { return { @@ -96,14 +100,17 @@ export function createMetrics({ dataDir, getAudience }: { dataDir: string | unde current = { index, title, at: now }; slideRec(index, title); }, - pollOpen() { - livePoll = { n: m.polls.length + 1, slide: current ? current.index + 1 : null, slideTitle: current ? current.title : "", openedAt: iso(), closedAt: null, up: 0, down: 0 }; + pollOpen(poll: Tally) { + livePoll = { + n: m.polls.length + 1, slide: current ? current.index + 1 : null, slideTitle: current ? current.title : "", openedAt: iso(), closedAt: null, + question: poll.question, options: [...poll.options], counts: [...poll.counts], + }; m.polls.push(livePoll); }, - pollVote(poll: Tally) { win.v++; if (livePoll) { livePoll.up = poll.up; livePoll.down = poll.down; } }, + pollVote(poll: Tally) { win.v++; if (livePoll) livePoll.counts = [...poll.counts]; }, pollClose(poll: Tally) { if (!livePoll) return; - livePoll.up = poll.up; livePoll.down = poll.down; livePoll.closedAt = iso(); + livePoll.counts = [...poll.counts]; livePoll.closedAt = iso(); livePoll = null; }, tick() { diff --git a/backstage/protocol.ts b/backstage/protocol.ts index b808395..edcc20e 100644 --- a/backstage/protocol.ts +++ b/backstage/protocol.ts @@ -2,7 +2,11 @@ // a plateia, /apresentador/ws é o palco), nunca de uma mensagem. export type Link = { label: string; url: string }; -export type Poll = { id: number; open: boolean; up: number; down: number }; +// pergunta definida no slide (`poll` em SlideBase); sem ela, a votação é 👍/👎 com a pergunta falada +export type PollSpec = { question: string; options: string[] }; + +// `counts[i]` é o total da opção `options[i]`; `question` vazia = pergunta falada +export type Poll = { id: number; open: boolean; question: string; options: string[]; counts: number[] }; // envio da tela para a plateia; `v` muda a cada foto (0 = nenhuma ainda) e vai em /tela.jpg?v= export type Share = { on: boolean; v: number }; @@ -18,11 +22,10 @@ export type StageState = PublicState & { connected: number; bot: boolean; public export type RemoteKey = "ArrowRight" | "ArrowLeft" | "b" | "v" | "f"; export type PointerMode = "laser" | "spot"; -export type Vote = "up" | "down"; export type AudienceMessage = | { type: "react"; kind: string } - | { type: "vote"; choice: Vote; cid?: string } + | { type: "vote"; choice: number; cid?: string } // índice em poll.options | { type: "click"; url: string }; export type StageCommand = @@ -31,7 +34,7 @@ export type StageCommand = | { type: "share"; on: boolean }; export type DeckMessage = - | { type: "slide"; index: number; title: string; links: Link[] } + | { type: "slide"; index: number; title: string; links: Link[]; poll?: PollSpec } | { type: "view"; index: number; step: number; steps: number; black: boolean; notes: boolean; full: boolean; elapsed: number | null } | { type: "shot"; data: string } // data URL JPEG, até 2 MB, só com o envio ligado | StageCommand; diff --git a/backstage/public/index.html b/backstage/public/index.html index ab2597c..6e03a86 100644 --- a/backstage/public/index.html +++ b/backstage/public/index.html @@ -37,6 +37,9 @@ .vote button { font-size: 52px; line-height: 1; padding: 22px 0; background: var(--surface); border: 3px solid var(--line); border-radius: 18px; touch-action: manipulation; user-select: none; -webkit-user-select: none; transition: transform .1s; } .vote button:active { transform: scale(.94); } .vote button.on { border-color: var(--accent); background: var(--accent-soft); } + .vote h3 { grid-column: 1 / -1; margin: 0 0 2px; font-size: 19px; line-height: 1.3; } + .vote.choices { grid-template-columns: 1fr; gap: 8px; } + .vote.choices button { font-size: 17px; font-weight: 600; line-height: 1.3; padding: 14px 16px; text-align: left; color: var(--fg); } @keyframes pop { from { opacity: 0; transform: scale(.96); } } footer { padding: 12px 16px calc(14px + env(safe-area-inset-bottom)); background: var(--surface); border-top: 2px solid var(--line); display: grid; grid-template-columns: repeat(var(--n, 4), 1fr); gap: 10px; position: sticky; bottom: 0; } footer button { font-size: 34px; line-height: 1; padding: 14px 0; background: var(--bg); border: 2px solid var(--line); border-radius: 16px; color: var(--fg); touch-action: manipulation; user-select: none; -webkit-user-select: none; transition: transform .1s; } @@ -65,10 +68,7 @@

{{title}}

{{t.tapToZoom}} - +

{{t.links}}

@@ -146,14 +146,34 @@

{{t.links}}

if (first && navigator.vibrate) navigator.vibrate(30); } const opened = s.poll.open && !poll.open; + const changed = s.poll.id !== poll.id || !poll.options; poll = s.poll; + if (changed) renderVote(); $("vote").hidden = !poll.open; markVote(); if (opened && navigator.vibrate) navigator.vibrate(30); } + // Sem pergunta e com 👍/👎, os dois botões grandes; com pergunta, uma lista de opções. O texto + // vem do deck: entra com textContent, nunca como HTML. + function renderVote() { + const box = $("vote"); + const opts = poll.options || []; + const thumbs = !poll.question && opts.length === 2 && opts[0] === "👍" && opts[1] === "👎"; + box.classList.toggle("choices", !thumbs); + const kids = []; + if (poll.question) { const h = document.createElement("h3"); h.textContent = poll.question; kids.push(h); } + opts.forEach((o, i) => { + const b = document.createElement("button"); + b.dataset.choice = String(i); + b.textContent = o; + if (thumbs) b.setAttribute("aria-label", i === 0 ? box.dataset.yes : box.dataset.no); + kids.push(b); + }); + box.replaceChildren(...kids); + } function markVote() { const mine = store.get("vote"); - const choice = mine && mine.id === poll.id ? mine.choice : null; + const choice = mine && mine.id === poll.id ? String(mine.choice) : null; document.querySelectorAll("#vote button").forEach((b) => b.classList.toggle("on", b.dataset.choice === choice)); } $("tela-open").addEventListener("click", () => { @@ -166,13 +186,15 @@

{{t.links}}

const a = e.target.closest("a[data-url]"); if (a && ws && ws.readyState === 1) ws.send(JSON.stringify({ type: "click", url: a.dataset.url })); }); - document.querySelectorAll("#vote button").forEach((b) => b.addEventListener("click", () => { - if (!poll.open || !ws || ws.readyState !== 1) return; - ws.send(JSON.stringify({ type: "vote", choice: b.dataset.choice, cid })); - store.set("vote", { id: poll.id, choice: b.dataset.choice }); + $("vote").addEventListener("click", (e) => { + const b = e.target.closest("button[data-choice]"); + if (!b || !poll.open || !ws || ws.readyState !== 1) return; + const choice = Number(b.dataset.choice); + ws.send(JSON.stringify({ type: "vote", choice, cid })); + store.set("vote", { id: poll.id, choice }); markVote(); if (navigator.vibrate) navigator.vibrate(12); - })); + }); const PER_BURST = 4, MAX_FLYING = 24; let flying = 0; function sample(counts, max) { diff --git a/backstage/report.ts b/backstage/report.ts index 5803c60..20f2726 100644 --- a/backstage/report.ts +++ b/backstage/report.ts @@ -1,5 +1,5 @@ import type { Config } from "./config.ts"; -import type { Report, TimelinePoint } from "./metrics.ts"; +import type { PollRecord, Report, TimelinePoint } from "./metrics.ts"; import type { Link } from "./protocol.ts"; const esc = (s: unknown) => String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c] ?? c); @@ -63,7 +63,18 @@ export function renderReport(r: Report, links: Link[], config: Config): string { const kinds = Object.entries(r.reactions.byKind).sort((a, b) => b[1] - a[1]).map(([k, n]) => `${esc(emoji[k] || k)} ${n}`).join(" · ") || "—"; const clicks = Object.entries(r.linkClicks).sort((a, b) => b[1] - a[1]); const totalClicks = clicks.reduce((a, [, n]) => a + n, 0); - const totalVotes = r.polls.reduce((a, p) => a + p.up + p.down, 0); + // métricas antigas guardavam só 👍/👎 em up/down + const tally = (p: PollRecord) => { + const options = p.options ?? ["👍", "👎"]; + const counts = p.counts ?? [p.up ?? 0, p.down ?? 0]; + return options.map((o, i) => ({ label: o, n: counts[i] ?? 0 })); + }; + const totalVotes = r.polls.reduce((a, p) => a + tally(p).reduce((b, o) => b + o.n, 0), 0); + const result = (p: PollRecord) => { + const opts = tally(p); + const max = Math.max(0, ...opts.map((o) => o.n)); + return opts.map((o) => (max && o.n === max ? `${esc(o.label)} ${o.n}` : `${esc(o.label)} ${o.n}`)).join(" · "); + }; const card = (n: number, text: string, sub = "") => `
${n}${esc(text)}${sub ? `${sub}` : ""}
`; const pad = (n: number) => String(n).padStart(2, "0"); const empty = (cols: number, text: string) => `${esc(text)}`; @@ -91,8 +102,8 @@ ${chart(r.timeline)} ${r.slides.map((s) => `${pad(s.slide)}${esc(s.title)}${dur(s.timeMs)}${s.reactions}${s.peakAudience}${time(s.firstAt)}`).join("") || empty(6, t.noSlides)}

${esc(t.pollsTitle)}

-
-${r.polls.map((p) => ``).join("") || empty(6, t.noPolls)} +
#${esc(t.slide)}👍👎${esc(t.openedAt)}${esc(t.duration)}
${p.n}${p.slide ? pad(p.slide) + " · " : ""}${esc(p.slideTitle)}${p.up}${p.down}${time(p.openedAt)}${p.closedAt ? dur(Date.parse(p.closedAt) - Date.parse(p.openedAt)) : esc(t.open)}
+${r.polls.map((p) => ``).join("") || empty(7, t.noPolls)}
#${esc(t.slide)}${esc(t.question)}${esc(t.result)}${esc(t.openedAt)}${esc(t.duration)}
${p.n}${p.slide ? pad(p.slide) + " · " : ""}${esc(p.slideTitle)}${esc(p.question || "—")}${result(p)}${time(p.openedAt)}${p.closedAt ? dur(Date.parse(p.closedAt) - Date.parse(p.openedAt)) : esc(t.open)}

${esc(t.clicksTitle)}

diff --git a/backstage/server.ts b/backstage/server.ts index 18caaa6..264698f 100644 --- a/backstage/server.ts +++ b/backstage/server.ts @@ -9,7 +9,7 @@ import { WebSocketServer } from "ws"; import type { WebSocket } from "ws"; import { httpUrl, loadConfig } from "./config.ts"; import { createMetrics } from "./metrics.ts"; -import type { PointerMessage, Poll, PublicState, RemoteKey, ServerMessage, Share, StageState, ViewMessage, Vote } from "./protocol.ts"; +import type { PointerMessage, Poll, PollSpec, PublicState, RemoteKey, ServerMessage, Share, StageState, ViewMessage } from "./protocol.ts"; import { renderReport } from "./report.ts"; const PORT = Number(process.env.PORT || 8080); @@ -54,16 +54,30 @@ function deny(res: ServerResponse) { res.end(DENIED); } -const state: { slide: PublicState["slide"]; links: PublicState["links"]; bot: boolean; poll: Poll; share: Share } = { +const state: { slide: PublicState["slide"]; links: PublicState["links"]; bot: boolean; poll: Poll; share: Share; slidePoll: PollSpec | null } = { slide: { index: 0, title: "" }, links: [], bot: false, - poll: { id: 0, open: false, up: 0, down: 0 }, + poll: { id: 0, open: false, question: "", options: ["👍", "👎"], counts: [0, 0] }, share: { on: false, v: 0 }, + slidePoll: null, // a pergunta do slide atual, usada quando o apresentador abre a votação }; + +// Sem pergunta no slide, a votação é 👍/👎 e a pergunta é falada. +const THUMBS: PollSpec = { question: "", options: ["👍", "👎"] }; +const POLL_OPTIONS_MAX = 6; +// A definição vem do deck, mas é conferida como qualquer entrada: texto curto, 2 a 6 opções. +function pollSpec(v: unknown): PollSpec | null { + if (typeof v !== "object" || v === null) return null; + const { question, options } = v as { question?: unknown; options?: unknown }; + if (!Array.isArray(options)) return null; + const opts = options.filter((o): o is string => typeof o === "string").map((o) => o.trim().slice(0, 80)).filter(Boolean).slice(0, POLL_OPTIONS_MAX); + if (opts.length < 2) return null; + return { question: typeof question === "string" ? question.trim().slice(0, 200) : "", options: opts }; +} let shot: Buffer | null = null; const SHOT_MAX = 2 * 1024 * 1024; -const votes = new Map(); +const votes = new Map(); let lastHumanReaction = 0; const metrics = createMetrics({ dataDir: process.env.DATA_DIR, getAudience: () => audience() }); @@ -271,15 +285,18 @@ wss.on("connection", (ws: Client) => { break; } case "vote": { - if (!state.poll.open || (m.choice !== "up" && m.choice !== "down")) return; + // "up"/"down" é o formato antigo da página da plateia (aberta antes de atualizar o servidor) + const choice = m.choice === "up" ? 0 : m.choice === "down" ? 1 : m.choice; + if (!state.poll.open || typeof choice !== "number" || !Number.isInteger(choice) || choice < 0 || choice >= state.poll.counts.length) return; // O celular manda um id que guarda no navegador: reconectar (tela apagada) não vira voto novo. // Cada socket fica com o primeiro id que mandou, para não dar para inflar trocando o id. ws.cid ??= ws.connCid || validCid(m.cid) || `ws:${Math.random()}`; const prev = votes.get(ws.cid); - if (prev === m.choice) return; - if (prev) state.poll[prev]--; - state.poll[m.choice]++; - votes.set(ws.cid, m.choice); + if (prev === choice) return; + const counts = state.poll.counts; + if (prev !== undefined) counts[prev] = (counts[prev] ?? 1) - 1; + counts[choice] = (counts[choice] ?? 0) + 1; + votes.set(ws.cid, choice); metrics.pollVote(state.poll); sendStateSoon(); break; @@ -300,6 +317,7 @@ wss.on("connection", (ws: Client) => { const { url: u, label } = l as { url?: unknown; label?: unknown }; if (typeof u === "string" && u && !state.links.some((k) => k.url === u)) state.links.push({ label: String(label || u), url: u }); } + state.slidePoll = pollSpec(m.poll); sendState(); break; } @@ -352,7 +370,12 @@ wss.on("connection", (ws: Client) => { break; case "poll": if (!stage) return; - if (m.open && !state.poll.open) { state.poll = { id: state.poll.id + 1, open: true, up: 0, down: 0 }; votes.clear(); metrics.pollOpen(); } + if (m.open && !state.poll.open) { + const spec = state.slidePoll ?? THUMBS; + state.poll = { id: state.poll.id + 1, open: true, question: spec.question, options: [...spec.options], counts: spec.options.map(() => 0) }; + votes.clear(); + metrics.pollOpen(state.poll); + } else if (!m.open && state.poll.open) { state.poll.open = false; metrics.pollClose(state.poll); } sendState(); break; diff --git a/backstage/test/server.test.ts b/backstage/test/server.test.ts index 88fa4ab..c5084ad 100644 --- a/backstage/test/server.test.ts +++ b/backstage/test/server.test.ts @@ -191,16 +191,56 @@ test("votação: o palco abre, a plateia vota uma vez por celular e pode trocar" const phone = await connect(srv.port, "/ws?cid=votante00001"); deck.say({ type: "poll", open: true }); await phone.next(publicWhere((s) => s.poll.open)); - phone.say({ type: "vote", choice: "up" }); - phone.say({ type: "vote", choice: "up" }); - await deck.next(stageWhere((s) => s.poll.up === 1)); - phone.say({ type: "vote", choice: "down" }); - const s = await deck.next(stageWhere((st) => st.poll.down === 1)); - assert.equal(s.state.poll.up, 0); + phone.say({ type: "vote", choice: 0 }); + phone.say({ type: "vote", choice: 0 }); + await deck.next(stageWhere((s) => s.poll.counts[0] === 1)); + phone.raw({ type: "vote", choice: "down" }); // formato antigo da página da plateia + const s = await deck.next(stageWhere((st) => st.poll.counts[1] === 1)); + assert.deepEqual(s.state.poll.counts, [0, 1]); + assert.deepEqual(s.state.poll.options, ["👍", "👎"]); deck.say({ type: "poll", open: false }); deck.close(); phone.close(); }); +test("votação com pergunta: o slide define as opções e voto fora delas é ignorado", async () => { + const deck = await connect(srv.port, "/apresentador/ws", { cookie }); + const phone = await connect(srv.port, "/ws?cid=votante00002"); + const other = await connect(srv.port, "/ws?cid=votante00003"); + deck.say({ type: "slide", index: 4, title: "Pergunta", links: [], poll: { question: " Qual você usa? ", options: ["A", " B ", "", "C"] } }); + await phone.next(publicWhere((st) => st.slide.title === "Pergunta")); + deck.say({ type: "poll", open: true }); + const opened = await phone.next(publicWhere((st) => st.poll.open)); + assert.equal(opened.state.poll.question, "Qual você usa?"); + assert.deepEqual(opened.state.poll.options, ["A", "B", "C"]); + assert.deepEqual(opened.state.poll.counts, [0, 0, 0]); + phone.say({ type: "vote", choice: 2 }); + other.say({ type: "vote", choice: 2 }); + phone.say({ type: "vote", choice: 3 }); + phone.raw({ type: "vote", choice: 1.5 }); + phone.raw({ type: "vote", choice: -1 }); + await deck.next(stageWhere((st) => st.poll.counts[2] === 2)); + phone.say({ type: "vote", choice: 0 }); + const s = await deck.next(stageWhere((st) => st.poll.counts[0] === 1)); + assert.deepEqual(s.state.poll.counts, [1, 0, 1]); + deck.say({ type: "poll", open: false }); + await phone.next(publicWhere((st) => !st.poll.open)); + const report = await (await fetch(srv.base + "/apresentador/metricas.json", { headers: { cookie } })).json() as { polls: { question?: string; options?: string[]; counts?: number[] }[] }; + const last = report.polls.at(-1); + assert.equal(last?.question, "Qual você usa?"); + assert.deepEqual(last?.counts, [1, 0, 1]); + assert.match(await (await fetch(srv.base + "/apresentador/metricas", { headers: { cookie } })).text(), /Qual você usa\?/); + + // slide sem `poll` (ou com definição inválida) volta ao 👍/👎 + deck.say({ type: "slide", index: 5, title: "Sem pergunta", links: [], poll: { question: "só uma", options: ["X"] } as never }); + await phone.next(publicWhere((st) => st.slide.title === "Sem pergunta")); + deck.say({ type: "poll", open: true }); + const thumbs = await phone.next(publicWhere((st) => st.poll.open && st.poll.id > opened.state.poll.id)); + assert.equal(thumbs.state.poll.question, ""); + assert.deepEqual(thumbs.state.poll.options, ["👍", "👎"]); + deck.say({ type: "poll", open: false }); + deck.close(); phone.close(); other.close(); +}); + test("o deck libera links para a plateia; entrada malformada não derruba o servidor", async () => { const deck = await connect(srv.port, "/apresentador/ws", { cookie }); const phone = await connect(srv.port, "/ws"); diff --git a/deck/README.md b/deck/README.md index 7a0d931..bddd8fb 100644 --- a/deck/README.md +++ b/deck/README.md @@ -53,7 +53,7 @@ escolha "Salvar como PDF", margens "Nenhuma" e "Gráficos de plano de fundo". `←` `→` `espaço` `PgUp`/`PgDn` navegar (funciona com passador de slides) · `N` notas do apresentador · `O` visão geral · `F` tela cheia · `T` tema claro/escuro · `B` ou `.` tela preta · -`R` zera o cronômetro · `V` toca/pausa o vídeo · `L` robô das reações · `P` votação 👍/👎 · +`R` zera o cronômetro · `V` toca/pausa o vídeo · `L` robô das reações · `P` votação (👍/👎, ou a pergunta de `poll` do slide) · `Home`/`End`. ## Apresentando diff --git a/deck/app/globals.css b/deck/app/globals.css index 83144e1..c786aac 100644 --- a/deck/app/globals.css +++ b/deck/app/globals.css @@ -256,6 +256,14 @@ pre.code .w { color: var(--warn); border-radius: 4px; } .poll-bar.empty { background: var(--line); } .poll-bar div { height: 100%; background: var(--accent); transition: width .6s var(--ease-out); } .poll-bar.empty div { background: transparent; } +/* votação com pergunta: uma linha por opção, a barra mostra a fatia de cada uma */ +.poll.multi { display: grid; gap: 10px; width: min(760px, 50vw); padding: 18px 26px; } +.poll.multi h3 { margin: 0 0 2px; font: 700 30px/1.2 var(--font-display), ui-sans-serif, system-ui, sans-serif; } +.poll-row { display: grid; grid-template-columns: minmax(0, 38%) 1fr 3.5ch; align-items: center; gap: 14px; } +.poll-label { font-size: 24px; font-weight: 600; line-height: 1.2; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.poll.multi b { font-size: 32px; } +.poll.multi .poll-bar.empty div { background: var(--accent); } +.poll.multi small { color: var(--muted); font-size: 16px; text-align: right; } .pointer-layer { pointer-events: none; z-index: 9; } .pointer-layer.off { opacity: 0; transition: opacity .5s ease .8s; } @@ -318,6 +326,12 @@ pre.code .w { color: var(--warn); border-radius: 4px; } .remote .vote-strip b { font-size: 22px; } .remote .vote-strip .bar { flex: 1; height: 12px; border-radius: 6px; background: var(--warn); overflow: hidden; } .remote .vote-strip .bar div { height: 100%; background: var(--accent); transition: width .4s var(--ease-out); } +.remote .vote-strip.multi { display: grid; gap: 6px; font-size: 15px; } +.remote .vote-strip.multi p { margin: 0; font-family: inherit; font-weight: 700; } +.remote .vote-strip.multi .row { display: grid; grid-template-columns: minmax(0, 40%) 1fr 3ch; align-items: center; gap: 8px; } +.remote .vote-strip.multi .row span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.remote .vote-strip.multi .bar.empty { background: var(--line); } +.remote .vote-strip.multi b { font-size: 18px; text-align: right; } .remote .tools { display: flex; gap: 8px; } .remote .tools button { flex: 1 1 0; min-width: 0; min-height: 50px; padding: 0 4px; border-radius: 12px; border: 2px solid var(--line); background: var(--surface); font-size: 14px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; touch-action: manipulation; } .remote .tools button:last-child { flex: 0 0 56px; } diff --git a/deck/components/Deck.tsx b/deck/components/Deck.tsx index 57112f5..c244379 100644 --- a/deck/components/Deck.tsx +++ b/deck/components/Deck.tsx @@ -282,7 +282,7 @@ export default function Deck({ index: initial }: { index: number }) { diff --git a/deck/components/Live.tsx b/deck/components/Live.tsx index 8f4dda7..1530c3f 100644 --- a/deck/components/Live.tsx +++ b/deck/components/Live.tsx @@ -4,7 +4,8 @@ import { useEffect, useRef, useState } from "react"; import { liveUrl, sample } from "@/components/base"; import { EMOJI, FALLBACK_EMOJI } from "@/components/config"; import { t } from "@/components/i18n"; -import type { Link } from "@/components/types"; +import { EMPTY_POLL, isThumbs, shares, total } from "@/components/poll"; +import type { Link, PollSpec } from "@/components/types"; import type { DeckMessage, StageState, ToDeck } from "../../backstage/protocol"; type Reaction = { id: number; kind: string; x: number; delay: number }; @@ -13,7 +14,7 @@ type Pointer = { x: number; y: number; mode: "laser" | "spot"; off: boolean; tap const PER_BURST = 8; type Props = { - index: number; title: string; links: Link[]; + index: number; title: string; links: Link[]; poll?: PollSpec; step: number; steps: number; black: boolean; notes: boolean; full: boolean; startedAt: number | null; scale: number; onPublicUrl?: (url: string) => void; }; @@ -30,10 +31,10 @@ function rootVars(): Record { return vars; } -export default function Live({ index, title, links, step, steps, black, notes, full, startedAt, scale, onPublicUrl }: Props) { +export default function Live({ index, title, links, poll, step, steps, black, notes, full, startedAt, scale, onPublicUrl }: Props) { const ws = useRef(null); const [online, setOnline] = useState(false); - const [state, setState] = useState({ slide: { index: 0, title: "" }, links: [], poll: { id: 0, open: false, up: 0, down: 0 }, share: { on: false, v: 0 }, connected: 0, bot: false, publicUrl: "" }); + const [state, setState] = useState({ slide: { index: 0, title: "" }, links: [], poll: EMPTY_POLL, share: { on: false, v: 0 }, connected: 0, bot: false, publicUrl: "" }); const [reactions, setReactions] = useState([]); const [pointer, setPointer] = useState(null); const seq = useRef(0); @@ -91,8 +92,8 @@ export default function Live({ index, title, links, step, steps, black, notes, f useEffect(() => { if (publicUrl) onPublicUrl?.(publicUrl); }, [publicUrl, onPublicUrl]); useEffect(() => { - if (online) sendMsg({ type: "slide", index, title, links }); - }, [online, index, title, links]); + if (online) sendMsg({ type: "slide", index, title, links, poll }); + }, [online, index, title, links, poll]); useEffect(() => { if (online) sendMsg({ type: "view", index, step: Math.min(step, steps), steps, black, notes, full, elapsed: startedAt ? Date.now() - startedAt : null }); @@ -143,8 +144,11 @@ export default function Live({ index, title, links, step, steps, black, notes, f }, [state.bot, state.poll.open]); if (!online) return null; - const votes = state.poll.up + state.poll.down; - const upPct = votes ? Math.round((state.poll.up / votes) * 100) : 50; + const p = state.poll; + const votes = total(p); + const pct = shares(p); + const thumbs = isThumbs(p); + const [up = 0, down = 0] = p.counts; return ( <> @@ -165,15 +169,28 @@ export default function Live({ index, title, links, step, steps, black, notes, f ))} - {state.poll.open && ( -
+ {p.open && thumbs && ( +
👍 - {state.poll.up} -
- {state.poll.down} + {up} +
+ {down} 👎
)} + {p.open && !thumbs && ( +
`${o}: ${p.counts[i] ?? 0}`).join(", ")}`}> + {p.question &&

{p.question}

} + {p.options.map((o, i) => ( +
+ {o} +
+ {p.counts[i] ?? 0} +
+ ))} + {votes} {votes === 1 ? t.deck.vote : t.deck.votes} +
+ )} ); } diff --git a/deck/components/Remote.tsx b/deck/components/Remote.tsx index 2b5a70a..6467f48 100644 --- a/deck/components/Remote.tsx +++ b/deck/components/Remote.tsx @@ -5,6 +5,7 @@ import { slides } from "@/components/content"; import { liveUrl } from "@/components/base"; import { t } from "@/components/i18n"; import { PreviewContext } from "@/components/preview"; +import { EMPTY_POLL, isThumbs, shares, total as pollTotal } from "@/components/poll"; import type { RemoteKey, RemoteMessage, StageState, ToRemote, ViewMessage } from "../../backstage/protocol"; import roteiroJson from "@/components/roteiro.json"; @@ -26,7 +27,7 @@ export default function Remote() { const [online, setOnline] = useState(false); const [view, setView] = useState(null); const viewAt = useRef(0); - const [room, setRoom] = useState({ slide: { index: 0, title: "" }, links: [], poll: { id: 0, open: false, up: 0, down: 0 }, share: { on: false, v: 0 }, connected: 0, bot: false, publicUrl: "" }); + const [room, setRoom] = useState({ slide: { index: 0, title: "" }, links: [], poll: EMPTY_POLL, share: { on: false, v: 0 }, connected: 0, bot: false, publicUrl: "" }); const [now, setNow] = useState(0); const cheers = useRef<{ t: number; n: number }[]>([]); const [heat, setHeat] = useState(0); @@ -230,11 +231,23 @@ export default function Remote() { {finger && }
- {room.poll.open && ( -
- 👍 {room.poll.up} -
- {room.poll.down} 👎 + {room.poll.open && isThumbs(room.poll) && ( +
+ 👍 {room.poll.counts[0] ?? 0} +
+ {room.poll.counts[1] ?? 0} 👎 +
+ )} + {room.poll.open && !isThumbs(room.poll) && ( +
+ {room.poll.question &&

{room.poll.question}

} + {room.poll.options.map((o, i) => ( +
+ {o} +
+ {room.poll.counts[i] ?? 0} +
+ ))}
)} diff --git a/deck/components/i18n.ts b/deck/components/i18n.ts index 0b76178..8bf9ab7 100644 --- a/deck/components/i18n.ts +++ b/deck/components/i18n.ts @@ -13,6 +13,8 @@ const ptBR = { poweredBy: "feito com Talk in Loop", yes: "sim", no: "não", + vote: "voto", + votes: "votos", }, remote: { title: "Passador", @@ -73,6 +75,8 @@ const en: Messages = { poweredBy: "powered by Talk in Loop", yes: "yes", no: "no", + vote: "vote", + votes: "votes", }, remote: { title: "Remote", diff --git a/deck/components/poll.ts b/deck/components/poll.ts new file mode 100644 index 0000000..7a58976 --- /dev/null +++ b/deck/components/poll.ts @@ -0,0 +1,11 @@ +import type { Poll } from "../../backstage/protocol"; + +// Sem pergunta e com 👍/👎: a barra única de sempre. Com pergunta ou outras opções: uma barra por opção. +export const isThumbs = (p: Poll) => !p.question && p.options.length === 2 && p.options[0] === "👍" && p.options[1] === "👎"; + +export const total = (p: Poll) => p.counts.reduce((a, n) => a + n, 0); + +// percentual de cada opção, arredondado; 0 em todas enquanto não há voto +export const shares = (p: Poll) => { const n = total(p); return p.counts.map((c) => (n ? Math.round((c / n) * 100) : 0)); }; + +export const EMPTY_POLL: Poll = { id: 0, open: false, question: "", options: ["👍", "👎"], counts: [0, 0] }; diff --git a/deck/components/types.ts b/deck/components/types.ts index c66fe46..2517296 100644 --- a/deck/components/types.ts +++ b/deck/components/types.ts @@ -1,7 +1,7 @@ import type { CSSProperties, ReactNode } from "react"; -export type { Link } from "../../backstage/protocol"; -import type { Link } from "../../backstage/protocol"; +export type { Link, PollSpec } from "../../backstage/protocol"; +import type { Link, PollSpec } from "../../backstage/protocol"; export type SlideBase = { title: string; @@ -10,6 +10,7 @@ export type SlideBase = { top?: boolean; kind?: "title" | "statement" | "final"; links?: Link[]; + poll?: PollSpec; // pergunta e opções da votação deste slide; sem ela, 👍/👎 content: ReactNode; notes: ReactNode; }; diff --git a/deck/talks/starter/slides/index.tsx b/deck/talks/starter/slides/index.tsx index 4773bdd..4e366e1 100644 --- a/deck/talks/starter/slides/index.tsx +++ b/deck/talks/starter/slides/index.tsx @@ -144,17 +144,18 @@ export const slides: SlideBase[] = [ { label: "Um link citado neste slide", url: "https://example.com/artigo" }, { label: "Outro, que fica disponível no celular", url: "https://example.com/video" }, ], + poll: { question: "Qual recurso você mais usaria?", options: ["Reações", "Links no celular", "Votação", "Passador"] }, content: ( <>

A plateia participa pelo celular

  1. Reage, e as reações sobem no telão
  2. Recebe os links deste slide
  3. -
  4. Vota 👍 ou 👎 quando você pergunta
  5. +
  6. Vota quando você abre a votação
), - notes:

Tecla P abre e fecha a votação, em qualquer slide. A pergunta é falada, não escrita. Tecla L liga o robô, que reage se a sala ficar em silêncio.

, + notes:

Tecla P abre e fecha a votação. Neste slide ela usa a pergunta e as opções de poll; nos outros é 👍/👎 e a pergunta é falada. Tecla L liga o robô, que reage se a sala ficar em silêncio.

, }, { title: "Vídeo", block: "Ao vivo", minute: "8:00",
${esc(t.link)}${esc(t.clicksCol)}