diff --git a/AGENTS.md b/AGENTS.md index 99080ca..f52b853 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -66,6 +66,7 @@ src/ PollStateService State-JSON für Presenter und Teilnehmende ThrottleService Rate-Limit pro IP (Cache 'throttle') YouTubeService YouTube-Links/Timecodes parsen, Watch-/Embed-URLs, Prüfung per oEmbed (Http\Client) + QaService Q&A: Phasen wechseln, Fragen nach Upvotes ranken, Fokus beim Besprechen templates/ Deutsche UI, Layouts: default, present (Vollbild, dunkel), error, email webroot/css/plenario.css Eigenes CSS, kein Framework webroot/js/plenario.js Vanilla JS: Polling, Ergebnis-Rendering, Presenter-Steuerung, Folien-Sortierung (Pointer Events + Pfeiltasten) @@ -76,12 +77,14 @@ tests/ PHPUnit; PlenarioTestTrait erzeugt Testdaten, Fixtures - `polls`: `title`, `email`, `admin_token_hash` (sha256), `admin_token_encrypted` (Security::encrypt), `join_code` (6 Zeichen, ohne 0/O/1/I/L), `current_slide_id`, `is_active`, `show_results_to_participants` -- `slides`: `type` (`choice|wordcloud|open|scale|content|quiz|youtube`), `question`, `description`, `position`, +- `slides`: `type` (`choice|wordcloud|open|scale|content|quiz|youtube|qa`), `question`, `description`, `position`, `settings` (JSON, je Typ siehe `Slide::DEFAULT_SETTINGS`), `is_voting_open`, - `voting_started_at` / `voting_ends_at` (nur Quiz: Start und Deadline, `null` = manuell beenden) + `voting_started_at` / `voting_ends_at` (nur Quiz: Start und Deadline, `null` = manuell beenden), + `stage` / `focus_response_id` (nur Q&A: Phase und gerade besprochene Frage) - `slide_options`: Antwortoptionen für `choice` und `quiz`; `is_correct` markiert richtige Quiz-Antworten -- `responses`: `participant_hash`, `slide_option_id` | `text_value` | `numeric_value`. +- `responses`: `participant_hash`, `slide_option_id` | `text_value` | `numeric_value` | `parent_id`. Mehrfachauswahl/mehrere Wörter = mehrere Zeilen mit gleichem `participant_hash`. + Q&A: Frage = Zeile mit `text_value`, Upvote = Zeile mit `parent_id` (= id der Frage, FK mit CASCADE). ### Zentrale Regeln (nicht versehentlich brechen) @@ -113,6 +116,18 @@ tests/ PHPUnit; PlenarioTestTrait erzeugt Testdaten, Fixtures - Ausgaben in Templates immer mit `h()` escapen. JS baut DOM mit `textContent`, nie `innerHTML` mit Nutzerdaten. - Routen nur benannt verwenden (`['_name' => 'admin', 'token' => $adminToken]`), keine Fallbacks einführen. +- Q&A-Folie (`qa`, „Fragen & Antworten“): Phasen `collect` → `vote` → `discuss` (`Slide::qaStage()`, `QaService`), + der Presenter schaltet manuell weiter (V bzw. Stepper, auch zurück). `collect`: Fragen einreichen (max. + `VoteService::MAX_QA_QUESTIONS` pro Person, gleiche Frage nur einmal pro Folie), Teilnehmende sehen alle bisherigen Fragen + (gegen Dubletten, eigene markiert), aber noch keine Upvotes. + `vote`: Upvotes auf fremde Fragen, Budget = Setting `max_upvotes` pro Person, frei verteilbar (auch mehrere auf eine Frage, + je Upvote eine Zeile), `vote=remove` nimmt eine Stimme der Frage zurück; im State `qa.upvoted` = {Frage-id: eigene Stimmen}; + Teilnehmende sehen alle Fragen in Eingangsreihenfolge **ohne** Zählung. `discuss`: Abstimmung zu, Fragen nach Upvotes + sortiert (Gleichstand: älteste zuerst), `focus_response_id` = aktuelle Frage. In `discuss` blättern next/prev + (→/←, Klicker) zuerst durch die Fragen, erst danach durch die Folien. Fokuswechsel per `updateAll` ohne `modified`, + damit Teilnehmerseiten nicht neu laden. Teilnehmende bekommen nie `results`, sondern `qa` aus `PollStateService::qaState()`. + Zurücksetzen startet wieder bei `collect`. + - YouTube-Folie (`youtube`): nicht interaktiv (wie `content`). Settings `url` (wie eingegeben), `video_id`, `start` (Sekunden), `autoplay`. Startzeit-Feld leer = Timecode aus dem Link (`t`/`start`), sonst gewinnt das Feld (`1:30`, `2` = Minuten). Beim Speichern prüft `SlidesController::prepareYouTube()` per oEmbed: nicht gefunden/nicht einbettbar = Fehler, @@ -129,7 +144,7 @@ tests/ PHPUnit; PlenarioTestTrait erzeugt Testdaten, Fixtures 4. Aggregation in `ResultsService::forSlide()` + Docblock der JSON-Struktur 5. Formularfelder in `templates/Slides/form.php`, Eingabe in `templates/Participate/view.php` 6. Renderer in `webroot/js/plenario.js` (`Results.`), Styles in `plenario.css`, Badge-Farbe -7. Tests in `tests/TestCase/Service/VoteServiceTest.php` (Quiz: `QuizTest.php`) +7. Tests in `tests/TestCase/Service/VoteServiceTest.php` (Quiz: `QuizTest.php`, Q&A: `QaTest.php`) 8. Nach neuen Spalten lokal `bin/cake cache clear_all`, sonst nutzt das ORM das alte Schema aus dem Cache ### Live-Updates @@ -174,5 +189,5 @@ leiten `.htaccess` + `index.php` im Projektroot alles nach `webroot/` weiter. - Doppelte Stimmen sind möglich, wenn Teilnehmende Cookies löschen (bewusst: keine Accounts, kein IP-Tracking). - Polling skaliert für typische Meetings; für sehr große Events wären Server-Sent Events/WebSockets sinnvoll. -- Mögliche Erweiterungen: Q&A mit Upvotes, Quiz-Punkte/Bestenliste über mehrere Fragen, Bilder auf Folien, +- Mögliche Erweiterungen: Q&A-Moderation (Fragen ausblenden), Quiz-Punkte/Bestenliste über mehrere Fragen, Bilder auf Folien, Umfrage duplizieren, mehrsprachige UI (Übersetzungen unter `resources/locales`). diff --git a/config/Migrations/20261107140000_AddQaToSlides.php b/config/Migrations/20261107140000_AddQaToSlides.php new file mode 100644 index 0000000..d83e753 --- /dev/null +++ b/config/Migrations/20261107140000_AddQaToSlides.php @@ -0,0 +1,32 @@ +table('slides') + ->addColumn('stage', 'string', ['limit' => 20, 'null' => true, 'default' => null, 'after' => 'voting_ends_at']) + ->addColumn('focus_response_id', 'integer', ['null' => true, 'default' => null, 'after' => 'stage']) + ->update(); + + $this->table('responses') + ->addColumn('parent_id', 'integer', ['null' => true, 'default' => null, 'after' => 'numeric_value']) + ->addIndex(['parent_id']) + ->addForeignKey('parent_id', 'responses', 'id', ['delete' => 'CASCADE', 'update' => 'NO_ACTION']) + ->update(); + } +} diff --git a/src/Controller/AdminController.php b/src/Controller/AdminController.php index 3c650fb..0467b5b 100644 --- a/src/Controller/AdminController.php +++ b/src/Controller/AdminController.php @@ -8,6 +8,7 @@ use App\Model\Entity\Slide; use App\Model\Table\ResponsesTable; use App\Model\Table\SlidesTable; use App\Service\PollStateService; +use App\Service\QaService; use App\Service\VoteService; use Cake\Core\Configure; use Cake\Http\Exception\BadRequestException; @@ -158,7 +159,11 @@ class AdminController extends AdminAppController /** * Presenter controls. Field `action`: - * goto (+ slide_id), next, prev, open, close, toggle, stop + * goto (+ slide_id), next, prev, open, close, toggle, stop, + * Q&A: stage (+ stage: collect|vote|discuss), question (+ step: 1|-1) + * + * On a Q&A slide that is being discussed, next/prev step through the questions + * first (like builds in presentation software), toggle switches to the next stage. * * Answers with the new state as JSON for XHR requests, otherwise redirects back. * @@ -171,8 +176,36 @@ class AdminController extends AdminAppController $slides = $this->Slides->listForPoll($this->poll->id); $ids = array_map(fn(Slide $s) => $s->id, $slides); $index = array_search($this->poll->current_slide_id, $ids, true); + $current = $index === false ? null : $slides[$index]; + $qa = new QaService(); + if ($current !== null && $current->isQa()) { + if ($action === 'toggle') { + // No-op while discussing (last stage). + $qa->advance($current); + $action = 'none'; + } elseif (in_array($action, ['next', 'prev'], true) && $qa->moveFocus($current, $action === 'next' ? 1 : -1)) { + $action = 'none'; + } + } switch ($action) { + case 'none': + break; + case 'stage': + case 'question': + if ($current === null || !$current->isQa()) { + throw new BadRequestException('Not a Q&A slide'); + } + if ($action === 'question') { + $qa->moveFocus($current, (int)$this->request->getData('step') < 0 ? -1 : 1); + break; + } + $stage = (string)$this->request->getData('stage'); + if (!in_array($stage, Slide::QA_STAGES, true)) { + throw new BadRequestException('Unknown stage'); + } + $qa->setStage($current, $stage); + break; case 'goto': $target = (int)$this->request->getData('slide_id'); if (!in_array($target, $ids, true)) { @@ -267,8 +300,11 @@ class AdminController extends AdminAppController ->where(['slide_id' => $slide->id]) ->orderBy(['id' => 'ASC']) ->all(); + $texts = []; foreach ($responses as $response) { + $texts[$response->id] = (string)$response->text_value; $answer = match (true) { + $response->parent_id !== null => __('Upvote: {0}', $texts[$response->parent_id] ?? ''), $response->slide_option_id !== null => $labels[$response->slide_option_id] ?? '', $response->text_value !== null && $response->numeric_value === VoteService::DOWNVOTE => __('Downvote: {0}', $response->text_value), diff --git a/src/Controller/ParticipateController.php b/src/Controller/ParticipateController.php index 1ef7095..e6ed9d5 100644 --- a/src/Controller/ParticipateController.php +++ b/src/Controller/ParticipateController.php @@ -124,7 +124,12 @@ class ParticipateController extends AppController } (new VoteService())->submit($poll, $slide, $this->participantHash($poll), (array)$this->request->getData()); $ok = true; - $message = __('Danke für deine Antwort!'); + $message = match (true) { + !$slide->isQa() => __('Danke für deine Antwort!'), + $this->request->getData('vote') === 'up' => __('Deine Stimme ist angekommen.'), + $this->request->getData('vote') === 'remove' => __('Deine Stimme wurde zurückgenommen.'), + default => __('Danke, deine Frage ist angekommen!'), + }; } catch (VoteException $e) { $ok = false; $message = $e->getMessage(); diff --git a/src/Controller/SlidesController.php b/src/Controller/SlidesController.php index f8cb81e..6d6139a 100644 --- a/src/Controller/SlidesController.php +++ b/src/Controller/SlidesController.php @@ -5,6 +5,7 @@ namespace App\Controller; use App\Model\Entity\Slide; use App\Model\Table\SlidesTable; +use App\Service\QaService; use App\Service\YouTubeService; use Cake\Http\Exception\NotFoundException; use Cake\Http\Response; @@ -43,6 +44,8 @@ class SlidesController extends AdminAppController $slide->poll_id = $this->poll->id; // A quiz is started by the presenter (that also starts its timer). $slide->is_voting_open = $type !== Slide::TYPE_QUIZ; + // Q&A starts by collecting questions. + $slide->stage = $type === Slide::TYPE_QA ? Slide::QA_COLLECT : null; $optionsText = $type === Slide::TYPE_CHOICE ? "\n" : ''; $quizOptions = []; @@ -147,6 +150,9 @@ class SlidesController extends AdminAppController $slide->voting_ends_at = null; $this->Slides->saveOrFail($slide); } + if ($slide->isQa()) { + (new QaService())->reset($slide); + } $this->Flash->success(__('Antworten der Folie „{0}“ wurden gelöscht.', $slide->question)); return $this->redirect($this->adminUrl()); @@ -205,8 +211,8 @@ class SlidesController extends AdminAppController // The type of an existing slide cannot change (would invalidate responses). $data['type'] = $slide->type; $fields = ['type', 'question', 'description', 'settings', 'is_voting_open']; - if ($slide->isQuiz()) { - // Quiz voting is controlled by the presenter only. + if ($slide->isQuiz() || $slide->isQa()) { + // Quiz and Q&A voting is controlled by the presenter only. $fields = array_values(array_diff($fields, ['is_voting_open'])); } $youtube = $slide->isYouTube() ? $this->prepareYouTube($data) : ['errors' => [], 'warning' => null]; diff --git a/src/Model/Entity/Response.php b/src/Model/Entity/Response.php index 78cf5a6..9e56603 100644 --- a/src/Model/Entity/Response.php +++ b/src/Model/Entity/Response.php @@ -8,6 +8,7 @@ use Cake\ORM\Entity; /** * One answer row of a participant. A multi-select vote or a word cloud entry * with several words results in several rows with the same participant_hash. + * Q&A: a question is a row with text_value, an upvote a row with parent_id = question id. * * @property int $id * @property int $slide_id @@ -15,6 +16,7 @@ use Cake\ORM\Entity; * @property int|null $slide_option_id * @property string|null $text_value * @property int|null $numeric_value + * @property int|null $parent_id Q&A upvote: id of the supported question * @property \Cake\I18n\DateTime $created */ class Response extends Entity @@ -30,6 +32,7 @@ class Response extends Entity 'slide_option_id' => true, 'text_value' => true, 'numeric_value' => true, + 'parent_id' => true, ]; /** diff --git a/src/Model/Entity/Slide.php b/src/Model/Entity/Slide.php index 186f2cf..6a2c1cb 100644 --- a/src/Model/Entity/Slide.php +++ b/src/Model/Entity/Slide.php @@ -21,6 +21,8 @@ use Cake\ORM\Entity; * @property bool $is_voting_open * @property \Cake\I18n\DateTime|null $voting_started_at Quiz: start of the voting window * @property \Cake\I18n\DateTime|null $voting_ends_at Quiz: deadline (null = closed manually) + * @property string|null $stage Q&A: collect|vote|discuss (null = collect), see qaStage() + * @property int|null $focus_response_id Q&A: question currently being discussed * @property \Cake\I18n\DateTime $created * @property \Cake\I18n\DateTime $modified * @property \App\Model\Entity\Poll $poll @@ -36,6 +38,7 @@ class Slide extends Entity public const TYPE_CONTENT = 'content'; public const TYPE_QUIZ = 'quiz'; public const TYPE_YOUTUBE = 'youtube'; + public const TYPE_QA = 'qa'; /** * Quiz phases, see quizPhase(). @@ -51,6 +54,24 @@ class Slide extends Entity */ public const QUIZ_TIME_LIMITS = [0, 10, 15, 20, 30, 45, 60, 90, 120, 180, 300]; + /** + * Q&A stages, see qaStage(): participants submit questions, then upvote + * them, then the presenter discusses them one by one (most upvoted first). + */ + public const QA_COLLECT = 'collect'; + public const QA_VOTE = 'vote'; + public const QA_DISCUSS = 'discuss'; + + /** + * @var list + */ + public const QA_STAGES = [self::QA_COLLECT, self::QA_VOTE, self::QA_DISCUSS]; + + /** + * Highest selectable number of upvotes per participant on a Q&A slide. + */ + public const QA_MAX_UPVOTES = 10; + /** * Default settings per type. Unknown keys are dropped on save. * @@ -67,6 +88,8 @@ class Slide extends Entity self::TYPE_QUIZ => ['time_limit' => 30], // url as entered, video_id parsed from it, start in seconds self::TYPE_YOUTUBE => ['url' => '', 'video_id' => '', 'start' => 0, 'autoplay' => false], + // upvotes per participant in the voting stage (1..QA_MAX_UPVOTES) + self::TYPE_QA => ['max_upvotes' => 3], ]; /** @@ -91,6 +114,7 @@ class Slide extends Entity self::TYPE_OPEN => __('Offene Frage'), self::TYPE_SCALE => __('Skala'), self::TYPE_QUIZ => __('Quiz'), + self::TYPE_QA => __('Fragen & Antworten'), self::TYPE_CONTENT => __('Inhaltsfolie'), self::TYPE_YOUTUBE => __('YouTube-Video'), ]; @@ -107,6 +131,7 @@ class Slide extends Entity self::TYPE_OPEN => __('Freitext-Antworten, live als Liste.'), self::TYPE_SCALE => __('Bewertung auf einer Skala, z. B. 1 bis 5.'), self::TYPE_QUIZ => __('Frage mit richtiger Antwort und Zeitlimit, aufgelöst wird erst am Ende.'), + self::TYPE_QA => __('Teilnehmende reichen Fragen ein und wählen per Upvote, welche zuerst beantwortet werden.'), self::TYPE_CONTENT => __('Nur Text anzeigen, ohne Abstimmung.'), self::TYPE_YOUTUBE => __('Video in der Präsentation abspielen, Teilnehmende bekommen den Link zum Teilen.'), ]; @@ -199,6 +224,35 @@ class Slide extends Entity return $this->type === self::TYPE_QUIZ; } + /** + * @return bool + */ + public function isQa(): bool + { + return $this->type === self::TYPE_QA; + } + + /** + * Stage of a Q&A slide (one of the QA_* constants), see QaService. + * + * @return string + */ + public function qaStage(): string + { + return in_array($this->stage, self::QA_STAGES, true) ? (string)$this->stage : self::QA_COLLECT; + } + + /** + * Whether a participant may answer the slide several times (word cloud: one + * row per word, Q&A: questions and upvotes). + * + * @return bool + */ + public function allowsMultipleResponses(): bool + { + return in_array($this->type, [self::TYPE_WORDCLOUD, self::TYPE_QA], true); + } + /** * Phase of a quiz: ready (not started yet), running, finished (time up or * closed by the presenter). Results and correct answers are only revealed diff --git a/src/Model/Table/ResponsesTable.php b/src/Model/Table/ResponsesTable.php index 820aa2f..65e54b5 100644 --- a/src/Model/Table/ResponsesTable.php +++ b/src/Model/Table/ResponsesTable.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace App\Model\Table; use App\Service\VoteService; +use Cake\ORM\Query\SelectQuery; use Cake\ORM\Table; /** @@ -32,6 +33,67 @@ class ResponsesTable extends Table $this->belongsTo('SlideOptions', ['foreignKey' => 'slide_option_id']); } + /** + * Q&A questions of a slide (rows with text, without parent). + * + * @param int $slideId Slide id + * @return \Cake\ORM\Query\SelectQuery + */ + public function questionsOf(int $slideId): SelectQuery + { + return $this->find()->where([ + 'Responses.slide_id' => $slideId, + 'Responses.parent_id IS' => null, + 'Responses.text_value IS NOT' => null, + ]); + } + + /** + * Q&A progress of one participant on a slide. + * + * @param int $slideId Slide id + * @param string $participantHash Participant hash + * @return array{questions: list, upvotes: list} ids of own questions / question id of each own upvote (repeated per upvote) + */ + public function qaVotesOf(int $slideId, string $participantHash): array + { + $rows = $this->find() + ->select(['id', 'parent_id']) + ->where(['slide_id' => $slideId, 'participant_hash' => $participantHash]) + ->orderBy(['id' => 'ASC']) + ->disableHydration() + ->all(); + + $result = ['questions' => [], 'upvotes' => []]; + foreach ($rows as $row) { + if ($row['parent_id'] === null) { + $result['questions'][] = (int)$row['id']; + } else { + $result['upvotes'][] = (int)$row['parent_id']; + } + } + + return $result; + } + + /** + * Upvotes per Q&A question of a slide. + * + * @param int $slideId Slide id + * @return array question id => upvotes + */ + public function upvotesPerQuestion(int $slideId): array + { + return $this->find() + ->select(['parent_id', 'n' => $this->find()->func()->count('*')]) + ->where(['slide_id' => $slideId, 'parent_id IS NOT' => null]) + ->groupBy(['parent_id']) + ->disableHydration() + ->all() + ->combine(fn($row) => (int)$row['parent_id'], fn($row) => (int)$row['n']) + ->toArray(); + } + /** * @param int $slideId Slide id * @param string $participantHash Participant hash diff --git a/src/Model/Table/SlidesTable.php b/src/Model/Table/SlidesTable.php index d3fc22c..5acad51 100644 --- a/src/Model/Table/SlidesTable.php +++ b/src/Model/Table/SlidesTable.php @@ -159,6 +159,10 @@ class SlidesTable extends Table $settings['time_limit'] = $limit; } break; + case Slide::TYPE_QA: + $max = (int)($input['max_upvotes'] ?? $settings['max_upvotes']); + $settings['max_upvotes'] = max(1, min(Slide::QA_MAX_UPVOTES, $max)); + break; case Slide::TYPE_YOUTUBE: $url = mb_substr(trim((string)($input['url'] ?? '')), 0, 500); $parsed = YouTubeService::parseUrl($url); diff --git a/src/Service/PollStateService.php b/src/Service/PollStateService.php index f4bc2c9..d3a8f3b 100644 --- a/src/Service/PollStateService.php +++ b/src/Service/PollStateService.php @@ -22,6 +22,8 @@ use Cake\ORM\Locator\LocatorAwareTrait; * once the quiz is finished – then always, independent of * `show_results_to_participants`. Timed quizzes are closed lazily here * when their deadline has passed. + * + * Q&A slides have their own participant view (`qa`, see qaState()), never `results`. */ class PollStateService { @@ -111,13 +113,17 @@ class PollStateService $slide = $poll->is_active ? $this->currentSlide($poll) : null; $words = $slide?->type === Slide::TYPE_WORDCLOUD ? $this->wordState($slide, $participantHash) : null; $quiz = $slide?->isQuiz() ? $this->quizState($slide, $participantHash) : null; - $hasResponded = $words !== null - ? $words['mine'] !== [] || $words['down'] !== [] - : $slide && $slide->isInteractive() && $this->Responses->hasResponded($slide->id, $participantHash); + $qa = $slide?->isQa() ? $this->qaState($slide, $participantHash) : null; + $hasResponded = match (true) { + $words !== null => $words['mine'] !== [] || $words['down'] !== [], + $qa !== null => $qa['mine'] !== [] || $qa['upvoted'] !== [], + default => $slide && $slide->isInteractive() && $this->Responses->hasResponded($slide->id, $participantHash), + }; $isVotingOpen = $slide?->isVotingOpen() ?? false; $showResults = $slide !== null && $slide->isInteractive() + && $qa === null && ($quiz !== null ? $quiz['phase'] === Slide::QUIZ_FINISHED : ($poll->show_results_to_participants && ($hasResponded || !$isVotingOpen)) @@ -133,14 +139,15 @@ class PollStateService (int)$poll->is_active, $slide?->id ?? 0, (int)$isVotingOpen, - // Word clouds are answered word by word without reload. - $words !== null ? 0 : (int)$hasResponded, + // Word clouds and Q&A are answered item by item without reload. + $words !== null || $qa !== null ? 0 : (int)$hasResponded, $slide?->modified?->toUnixString() ?? 0, ]), 'slide' => $showResults ? $this->slidePayload($slide) : null, 'results' => $showResults ? $this->results->forSlide($slide) : null, 'words' => $words, 'quiz' => $quiz, + 'qa' => $qa, ]; } @@ -181,6 +188,45 @@ class PollStateService ]; } + /** + * Q&A view of one participant: + * - collect: all questions so far in submission order (helps to avoid duplicates), `mine` marks own ones + * - vote: all questions in submission order, without counts (no bandwagon effect) + * - discuss: all questions ranked with upvotes, `focusId` = question being discussed + * `upvoted` = own upvotes per question id (several per question are allowed). + * + * @param \App\Model\Entity\Slide $slide Q&A slide + * @param string $participantHash Participant hash + * @return array{stage: string, maxUpvotes: int, votesLeft: int, mine: list, upvoted: array, + * questions: list, focusId: int|null} + */ + public function qaState(Slide $slide, string $participantHash): array + { + $stage = $slide->qaStage(); + $own = $this->Responses->qaVotesOf($slide->id, $participantHash); + $max = (int)$slide->setting('max_upvotes'); + $questions = (new QaService())->rankedQuestions($slide); + if ($stage === Slide::QA_DISCUSS) { + $focusId = in_array($slide->focus_response_id, array_column($questions, 'id'), true) + ? $slide->focus_response_id + : null; + } else { + $focusId = null; + usort($questions, fn($a, $b) => $a['id'] <=> $b['id']); + $questions = array_map(fn($q) => ['id' => $q['id'], 'text' => $q['text']], $questions); + } + + return [ + 'stage' => $stage, + 'maxUpvotes' => $max, + 'votesLeft' => max(0, $max - count($own['upvotes'])), + 'mine' => $own['questions'], + 'upvoted' => array_count_values($own['upvotes']), + 'questions' => array_values($questions), + 'focusId' => $focusId, + ]; + } + /** * Word cloud progress of one participant. * diff --git a/src/Service/QaService.php b/src/Service/QaService.php new file mode 100644 index 0000000..8a2bd85 --- /dev/null +++ b/src/Service/QaService.php @@ -0,0 +1,154 @@ +fetchTable('Slides'); + $this->Slides = $slides; + /** @var \App\Model\Table\ResponsesTable $responses */ + $responses = $this->fetchTable('Responses'); + $this->Responses = $responses; + } + + /** + * Questions of a slide, most upvoted first (ties: oldest first). + * + * @param \App\Model\Entity\Slide $slide Q&A slide + * @return list + */ + public function rankedQuestions(Slide $slide): array + { + $votes = $this->Responses->upvotesPerQuestion($slide->id); + $questions = []; + $rows = $this->Responses->questionsOf($slide->id) + ->select(['id', 'text_value']) + ->orderBy(['id' => 'ASC']) + ->disableHydration() + ->all(); + foreach ($rows as $row) { + $id = (int)$row['id']; + $questions[] = ['id' => $id, 'text' => (string)$row['text_value'], 'votes' => $votes[$id] ?? 0]; + } + usort($questions, fn($a, $b) => [$b['votes'], $a['id']] <=> [$a['votes'], $b['id']]); + + return $questions; + } + + /** + * Switches the stage. Collecting and voting open the slide for input, + * discussing closes it and puts the top question on screen. Setting the + * current stage again changes nothing. + * + * @param \App\Model\Entity\Slide $slide Q&A slide + * @param string $stage One of Slide::QA_STAGES + * @return \App\Model\Entity\Slide + */ + public function setStage(Slide $slide, string $stage): Slide + { + if (!$slide->isQa() || !in_array($stage, Slide::QA_STAGES, true)) { + throw new InvalidArgumentException('Unknown Q&A stage ' . $stage); + } + if ($slide->qaStage() === $stage && $slide->stage !== null) { + return $slide; + } + $slide->stage = $stage; + $slide->is_voting_open = $stage !== Slide::QA_DISCUSS; + $slide->focus_response_id = $stage === Slide::QA_DISCUSS + ? ($this->rankedQuestions($slide)[0]['id'] ?? null) + : null; + $this->Slides->saveOrFail($slide); + + return $slide; + } + + /** + * Moves to the following stage (collect → vote → discuss). + * + * @param \App\Model\Entity\Slide $slide Q&A slide + * @return bool False when already discussing + */ + public function advance(Slide $slide): bool + { + $index = (int)array_search($slide->qaStage(), Slide::QA_STAGES, true); + if (!isset(Slide::QA_STAGES[$index + 1])) { + return false; + } + $this->setStage($slide, Slide::QA_STAGES[$index + 1]); + + return true; + } + + /** + * Steps to the next/previous question while discussing. + * + * Saved without touching `modified`, so participant pages update live + * instead of reloading (see PollStateService version). + * + * @param \App\Model\Entity\Slide $slide Q&A slide + * @param int $step +1 next, -1 previous + * @return bool False when there is no such question (or not discussing) + */ + public function moveFocus(Slide $slide, int $step): bool + { + if (!$slide->isQa() || $slide->qaStage() !== Slide::QA_DISCUSS) { + return false; + } + $ids = array_column($this->rankedQuestions($slide), 'id'); + $index = array_search($slide->focus_response_id, $ids, true); + $target = $index === false ? 0 : $index + $step; + if (!isset($ids[$target]) || $ids[$target] === $slide->focus_response_id) { + return false; + } + $this->Slides->updateAll(['focus_response_id' => $ids[$target]], ['id' => $slide->id]); + $slide->focus_response_id = $ids[$target]; + $slide->setDirty('focus_response_id', false); + + return true; + } + + /** + * Back to the start after all responses were deleted. + * + * @param \App\Model\Entity\Slide $slide Q&A slide + * @return void + */ + public function reset(Slide $slide): void + { + $slide->stage = Slide::QA_COLLECT; + $slide->is_voting_open = true; + $slide->focus_response_id = null; + $this->Slides->saveOrFail($slide); + } +} diff --git a/src/Service/ResultsService.php b/src/Service/ResultsService.php index 100a018..7d118da 100644 --- a/src/Service/ResultsService.php +++ b/src/Service/ResultsService.php @@ -24,6 +24,10 @@ use Cake\ORM\Locator\LocatorAwareTrait; * once finished additionally per option 'count', 'percent', 'correct' (bool) * and 'correctCount' (participants with a correct answer). * Counts and correct answers are NEVER part of the result before the quiz is finished. + * - qa: 'stage' (collect|vote|discuss), 'maxUpvotes', 'upvotes' (total), + * 'questions' => [['id', 'text', 'votes']] most upvoted first (ties: oldest first), + * 'focusId' (question being discussed|null), 'focusIndex' (0-based position in questions|null). + * Presenter only – participants get their own view, see PollStateService::qaState(). */ class ResultsService { @@ -60,6 +64,7 @@ class ResultsService Slide::TYPE_OPEN => $this->open($slide), Slide::TYPE_SCALE => $this->scale($slide), Slide::TYPE_QUIZ => $this->quiz($slide), + Slide::TYPE_QA => $this->qa($slide), default => [], }; } @@ -134,6 +139,30 @@ class ResultsService return $result; } + /** + * @param \App\Model\Entity\Slide $slide Slide + * @return array + */ + protected function qa(Slide $slide): array + { + $questions = (new QaService())->rankedQuestions($slide); + $focusIndex = null; + foreach ($questions as $index => $question) { + if ($question['id'] === $slide->focus_response_id) { + $focusIndex = $index; + } + } + + return [ + 'stage' => $slide->qaStage(), + 'maxUpvotes' => (int)$slide->setting('max_upvotes'), + 'upvotes' => array_sum(array_column($questions, 'votes')), + 'questions' => $questions, + 'focusId' => $focusIndex === null ? null : $slide->focus_response_id, + 'focusIndex' => $focusIndex, + ]; + } + /** * @param \App\Model\Entity\Slide $slide Slide * @return array diff --git a/src/Service/VoteService.php b/src/Service/VoteService.php index 48ba226..deec40e 100644 --- a/src/Service/VoteService.php +++ b/src/Service/VoteService.php @@ -23,6 +23,11 @@ use Cake\Utility\Security; * word of someone else. Each participant rates a word only once (up or down). * - quiz: exactly one option, only while the quiz runs (Slide::isVotingOpen() * includes the deadline of a timed quiz). + * - Q&A (see QaService for the stages): `question` (text) only while collecting, + * at most MAX_QA_QUESTIONS per participant, the same question (case-insensitive) + * only once per slide. `vote=up|remove` + `question_id` only while voting: upvote + * questions of others, at most `max_upvotes` in total, freely distributed (several + * on one question are allowed); `remove` withdraws one own upvote of the question. */ class VoteService { @@ -30,6 +35,7 @@ class VoteService public const MAX_WORD_LENGTH = 40; public const MAX_TEXT_LENGTH = 500; + public const MAX_QA_QUESTIONS = 10; /** * `responses.numeric_value` of a word cloud downvote (upvotes/words: null). @@ -84,10 +90,11 @@ class VoteService throw new VoteException(match (true) { $slide->isQuiz() && $slide->voting_started_at === null => __('Das Quiz hat noch nicht begonnen.'), $slide->isQuiz() => __('Die Zeit für dieses Quiz ist abgelaufen.'), + $slide->isQa() => __('Die Fragerunde läuft – Fragen und Stimmen sind nicht mehr möglich.'), default => __('Die Abstimmung zu dieser Frage ist geschlossen.'), }); } - if ($slide->type !== Slide::TYPE_WORDCLOUD && $this->Responses->hasResponded($slide->id, $participantHash)) { + if (!$slide->allowsMultipleResponses() && $this->Responses->hasResponded($slide->id, $participantHash)) { throw new VoteException(__('Du hast bereits abgestimmt.')); } @@ -97,6 +104,7 @@ class VoteService Slide::TYPE_OPEN => $this->openRows($data), Slide::TYPE_SCALE => $this->scaleRows($slide, $data), Slide::TYPE_QUIZ => $this->quizRows($slide, $data), + Slide::TYPE_QA => $this->qaRows($slide, $participantHash, $data), default => throw new VoteException(__('Unbekannter Folientyp.')), }; @@ -107,7 +115,9 @@ class VoteService 'participant_hash' => $participantHash, ]); } - $this->Responses->saveManyOrFail($entities); + if ($entities !== []) { + $this->Responses->saveManyOrFail($entities); + } } /** @@ -149,6 +159,86 @@ class VoteService return [['slide_option_id' => $id]]; } + /** + * Q&A: a new question while collecting, an upvote (or its withdrawal) while voting. + * Withdrawing deletes one upvote row and returns no new rows. + * + * @param \App\Model\Entity\Slide $slide Slide + * @param string $participantHash Participant hash + * @param array $data Request data + * @return list> + */ + protected function qaRows(Slide $slide, string $participantHash, array $data): array + { + $stage = $slide->qaStage(); + $vote = $data['vote'] ?? null; + $own = $this->Responses->qaVotesOf($slide->id, $participantHash); + + if ($vote === null) { + if ($stage !== Slide::QA_COLLECT) { + throw new VoteException(__('Es können keine neuen Fragen mehr eingereicht werden.')); + } + $text = trim((string)preg_replace('/\s+/u', ' ', (string)($data['question'] ?? ''))); + if ($text === '') { + throw new VoteException(__('Bitte gib eine Frage ein.')); + } + if (mb_strlen($text) > self::MAX_TEXT_LENGTH) { + throw new VoteException(__('Die Frage darf maximal {0} Zeichen lang sein.', self::MAX_TEXT_LENGTH)); + } + $key = mb_strtolower($text); + foreach ($this->Responses->questionsOf($slide->id)->select(['text_value'])->disableHydration() as $row) { + if (mb_strtolower((string)$row['text_value']) === $key) { + throw new VoteException(__('Diese Frage wurde schon gestellt. Du kannst sie gleich beim Abstimmen unterstützen.')); + } + } + if (count($own['questions']) >= self::MAX_QA_QUESTIONS) { + throw new VoteException(__('Du kannst höchstens {0} Fragen stellen.', self::MAX_QA_QUESTIONS)); + } + + return [['text_value' => $text]]; + } + + if ($stage !== Slide::QA_VOTE) { + throw new VoteException(__('Die Abstimmung über die Fragen hat noch nicht begonnen.')); + } + $id = is_scalar($data['question_id'] ?? null) ? filter_var($data['question_id'], FILTER_VALIDATE_INT) : false; + if ($id === false || !$this->Responses->questionsOf($slide->id)->where(['Responses.id' => $id])->count()) { + throw new VoteException(__('Diese Frage gibt es nicht.')); + } + + if ($vote === 'remove') { + // Withdraws one of possibly several own upvotes on the question. + $upvote = $this->Responses->find() + ->where(['slide_id' => $slide->id, 'participant_hash' => $participantHash, 'parent_id' => $id]) + ->orderBy(['id' => 'DESC']) + ->first(); + if ($upvote === null) { + throw new VoteException(__('Du hast diese Frage nicht unterstützt.')); + } + $this->Responses->deleteOrFail($upvote); + + return []; + } + if ($vote !== 'up') { + throw new VoteException(__('Ungültige Stimme.')); + } + if (in_array($id, $own['questions'], true)) { + throw new VoteException(__('Deine eigene Frage kannst du nicht unterstützen.')); + } + // Several upvotes on the same question are allowed (push important questions). + $max = (int)$slide->setting('max_upvotes'); + if (count($own['upvotes']) >= $max) { + throw new VoteException(__n( + 'Du hast deine Stimme schon vergeben. Nimm sie zurück, um eine andere Frage zu unterstützen.', + 'Du hast alle {0} Stimmen vergeben. Nimm eine zurück, um eine andere Frage zu unterstützen.', + $max, + $max, + )); + } + + return [['parent_id' => $id]]; + } + /** * Normalized key of a word cloud term: whitespace collapsed, trimmed, cut to * MAX_WORD_LENGTH. Use wordKey() for case-insensitive comparison. diff --git a/templates/Admin/index.php b/templates/Admin/index.php index 8e823e2..9bdbce0 100644 --- a/templates/Admin/index.php +++ b/templates/Admin/index.php @@ -79,6 +79,12 @@ $url = fn(string $name, array $params = []) => ['_name' => $name, 'token' => $ad 'running' => __('Quiz läuft'), 'finished' => __('Quiz beendet'), ][$slide->quizPhase()]) ?> + isQa()) : ?> + · __('Fragen sammeln'), + 'vote' => __('Abstimmung läuft'), + 'discuss' => __('Fragen werden besprochen'), + ][$slide->qaStage()]) ?> · setting('max_upvotes'), (int)$slide->setting('max_upvotes')) ?> is_voting_open) : ?>· diff --git a/templates/Admin/present.php b/templates/Admin/present.php index adbb330..7c03ffd 100644 --- a/templates/Admin/present.php +++ b/templates/Admin/present.php @@ -4,6 +4,7 @@ * (Plenario.presenter) from /admin/{token}/state. * * Keyboard: ←/→ slides, V voting on/off, H hide results, F fullscreen, Q QR code. + * Q&A slides: V switches to the next stage; while discussing ←/→ step through the questions first. * * @var \App\View\AppView $this * @var \App\Model\Entity\Poll $poll diff --git a/templates/Participate/view.php b/templates/Participate/view.php index d7235d2..5e31cac 100644 --- a/templates/Participate/view.php +++ b/templates/Participate/view.php @@ -14,6 +14,7 @@ $this->assign('bodyClass', 'participant'); $voteUrl = ['_name' => 'participate:vote', 'code' => $poll->join_code]; $words = $state['words'] ?? null; $quiz = $state['quiz'] ?? null; +$qa = $state['qa'] ?? null; $countdown = function (?int $remaining): string { if ($remaining === null) { return ''; @@ -117,6 +118,32 @@ $countdown = function (?int $remaining): string {

+ +
+ + Form->create(null, ['url' => $voteUrl, 'class' => 'vote-form qa-form', 'data-qa-form' => true]) ?> + Form->hidden('slide_id', ['value' => $slide->id]) ?> + + +

+ Form->button(__('Frage einreichen'), ['class' => 'button button--primary button--block']) ?> + Form->end() ?> + + Form->hidden('slide_id', ['value' => $slide->id]) ?> +

+ + +

+
+
is_voting_open) : ?> Form->create(null, ['url' => $voteUrl, 'class' => 'vote-form word-form', 'data-word-form' => true]) ?> Form->hidden('slide_id', ['value' => $slide->id]) ?> diff --git a/templates/Slides/form.php b/templates/Slides/form.php index 7411f81..5702741 100644 --- a/templates/Slides/form.php +++ b/templates/Slides/form.php @@ -93,12 +93,17 @@ $optionsError = $slide->getError('options_text'); 'label' => match ($slide->type) { 'content' => __('Überschrift'), 'youtube' => __('Titel'), + 'qa' => __('Überschrift'), default => __('Frage'), }, 'maxlength' => 500, 'required' => !$slide->isYouTube(), 'autofocus' => $isNew && !$slide->isYouTube(), - 'placeholder' => $slide->isYouTube() ? __('Leer lassen, um den Titel des Videos zu übernehmen') : null, + 'placeholder' => match (true) { + $slide->isYouTube() => __('Leer lassen, um den Titel des Videos zu übernehmen'), + $slide->isQa() => __('z. B. Eure Fragen an den Vorstand'), + default => null, + }, 'data-youtube-title' => $slide->isYouTube() ? '' : null, ]) ?> Form->control('description', [ @@ -205,9 +210,24 @@ $optionsError = $slide->getError('options_text'); 'value' => $settings['time_limit'], ]) ?>

+ type === 'qa') : + $upvoteOptions = []; + foreach (range(1, \App\Model\Entity\Slide::QA_MAX_UPVOTES) as $n) { + $upvoteOptions[$n] = __n('{0} Stimme', '{0} Stimmen', $n, $n); + } + ?> + Form->control('settings.max_upvotes', [ + 'type' => 'select', + 'options' => $upvoteOptions, + 'label' => __('Upvotes (Stimmen) pro Person'), + 'value' => $settings['max_upvotes'], + 'aria-describedby' => 'qa-upvotes-hint', + ]) ?> +

+

- isInteractive() && !$slide->isQuiz()) : ?> + isInteractive() && !$slide->isQuiz() && !$slide->isQa()) : ?> Form->control('is_voting_open', [ 'type' => 'checkbox', 'label' => __('Abstimmung geöffnet'), diff --git a/tests/TestCase/Controller/QaSlideTest.php b/tests/TestCase/Controller/QaSlideTest.php new file mode 100644 index 0000000..5fcd6b6 --- /dev/null +++ b/tests/TestCase/Controller/QaSlideTest.php @@ -0,0 +1,166 @@ + + */ + protected array $fixtures = ['app.Polls', 'app.Slides', 'app.SlideOptions', 'app.Responses']; + + protected const PID = '0123456789abcdef0123456789abcdef'; + + protected function setUp(): void + { + parent::setUp(); + $this->enableCsrfToken(); + } + + /** + * @return array + */ + protected function control(string $token, array $data): array + { + $this->configRequest(['headers' => ['Accept' => 'application/json']]); + $this->post("/admin/$token/control", $data); + $this->assertResponseOk(); + + return json_decode((string)$this->_response->getBody(), true); + } + + /** + * @return array + */ + protected function participantPost(string $code, array $data): array + { + $this->cookie('plenario_pid', self::PID); + $this->configRequest(['headers' => ['Accept' => 'application/json', 'X-Requested-With' => 'XMLHttpRequest']]); + $this->post("/p/$code/vote", $data); + $this->assertResponseOk(); + + return json_decode((string)$this->_response->getBody(), true); + } + + public function testAddQaSlide(): void + { + [$poll, $token] = $this->createPoll(); + $this->get("/admin/$token/slides/add?type=qa"); + $this->assertResponseOk(); + $this->assertResponseContains('Upvotes (Stimmen) pro Person'); + $this->assertResponseNotContains('Abstimmung geöffnet'); + + $this->post("/admin/$token/slides/add?type=qa", [ + 'type' => 'qa', + 'question' => 'Eure Fragen an den Vorstand', + 'settings' => ['max_upvotes' => '5'], + ]); + $this->assertRedirect(); + $slide = $this->slidesTable()->find()->where(['poll_id' => $poll->id])->firstOrFail(); + $this->assertSame([Slide::TYPE_QA, 5, Slide::QA_COLLECT, true], [ + $slide->type, $slide->setting('max_upvotes'), $slide->stage, $slide->is_voting_open, + ]); + + $this->get("/admin/$token"); + $this->assertResponseContains('Fragen sammeln'); + $this->assertResponseContains('max. 5 Upvotes pro Person'); + } + + public function testFullRoundTrip(): void + { + [$poll, $token] = $this->createPoll(); + $slide = $this->createSlide($poll, Slide::TYPE_QA, ['settings' => ['max_upvotes' => 1]]); + $next = $this->createSlide($poll, Slide::TYPE_CONTENT); + $this->goLive($poll, $slide); + $code = $poll->join_code; + + $this->cookie('plenario_pid', self::PID); + $this->get("/p/$code"); + $this->assertResponseContains('Frage einreichen'); + + $answer = $this->participantPost($code, ['slide_id' => $slide->id, 'question' => 'Meine Frage']); + $this->assertTrue($answer['ok']); + $this->assertSame('Danke, deine Frage ist angekommen!', $answer['message']); + $this->assertSame(['Meine Frage'], array_column($answer['state']['qa']['questions'], 'text')); + + // Others ask too (directly via the service). + $hash = VoteService::participantHash('ffffffffffffffffffffffffffffffff', $poll->id); + (new VoteService())->submit($this->pollsTable()->get($poll->id), $this->slidesTable()->get($slide->id), $hash, ['question' => 'Andere Frage']); + + // V: collect → vote + $state = $this->control($token, ['action' => 'toggle']); + $this->assertSame('vote', $state['results']['stage']); + $this->assertTrue($state['slide']['isVotingOpen']); + + $this->cookie('plenario_pid', self::PID); + $this->get("/p/$code"); + $this->assertResponseContains('Du hast eine Stimme'); + + $other = $state['results']['questions'][1]['id']; + $answer = $this->participantPost($code, ['slide_id' => $slide->id, 'vote' => 'up', 'question_id' => $other]); + $this->assertTrue($answer['ok'], $answer['message']); + $this->assertSame(0, $answer['state']['qa']['votesLeft']); + + // Presenter clicks "Besprechen" in the stepper. + $state = $this->control($token, ['action' => 'stage', 'stage' => 'discuss']); + $this->assertSame(['discuss', 0], [$state['results']['stage'], $state['results']['focusIndex']]); + $this->assertSame('Andere Frage', $state['results']['questions'][0]['text']); + $this->assertStringNotContainsString('participant_hash', (string)json_encode($state)); + $this->cookie('plenario_pid', self::PID); + $this->get("/p/$code"); + $this->assertResponseContains('Die Fragen werden jetzt besprochen'); + $this->get("/admin/$token/present"); + $this->assertResponseOk(); + + // → steps through the questions first, then to the next slide. + $state = $this->control($token, ['action' => 'next']); + $this->assertSame([$slide->id, 1], [$state['slide']['id'], $state['results']['focusIndex']]); + $state = $this->control($token, ['action' => 'question', 'step' => '-1']); + $this->assertSame(0, $state['results']['focusIndex']); + $this->control($token, ['action' => 'next']); + $state = $this->control($token, ['action' => 'next']); + $this->assertSame($next->id, $state['slide']['id']); + + $this->get("/admin/$token/export.csv"); + $this->assertResponseOk(); + $this->assertResponseContains('Upvote: Andere Frage'); + $this->assertResponseContains('Meine Frage'); + } + + public function testResetStartsOver(): void + { + [$poll, $token] = $this->createPoll(); + $slide = $this->createSlide($poll, Slide::TYPE_QA); + $this->goLive($poll, $slide); + (new VoteService())->submit($this->pollsTable()->get($poll->id), $slide, 'p1', ['question' => 'Frage']); + $this->control($token, ['action' => 'stage', 'stage' => 'discuss']); + + $this->post("/admin/$token/slides/{$slide->id}/reset"); + $this->assertRedirect(); + $slide = $this->slidesTable()->get($slide->id); + $this->assertSame([Slide::QA_COLLECT, true, null], [$slide->stage, $slide->is_voting_open, $slide->focus_response_id]); + $this->assertSame(0, $this->fetchTable('Responses')->find()->where(['slide_id' => $slide->id])->count()); + } + + public function testStageActionRequiresQaSlide(): void + { + [$poll, $token] = $this->createPoll(); + $this->goLive($poll, $this->createSlide($poll, Slide::TYPE_CHOICE)); + $this->configRequest(['headers' => ['Accept' => 'application/json']]); + $this->post("/admin/$token/control", ['action' => 'stage', 'stage' => 'vote']); + $this->assertResponseCode(400); + } +} diff --git a/tests/TestCase/Service/QaTest.php b/tests/TestCase/Service/QaTest.php new file mode 100644 index 0000000..d08270e --- /dev/null +++ b/tests/TestCase/Service/QaTest.php @@ -0,0 +1,205 @@ + + */ + protected array $fixtures = ['app.Polls', 'app.Slides', 'app.SlideOptions', 'app.Responses']; + + /** + * @return array{0: \App\Model\Entity\Poll, 1: \App\Model\Entity\Slide} + */ + protected function createQa(int $maxUpvotes = 2): array + { + [$poll] = $this->createPoll(); + $slide = $this->createSlide($poll, Slide::TYPE_QA, ['settings' => ['max_upvotes' => $maxUpvotes]]); + + return [$this->goLive($poll, $slide), $slide]; + } + + protected function ask(Poll $poll, Slide $slide, string $participant, string $question): int + { + (new VoteService())->submit($poll, $slide, $participant, ['question' => $question]); + + return (int)$this->fetchTable('Responses')->find() + ->where(['slide_id' => $slide->id, 'participant_hash' => $participant]) + ->orderBy(['id' => 'DESC']) + ->firstOrFail() + ->get('id'); + } + + protected function vote(Poll $poll, Slide $slide, string $participant, int $questionId, string $vote = 'up'): void + { + (new VoteService())->submit($poll, $slide, $participant, ['vote' => $vote, 'question_id' => $questionId]); + } + + protected function stage(Slide $slide, string $stage): Slide + { + (new QaService())->setStage($slide, $stage); + + return $this->slidesTable()->get($slide->id, contain: ['SlideOptions']); + } + + protected function assertVoteFails(string $message, callable $fn): void + { + try { + $fn(); + $this->fail('VoteException expected'); + } catch (VoteException $e) { + $this->assertSame($message, $e->getMessage()); + } + } + + public function testSanitizesMaxUpvotes(): void + { + [, $slide] = $this->createQa(); + $this->assertSame(2, $slide->setting('max_upvotes')); + $this->assertSame(Slide::QA_COLLECT, $slide->qaStage()); + + $table = $this->slidesTable(); + $this->assertSame(1, $table->patchEntity($slide, ['type' => 'qa', 'settings' => ['max_upvotes' => '0']])->setting('max_upvotes')); + $this->assertSame(10, $table->patchEntity($slide, ['type' => 'qa', 'settings' => ['max_upvotes' => '99']])->setting('max_upvotes')); + } + + public function testCollectQuestionsSeveralPerParticipantWithoutDuplicates(): void + { + [$poll, $slide] = $this->createQa(); + $this->ask($poll, $slide, 'p1', 'Wann kommt das neue Fahrzeug?'); + $this->ask($poll, $slide, 'p1', 'Wer organisiert das Sommerfest?'); + + $this->assertVoteFails('Diese Frage wurde schon gestellt. Du kannst sie gleich beim Abstimmen unterstützen.', fn() => $this->ask($poll, $slide, 'p2', 'wann kommt das neue fahrzeug?')); + $this->assertVoteFails('Bitte gib eine Frage ein.', fn() => $this->ask($poll, $slide, 'p2', ' ')); + $this->assertVoteFails('Die Abstimmung über die Fragen hat noch nicht begonnen.', fn() => $this->vote($poll, $slide, 'p2', 1)); + + $results = (new ResultsService())->forSlide($slide); + $this->assertSame('collect', $results['stage']); + $this->assertSame(['Wann kommt das neue Fahrzeug?', 'Wer organisiert das Sommerfest?'], array_column($results['questions'], 'text')); + + // Participants see all questions while collecting (to avoid duplicates), even before asking. + $state = (new PollStateService())->forParticipant($poll, 'p2'); + $this->assertSame(['Wann kommt das neue Fahrzeug?', 'Wer organisiert das Sommerfest?'], array_column($state['qa']['questions'], 'text')); + $this->assertSame([], $state['qa']['mine']); + $this->assertArrayNotHasKey('votes', $state['qa']['questions'][0]); + $this->assertNull($state['results']); + $this->assertCount(2, (new PollStateService())->forParticipant($poll, 'p1')['qa']['questions']); + } + + public function testQuestionLimitPerParticipant(): void + { + [$poll, $slide] = $this->createQa(); + for ($i = 1; $i <= VoteService::MAX_QA_QUESTIONS; $i++) { + $this->ask($poll, $slide, 'p1', 'Frage ' . $i); + } + $this->assertVoteFails('Du kannst höchstens 10 Fragen stellen.', fn() => $this->ask($poll, $slide, 'p1', 'Noch eine')); + } + + public function testUpvotesAreABudgetThatCanBeStackedAndWithdrawn(): void + { + [$poll, $slide] = $this->createQa(3); + $a = $this->ask($poll, $slide, 'p1', 'Frage A'); + $b = $this->ask($poll, $slide, 'p2', 'Frage B'); + $c = $this->ask($poll, $slide, 'p2', 'Frage C'); + $slide = $this->stage($slide, Slide::QA_VOTE); + $this->assertTrue($slide->isVotingOpen()); + + $this->assertVoteFails('Es können keine neuen Fragen mehr eingereicht werden.', fn() => $this->ask($poll, $slide, 'p3', 'Zu spät')); + $this->assertVoteFails('Deine eigene Frage kannst du nicht unterstützen.', fn() => $this->vote($poll, $slide, 'p1', $a)); + $this->assertVoteFails('Diese Frage gibt es nicht.', fn() => $this->vote($poll, $slide, 'p1', 999999)); + + $this->vote($poll, $slide, 'p1', $b); + // Several upvotes on one question push it. + $this->vote($poll, $slide, 'p3', $c); + $this->vote($poll, $slide, 'p3', $b); + $this->vote($poll, $slide, 'p3', $b); + $this->assertVoteFails('Du hast alle 3 Stimmen vergeben. Nimm eine zurück, um eine andere Frage zu unterstützen.', fn() => $this->vote($poll, $slide, 'p3', $a)); + + // Withdraw one vote at a time and use it elsewhere. + $this->vote($poll, $slide, 'p3', $c, 'remove'); + $this->assertVoteFails('Du hast diese Frage nicht unterstützt.', fn() => $this->vote($poll, $slide, 'p3', $c, 'remove')); + $this->vote($poll, $slide, 'p3', $a); + + $results = (new ResultsService())->forSlide($slide); + $this->assertSame([[$b, 3], [$a, 1], [$c, 0]], array_map(fn($q) => [$q['id'], $q['votes']], $results['questions'])); + $this->assertSame(4, $results['upvotes']); + + $this->vote($poll, $slide, 'p3', $b, 'remove'); + $this->assertSame(2, (new ResultsService())->forSlide($slide)['questions'][0]['votes'], 'remove withdraws only one upvote'); + $this->vote($poll, $slide, 'p3', $b); + + // Voting view of participants: all questions, submission order, no counts. + $state = (new PollStateService())->forParticipant($poll, 'p3'); + $this->assertSame([$a, $b, $c], array_column($state['qa']['questions'], 'id')); + $this->assertArrayNotHasKey('votes', $state['qa']['questions'][0]); + $this->assertSame([$b => 2, $a => 1], $state['qa']['upvoted']); + $this->assertSame(0, $state['qa']['votesLeft']); + $this->assertTrue($state['hasResponded']); + } + + public function testDiscussStepsThroughQuestionsByRank(): void + { + [$poll, $slide] = $this->createQa(3); + $a = $this->ask($poll, $slide, 'p1', 'Frage A'); + $b = $this->ask($poll, $slide, 'p1', 'Frage B'); + $slide = $this->stage($slide, Slide::QA_VOTE); + $this->vote($poll, $slide, 'p2', $b); + + $slide = $this->stage($slide, Slide::QA_DISCUSS); + $this->assertFalse($slide->isVotingOpen()); + $this->assertSame($b, $slide->focus_response_id, 'most upvoted question first'); + $this->assertVoteFails('Die Fragerunde läuft – Fragen und Stimmen sind nicht mehr möglich.', fn() => $this->vote($poll, $slide, 'p2', $a)); + + $qa = new QaService(); + $this->assertFalse($qa->moveFocus($slide, -1)); + $modified = $slide->modified; + $this->assertTrue($qa->moveFocus($slide, 1)); + $this->assertFalse($qa->moveFocus($slide, 1), 'no question after the last one'); + $slide = $this->slidesTable()->get($slide->id, contain: ['SlideOptions']); + $this->assertSame($a, $slide->focus_response_id); + $this->assertEquals($modified, $slide->modified, 'focus changes do not reload participant pages'); + + $results = (new ResultsService())->forSlide($slide); + $this->assertSame([$a, 1], [$results['focusId'], $results['focusIndex']]); + $state = (new PollStateService())->forParticipant($poll, 'p2'); + $this->assertSame($a, $state['qa']['focusId']); + $this->assertSame([1, 0], array_column($state['qa']['questions'], 'votes')); + + // Idempotent: setting the same stage again keeps the focus. + $slide = $this->stage($slide, Slide::QA_DISCUSS); + $this->assertSame($a, $slide->focus_response_id); + } + + public function testAdvanceAndReset(): void + { + [$poll, $slide] = $this->createQa(); + $this->ask($poll, $slide, 'p1', 'Frage A'); + $qa = new QaService(); + $this->assertTrue($qa->advance($slide)); + $this->assertTrue($qa->advance($slide)); + $this->assertFalse($qa->advance($slide)); + $this->assertSame(Slide::QA_DISCUSS, $slide->qaStage()); + + $this->fetchTable('Responses')->deleteAll(['slide_id' => $slide->id]); + $qa->reset($slide); + $slide = $this->slidesTable()->get($slide->id); + $this->assertSame([Slide::QA_COLLECT, true, null], [$slide->qaStage(), $slide->is_voting_open, $slide->focus_response_id]); + } +} diff --git a/webroot/css/plenario.css b/webroot/css/plenario.css index 51daabd..c994186 100644 --- a/webroot/css/plenario.css +++ b/webroot/css/plenario.css @@ -27,6 +27,7 @@ --c3: #f29a1f; --c4: #2f8fe0; --c5: #8e44c9; + --qa: #1f6bb0; /* Q&A accent, AA contrast with white text */ } @media (prefers-color-scheme: dark) { @@ -39,6 +40,7 @@ --border: #30334a; --primary: #7f75ff; --primary-soft: #2a2752; + --qa: #7cc4ff; --shadow: none; } } @@ -146,6 +148,7 @@ h3 { font-size: 1.05rem; margin-top: 1.6em; } .badge--type-content { background: #e3eefb; color: #1f6bb0; } .badge--type-quiz { background: #f1e3fb; color: #7a2fb0; } .badge--type-youtube { background: #fde4e1; color: #b3261e; } +.badge--type-qa { background: #dff1fb; color: #0b5f8a; } .message { padding: 12px 16px; border-radius: 8px; margin-bottom: 20px; cursor: pointer; background: var(--surface-2); border-left: 4px solid var(--muted); } .message.success { border-color: var(--ok); } @@ -227,6 +230,7 @@ textarea { resize: vertical; } .type-card--content { border-top-color: var(--c4); } .type-card--quiz { border-top-color: var(--c5); } .type-card--youtube { border-top-color: #d93025; } +.type-card--qa { border-top-color: #0b8bc9; } /* ---------------------------------------------------------------- slide form: youtube */ .youtube-status { margin: 6px 0 0; font-size: .9rem; color: var(--muted); } @@ -382,6 +386,46 @@ textarea { resize: vertical; } .answers { list-style: none; padding: 0; margin: 0; columns: 280px; column-gap: 12px; } .answer { break-inside: avoid; background: var(--surface-2); border-radius: 10px; padding: 10px 14px; margin-bottom: 12px; word-break: break-word; } +/* Q&A (participants + presenter) */ +.qa-form__label { display: block; font-weight: 600; margin-bottom: 6px; } +.qa-message { min-height: 1.4em; margin: 8px 0; font-size: .9rem; color: var(--ok); } +.qa-message.is-error { color: var(--danger); } +.qa-heading { font-size: 1rem; margin: 16px 0 8px; } +.qa-list { list-style: none; padding: 0; margin: 0; display: grid; gap: 10px; } +.qa-item { position: relative; display: flex; align-items: center; gap: 12px; padding: 12px 14px; border-radius: 10px; background: var(--surface-2); overflow: hidden; } +.qa-item__text { flex: 1; min-width: 0; word-break: break-word; position: relative; } +.qa-item__bar { position: absolute; left: 0; bottom: 0; height: 4px; background: var(--qa); border-radius: 0 4px 4px 0; transition: width .6s ease; } +.qa-item.is-mine { border-left: 4px solid var(--qa); } +.qa-item.is-upvoted { box-shadow: inset 0 0 0 2px var(--qa); } +.qa-item.is-done { opacity: .55; } +.qa-item.is-current { box-shadow: inset 0 0 0 2px var(--c1); } +.qa-votes { font-weight: 700; font-variant-numeric: tabular-nums; white-space: nowrap; color: var(--qa); position: relative; } +.qa-own { font-size: .85rem; color: var(--muted); white-space: nowrap; } +.qa-stepper { flex: none; display: inline-flex; align-items: center; gap: 6px; } +.qa-stepper__count { min-width: 3.2em; text-align: center; font-weight: 700; font-variant-numeric: tabular-nums; color: var(--muted); } +.qa-stepper.is-active .qa-stepper__count { color: var(--qa); } +.qa-upvote { width: 44px; height: 44px; padding: 0; border-radius: 50%; border: 2px solid var(--qa); background: var(--surface); color: var(--qa); font: inherit; font-size: 1.3rem; font-weight: 700; line-height: 1; cursor: pointer; } +.qa-upvote--up { background: var(--qa); color: var(--surface); } +.qa-upvote:disabled { opacity: .45; cursor: not-allowed; } +.qa-upvote:focus-visible { outline: 3px solid var(--primary); outline-offset: 2px; } +.qa-budget { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; margin: 0 0 12px; } +.qa-budget strong { font-size: 1.4rem; color: var(--qa); } +.qa-budget__dot { width: 12px; height: 12px; border-radius: 50%; background: var(--qa); } +.qa-budget__dot.is-used { background: transparent; box-shadow: inset 0 0 0 2px var(--border); } +.qa-budget__dot:first-of-type { margin-left: 6px; } +.qa-focus { padding: 16px 18px; margin: 0 0 16px; border-radius: 14px; background: var(--surface-2); border-left: 6px solid var(--c1); } +.qa-focus__meta { display: flex; gap: 16px; justify-content: space-between; margin: 0 0 6px; font-size: .85rem; font-weight: 700; text-transform: uppercase; letter-spacing: .08em; color: var(--muted); } +.qa-focus__text { margin: 0; font-size: 1.3rem; font-weight: 700; word-break: break-word; } +.qa-focus__nav { display: flex; gap: 8px; justify-content: flex-end; margin-top: 12px; } +.qa-focus__nav:empty { display: none; } +.qa-list--compact .qa-item { padding: 8px 12px; } +.qa-summary { color: var(--muted); margin: 0 0 1em; } +.qa-steps { list-style: none; padding: 0; margin: 0 0 1em; display: flex; flex-wrap: wrap; gap: 6px; counter-reset: none; } +.qa-steps__step { display: inline-block; padding: 4px 12px; border-radius: 99px; border: 1px solid var(--border); background: transparent; color: var(--muted); font: inherit; font-size: .85em; } +button.qa-steps__step { cursor: pointer; } +button.qa-steps__step:hover:not(:disabled) { color: var(--text); border-color: var(--text); } +.qa-steps .is-current .qa-steps__step { background: var(--qa); border-color: var(--qa); color: var(--surface); font-weight: 700; cursor: default; } + /* ---------------------------------------------------------------- presenter */ body.present { --bg: #0f1020; @@ -422,6 +466,16 @@ body.present { /* brighter green for contrast on the dark stage */ .stage .quiz-summary strong, .stage .bar--correct .bar__label { color: #3ddc97; } .stage .bar--correct .bar__fill { background: #3ddc97; } +.stage .qa-steps { font-size: .7em; } +.stage .qa-steps__step { border-color: rgba(255, 255, 255, .25); } +.stage .qa-item { background: rgba(255, 255, 255, .06); } +.stage { --qa: #7cc4ff; } +.stage .qa-steps .is-current .qa-steps__step { color: var(--bg); } +.stage .qa-focus { background: rgba(255, 255, 255, .08); padding: 3vh 3vw; } +.stage .qa-focus__meta { font-size: .7em; } +.stage .qa-focus__text { font-size: clamp(1.8rem, 3.6vw, 3.2rem); line-height: 1.2; } +.stage .qa-list--compact { font-size: .75em; } +.stage--qa .stage__question { font-size: clamp(1.5rem, 3vw, 2.6rem); } .stage__controls { display: flex; gap: 8px; align-items: center; justify-content: center; flex-wrap: wrap; opacity: .35; transition: opacity .2s; padding-top: 12px; } .stage__controls:hover, .stage__controls:focus-within { opacity: 1; } diff --git a/webroot/js/plenario.js b/webroot/js/plenario.js index 2342eb3..2dff7c4 100644 --- a/webroot/js/plenario.js +++ b/webroot/js/plenario.js @@ -300,7 +300,8 @@ return; } // A quiz shows its answer options even before anyone has answered. - if (results.participants === 0 && !(results.type === 'quiz' && !results.revealed)) { + // A Q&A slide always shows its stages. + if (results.participants === 0 && results.type !== 'qa' && !(results.type === 'quiz' && !results.revealed)) { container.appendChild(el('p', { class: 'results-empty', text: 'Noch keine Antworten' })); return; } @@ -498,6 +499,111 @@ return el('ul', { class: 'answers' }, results.answers.map(function (answer) { return el('li', { class: 'answer', text: answer.text }); })); + }, + + /** + * Presenter view of a Q&A slide: stage stepper, then per stage the + * collected questions, the live ranking or the question being discussed. + * options: {onStage: fn(stage)|null, onQuestion: fn(step)|null} + */ + qa: function (results, options) { + var onStage = options && options.onStage; + var onQuestion = options && options.onQuestion; + var questions = results.questions; + var maxVotes = Math.max.apply(null, questions.map(function (q) { return q.votes; }).concat([1])); + var children = [Qa.steps(results.stage, onStage)]; + + function votes(question) { + return el('span', { + class: 'qa-votes', + 'aria-label': question.votes + (question.votes === 1 ? ' Stimme' : ' Stimmen'), + text: '▲ ' + question.votes + }); + } + + if (results.stage === 'collect') { + children.push(el('p', { class: 'qa-summary', text: questions.length === 0 + ? 'Noch keine Fragen – jetzt mitmachen und Fragen einreichen!' + : questions.length + (questions.length === 1 ? ' Frage eingereicht' : ' Fragen eingereicht') })); + children.push(el('ul', { class: 'answers' }, questions.slice().reverse().map(function (question) { + return el('li', { class: 'answer', text: question.text }); + }))); + } else if (results.stage === 'vote') { + children.push(el('p', { class: 'qa-summary', text: 'Abstimmen: jede Person hat ' + + results.maxUpvotes + (results.maxUpvotes === 1 ? ' Stimme' : ' Stimmen') + + ' · bisher ' + results.upvotes + ' vergeben' })); + children.push(el('ol', { class: 'qa-list' }, questions.map(function (question) { + return el('li', { class: 'qa-item' }, [ + el('span', { class: 'qa-item__text', text: question.text }), + votes(question), + el('span', { class: 'qa-item__bar', style: 'width:' + (question.votes / maxVotes * 100) + '%' }) + ]); + }))); + } else if (questions.length === 0) { + children.push(el('p', { class: 'qa-summary', text: 'Es wurden keine Fragen eingereicht.' })); + } else { + var index = results.focusIndex === null ? 0 : results.focusIndex; + var focus = questions[index]; + var nav = function (step, label, symbol, disabled) { + if (!onQuestion) { + return null; + } + var button = el('button', { type: 'button', class: 'ctrl', title: label }, [ + el('span', { 'aria-hidden': 'true', text: symbol }), + el('span', { class: 'sr-only', text: label }) + ]); + button.disabled = disabled; + button.addEventListener('click', function () { onQuestion(step); }); + return button; + }; + children.push(el('div', { class: 'qa-focus', 'aria-live': 'polite' }, [ + el('p', { class: 'qa-focus__meta' }, [ + el('span', { text: 'Frage ' + (index + 1) + ' von ' + questions.length }), + votes(focus) + ]), + el('p', { class: 'qa-focus__text', text: focus.text }), + el('div', { class: 'qa-focus__nav' }, [ + nav(-1, 'Vorherige Frage', '←', index === 0), + nav(1, 'Nächste Frage', '→', index === questions.length - 1) + ]) + ])); + children.push(el('ol', { class: 'qa-list qa-list--compact' }, questions.map(function (question, i) { + var attrs = { class: 'qa-item' + (i < index ? ' is-done' : '') + (i === index ? ' is-current' : '') }; + if (i === index) { + attrs['aria-current'] = 'true'; + } + return el('li', attrs, [ + el('span', { class: 'qa-item__text', text: (i < index ? '✓ ' : '') + question.text }), + votes(question) + ]); + }))); + } + return el('div', { class: 'qa-results qa-results--' + results.stage }, children); + } + }; + + // ------------------------------------------------------------------ Q&A + + var Qa = { + labels: { collect: 'Fragen sammeln', vote: 'Abstimmen', discuss: 'Besprechen' }, + + /** Stepper of the three stages; clickable for the presenter (onStage). */ + steps: function (stage, onStage) { + return el('ol', { class: 'qa-steps', 'aria-label': 'Ablauf' }, ['collect', 'vote', 'discuss'].map(function (key, i) { + var current = key === stage; + var label = (i + 1) + ' ' + Qa.labels[key]; + var item = onStage + ? el('button', { type: 'button', class: 'qa-steps__step', text: label }) + : el('span', { class: 'qa-steps__step', text: label }); + if (current) { + item.setAttribute('aria-current', 'step'); + } + if (onStage) { + item.disabled = current; + item.addEventListener('click', function () { onStage(key); }); + } + return el('li', { class: current ? 'is-current' : '' }, [item]); + })); } }; @@ -704,29 +810,38 @@ } var quizPhase = slide.type === 'quiz' && state.results ? state.results.phase : null; + var qaStage = slide.type === 'qa' && state.results ? state.results.stage : null; q('[data-type]').textContent = quizPhase ? slide.typeLabel + ' · ' + { ready: 'bereit', running: 'läuft', finished: 'Auflösung' }[quizPhase] - : slide.typeLabel; + : (qaStage ? slide.typeLabel + ' · ' + Qa.labels[qaStage] : slide.typeLabel); q('[data-question]').textContent = slide.question; q('[data-description]').textContent = slide.description; root.classList.toggle('stage--content', !slide.isInteractive); root.classList.toggle('stage--video', slide.type === 'youtube'); renderMedia(slide); - root.classList.toggle('stage--closed', slide.isInteractive && !slide.isVotingOpen && !quizPhase); + root.classList.toggle('stage--closed', slide.isInteractive && !slide.isVotingOpen && !quizPhase && !qaStage); + root.classList.toggle('stage--qa', !!qaStage); var voting = q('[data-voting]'); - voting.hidden = !slide.isInteractive; + // Q&A: V switches to the next stage, there is none after "discuss". + voting.hidden = !slide.isInteractive || qaStage === 'discuss'; voting.querySelector('[data-label]').textContent = quizPhase ? { ready: 'Quiz starten', running: 'Quiz beenden', finished: 'Quiz erneut öffnen' }[quizPhase] - : (slide.isVotingOpen ? 'Abstimmung schließen' : 'Abstimmung öffnen'); + : (qaStage + ? { collect: 'Einreichen beenden', vote: 'Abstimmung beenden', discuss: '' }[qaStage] + : (slide.isVotingOpen ? 'Abstimmung schließen' : 'Abstimmung öffnen')); - q('[data-participants]').textContent = slide.isInteractive - ? state.results.participants + ' ' + (state.results.participants === 1 ? 'Antwort' : 'Antworten') - : ''; + var count = qaStage ? state.results.questions.length : (slide.isInteractive ? state.results.participants : 0); + q('[data-participants]').textContent = !slide.isInteractive ? '' : (qaStage + ? count + (count === 1 ? ' Frage' : ' Fragen') + : count + ' ' + (count === 1 ? 'Antwort' : 'Antworten')); var container = q('[data-results]'); container.classList.toggle('is-hidden', hideResults); - Results.render(container, slide.isInteractive ? state.results : null); + Results.render(container, slide.isInteractive ? state.results : null, { + onStage: function (stage) { control('stage', { stage: stage }); }, + onQuestion: function (step) { control('question', { step: step }); } + }); Countdown.start(); } @@ -833,8 +948,178 @@ && state.isVotingOpen); } + // --- Q&A: submit questions, upvote, follow the discussion ---------- + var qaRoot = root.querySelector('[data-qa]'); + var qaList = qaRoot ? qaRoot.querySelector('[data-qa-list]') : null; + var qaMessage = qaRoot ? qaRoot.querySelector('[data-qa-message]') : null; + var qaForm = qaRoot ? qaRoot.querySelector('[data-qa-form]') : null; + var qaRendered = ''; + var qaSending = false; + + function qaSay(text, isError) { + qaMessage.textContent = text; + qaMessage.classList.toggle('is-error', !!isError); + } + + function sendQa(data) { + if (qaSending) { + return Promise.resolve(null); + } + qaSending = true; + data.slide_id = root.querySelector('[name=slide_id]').value; + return postJson(voteUrl, data).then(function (response) { + qaSay(response.message, !response.ok); + if (response.state.version !== version) { + window.location.reload(); + return null; + } + renderQa(response.state); + return response; + }).catch(function () { + qaSay('Das hat nicht geklappt. Bitte versuche es noch einmal.', true); + return null; + }).then(function (response) { + qaSending = false; + return response; + }); + } + + function renderQa(state) { + var qa = state.qa; + if (!qaList || !qa) { + return; + } + var key = JSON.stringify(qa); + if (key === qaRendered) { + return; + } + qaRendered = key; + // Keep keyboard focus on the same question after re-rendering. + var focused = document.activeElement && document.activeElement.getAttribute('data-question-id'); + qaList.textContent = ''; + + if (qa.stage === 'collect') { + // All questions so far, so participants can spot duplicates before asking. + qaList.appendChild(el('h2', { class: 'qa-heading', text: 'Bereits gestellte Fragen (' + qa.questions.length + ')' })); + if (!qa.questions.length) { + qaList.appendChild(el('p', { class: 'results-empty', text: 'Noch keine – stell gern die erste Frage!' })); + return; + } + qaList.appendChild(el('ul', { class: 'qa-list' }, qa.questions.map(function (question) { + var mine = qa.mine.indexOf(question.id) >= 0; + return el('li', { class: 'qa-item' + (mine ? ' is-mine' : '') }, [ + el('span', { class: 'qa-item__text', text: question.text }), + mine ? el('span', { class: 'qa-own', text: 'deine Frage' }) : null + ]); + }))); + return; + } + + if (qa.stage === 'vote') { + var used = qa.maxUpvotes - qa.votesLeft; + qaList.appendChild(el('p', { class: 'qa-budget', 'aria-live': 'polite' }, [ + el('strong', { text: String(qa.votesLeft) }), + el('span', { text: ' von ' + qa.maxUpvotes + (qa.maxUpvotes === 1 ? ' Stimme' : ' Stimmen') + ' übrig' }) + ].concat(Array.apply(null, Array(qa.maxUpvotes)).map(function (_, i) { + return el('span', { class: 'qa-budget__dot' + (i < used ? ' is-used' : ''), 'aria-hidden': 'true' }); + })))); + if (!qa.questions.length) { + qaList.appendChild(el('p', { class: 'results-empty', text: 'Es wurden keine Fragen eingereicht.' })); + return; + } + qaList.appendChild(el('ul', { class: 'qa-list' }, qa.questions.map(function (question) { + var mine = qa.mine.indexOf(question.id) >= 0; + // Own upvotes on this question – several are allowed to push important questions. + var given = (qa.upvoted || {})[question.id] || 0; + var action; + if (mine) { + action = el('span', { class: 'qa-own', text: 'deine Frage' }); + } else { + var button = function (vote, symbol, label, disabled) { + var b = el('button', { + type: 'button', + class: 'qa-upvote qa-upvote--' + vote, + 'aria-label': label + ': ' + question.text, + 'data-question-id': question.id + '-' + vote + }, [el('span', { 'aria-hidden': 'true', text: symbol })]); + b.disabled = disabled; + b.addEventListener('click', function () { + sendQa({ vote: vote, question_id: question.id }); + }); + return b; + }; + action = el('span', { class: 'qa-stepper' + (given > 0 ? ' is-active' : '') }, [ + button('remove', '−', 'Stimme zurücknehmen', given === 0), + el('span', { + class: 'qa-stepper__count', + 'aria-label': given === 0 ? 'keine Stimme von dir' : given + (given === 1 ? ' Stimme' : ' Stimmen') + ' von dir', + text: '▲ ' + given + }), + button('up', '+', 'Stimme geben', qa.votesLeft === 0) + ]); + } + return el('li', { class: 'qa-item' + (mine ? ' is-mine' : '') + (given > 0 ? ' is-upvoted' : '') }, [ + el('span', { class: 'qa-item__text', text: question.text }), + action + ]); + }))); + } else { + if (!qa.questions.length) { + qaList.appendChild(el('p', { class: 'results-empty', text: 'Es wurden keine Fragen eingereicht.' })); + return; + } + var index = -1; + qa.questions.forEach(function (question, i) { + if (question.id === qa.focusId) { + index = i; + } + }); + if (index >= 0) { + qaList.appendChild(el('div', { class: 'qa-focus', 'aria-live': 'polite' }, [ + el('p', { class: 'qa-focus__meta', text: 'Wird gerade besprochen · Frage ' + (index + 1) + ' von ' + qa.questions.length }), + el('p', { class: 'qa-focus__text', text: qa.questions[index].text }) + ])); + } + qaList.appendChild(el('ol', { class: 'qa-list qa-list--compact' }, qa.questions.map(function (question, i) { + var mine = qa.mine.indexOf(question.id) >= 0; + var attrs = { class: 'qa-item' + (i < index ? ' is-done' : '') + (i === index ? ' is-current' : '') + (mine ? ' is-mine' : '') }; + if (i === index) { + attrs['aria-current'] = 'true'; + } + return el('li', attrs, [ + el('span', { class: 'qa-item__text', text: (i < index ? '✓ ' : '') + question.text + (mine ? ' (deine Frage)' : '') }), + el('span', { class: 'qa-votes', 'aria-label': question.votes + (question.votes === 1 ? ' Stimme' : ' Stimmen'), text: '▲ ' + question.votes }) + ]); + }))); + } + + if (focused) { + var again = qaList.querySelector('[data-question-id="' + focused + '"]'); + if (again && !again.disabled) { + again.focus(); + } + } + } + + if (qaForm) { + qaForm.addEventListener('submit', function (event) { + event.preventDefault(); + var field = qaForm.querySelector('[name=question]'); + var text = field.value.trim(); + if (!text) { + return; + } + sendQa({ question: text }).then(function (response) { + if (response && response.ok) { + field.value = ''; + } + }); + }); + } + function renderResults(state) { current = state; + renderQa(state); if (!card || !container) { return; }