From fd8da4c16c24ffca40bf1536cd6af2d05dd741b5 Mon Sep 17 00:00:00 2001 From: Patrick Niebeling Date: Sat, 7 Nov 2026 14:39:21 +0100 Subject: [PATCH] Add quiz slide type Quiz slides have predefined answers with one or more marked as correct. The presenter starts the quiz, which then runs until its optional time limit expires or the presenter ends it. Counts and correct answers are only revealed once the quiz is finished; participants then see whether their answer was right. - migration: slide_options.is_correct, slides.voting_started_at/voting_ends_at - Slide::isVotingOpen() includes the quiz deadline, expired quizzes are closed lazily when the state is read - presenter countdown, quiz tiles and reveal with correct-answer summary - CSV export marks quiz answers as right/wrong Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 19 +- .../20261107130000_AddQuizToSlides.php | 29 +++ src/Controller/AdminController.php | 11 +- src/Controller/SlidesController.php | 64 +++++- src/Model/Entity/Slide.php | 111 ++++++++++ src/Model/Entity/SlideOption.php | 1 + src/Model/Table/SlidesTable.php | 60 ++++- src/Service/PollStateService.php | 63 +++++- src/Service/ResultsService.php | 46 ++++ src/Service/VoteService.php | 28 ++- templates/Admin/index.php | 13 +- templates/Participate/view.php | 51 ++++- templates/Slides/form.php | 55 ++++- .../Controller/AdminControllerTest.php | 61 ++++++ tests/TestCase/PlenarioTestTrait.php | 6 +- tests/TestCase/Service/QuizTest.php | 205 ++++++++++++++++++ webroot/css/plenario.css | 52 +++++ webroot/js/plenario.js | 167 +++++++++++++- 18 files changed, 999 insertions(+), 43 deletions(-) create mode 100644 config/Migrations/20261107130000_AddQuizToSlides.php create mode 100644 tests/TestCase/Service/QuizTest.php diff --git a/AGENTS.md b/AGENTS.md index 114406f..f92b303 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -74,9 +74,10 @@ 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`), `question`, `description`, `position`, - `settings` (JSON, je Typ siehe `Slide::DEFAULT_SETTINGS`), `is_voting_open` -- `slide_options`: Antwortoptionen für `choice` +- `slides`: `type` (`choice|wordcloud|open|scale|content|quiz`), `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) +- `slide_options`: Antwortoptionen für `choice` und `quiz`; `is_correct` markiert richtige Quiz-Antworten - `responses`: `participant_hash`, `slide_option_id` | `text_value` | `numeric_value`. Mehrfachauswahl/mehrere Wörter = mehrere Zeilen mit gleichem `participant_hash`. @@ -98,6 +99,13 @@ tests/ PHPUnit; PlenarioTestTrait erzeugt Testdaten, Fixtures Downvotes (`vote=down`, Setting `allow_downvotes`, nur zusammen mit Upvotes): Zeile mit `numeric_value = VoteService::DOWNVOTE` (-1), nur auf fremde, vorhandene Begriffe, ein Rating pro Begriff und Person. Wortgröße richtet sich nur nach den Upvotes (`count`), Downvotes stehen separat in `down`. +- Quiz: Phasen `ready` → `running` → `finished` (`Slide::quizPhase()`). Neue Quiz-Folien starten geschlossen; + erst der Presenter startet (`control` open/toggle → `Slide::setVotingOpen()` setzt Start + Deadline aus + `time_limit`, erneutes Öffnen eines laufenden Quiz startet den Timer nicht neu). „Offen“ heißt immer + `Slide::isVotingOpen()` (inkl. Deadline), nicht nur `is_voting_open`. Abgelaufene Quizze schließt + `SlidesTable::closeIfExpired()` beim State-Abruf. **Zählungen und `is_correct` dürfen vor `finished` nie im + JSON/HTML landen** (weder Presenter noch Teilnehmende); danach sehen Teilnehmende die Auflösung immer, + unabhängig von `show_results_to_participants`. Zurücksetzen setzt das Quiz wieder auf `ready`. - `Poll`/`Response` haben `_hidden` für sensible Felder; mass assignment über `_accessible` restriktiv halten. - Alle POST-Formulare laufen über CSRF (`CsrfProtectionMiddleware`). JS sendet `X-CSRF-Token` aus ``. - Ausgaben in Templates immer mit `h()` escapen. JS baut DOM mit `textContent`, nie `innerHTML` mit Nutzerdaten. @@ -111,7 +119,8 @@ 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` +7. Tests in `tests/TestCase/Service/VoteServiceTest.php` (Quiz: `QuizTest.php`) +8. Nach neuen Spalten lokal `bin/cake cache clear_all`, sonst nutzt das ORM das alte Schema aus dem Cache ### Live-Updates @@ -155,5 +164,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 mit richtigen Antworten/Punkten, Bilder auf Folien, +- Mögliche Erweiterungen: Q&A mit Upvotes, Quiz-Punkte/Bestenliste über mehrere Fragen, Bilder auf Folien, Umfrage duplizieren, mehrsprachige UI (Übersetzungen unter `resources/locales`). diff --git a/config/Migrations/20261107130000_AddQuizToSlides.php b/config/Migrations/20261107130000_AddQuizToSlides.php new file mode 100644 index 0000000..90189ef --- /dev/null +++ b/config/Migrations/20261107130000_AddQuizToSlides.php @@ -0,0 +1,29 @@ +table('slide_options') + ->addColumn('is_correct', 'boolean', ['null' => false, 'default' => false, 'after' => 'label']) + ->update(); + + $this->table('slides') + ->addColumn('voting_started_at', 'datetime', ['null' => true, 'default' => null, 'after' => 'is_voting_open']) + ->addColumn('voting_ends_at', 'datetime', ['null' => true, 'default' => null, 'after' => 'voting_started_at']) + ->update(); + } +} diff --git a/src/Controller/AdminController.php b/src/Controller/AdminController.php index c4ea776..3c650fb 100644 --- a/src/Controller/AdminController.php +++ b/src/Controller/AdminController.php @@ -194,12 +194,13 @@ class AdminController extends AdminAppController case 'close': case 'toggle': if ($index !== false) { + // Opening a quiz (re)starts its timer, see Slide::setVotingOpen(). $slide = $slides[$index]; - $slide->is_voting_open = match ($action) { + $slide->setVotingOpen(match ($action) { 'open' => true, 'close' => false, - default => !$slide->is_voting_open, - }; + default => !$slide->isVotingOpen(), + }); $this->Slides->saveOrFail($slide); } break; @@ -258,7 +259,9 @@ class AdminController extends AdminAppController } $labels = []; foreach ($slide->slide_options ?? [] as $option) { - $labels[$option->id] = $option->label; + $labels[$option->id] = $slide->isQuiz() + ? __('{0} ({1})', $option->label, $option->is_correct ? __('richtig') : __('falsch')) + : $option->label; } $responses = $this->Responses->find() ->where(['slide_id' => $slide->id]) diff --git a/src/Controller/SlidesController.php b/src/Controller/SlidesController.php index cba4fbc..fbf102f 100644 --- a/src/Controller/SlidesController.php +++ b/src/Controller/SlidesController.php @@ -40,10 +40,14 @@ class SlidesController extends AdminAppController ]); $slide->setNew(true); $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; $optionsText = $type === Slide::TYPE_CHOICE ? "\n" : ''; + $quizOptions = []; if ($this->request->is('post')) { $optionsText = (string)$this->request->getData('options_text', ''); + $quizOptions = $this->postedQuizOptions(); if ($this->saveSlide($slide, $optionsText)) { $this->Flash->success(__('Folie angelegt.')); @@ -51,7 +55,7 @@ class SlidesController extends AdminAppController } } - $this->set(compact('slide', 'optionsText')); + $this->set(compact('slide', 'optionsText', 'quizOptions')); $this->render('form'); return null; @@ -65,9 +69,11 @@ class SlidesController extends AdminAppController { $slide = $this->loadSlide($id); $optionsText = implode("\n", array_map(fn($o) => $o->label, $slide->slide_options ?? [])); + $quizOptions = array_map(fn($o) => ['label' => $o->label, 'correct' => $o->is_correct], $slide->slide_options ?? []); if ($this->request->is(['post', 'put', 'patch'])) { $optionsText = (string)$this->request->getData('options_text', ''); + $quizOptions = $this->postedQuizOptions(); if ($this->saveSlide($slide, $optionsText)) { $this->Flash->success(__('Folie gespeichert.')); @@ -76,7 +82,7 @@ class SlidesController extends AdminAppController } $hasResponses = $this->Slides->Responses->exists(['slide_id' => $slide->id]); - $this->set(compact('slide', 'optionsText', 'hasResponses')); + $this->set(compact('slide', 'optionsText', 'quizOptions', 'hasResponses')); $this->render('form'); return null; @@ -125,6 +131,13 @@ class SlidesController extends AdminAppController $this->request->allowMethod(['post']); $slide = $this->loadSlide($id); $this->Slides->Responses->deleteAll(['slide_id' => $slide->id]); + if ($slide->isQuiz()) { + // Back to "not started" so the quiz can be played again. + $slide->is_voting_open = false; + $slide->voting_started_at = null; + $slide->voting_ends_at = null; + $this->Slides->saveOrFail($slide); + } $this->Flash->success(__('Antworten der Folie „{0}“ wurden gelöscht.', $slide->question)); return $this->redirect($this->adminUrl()); @@ -150,6 +163,26 @@ class SlidesController extends AdminAppController return $slide; } + /** + * Quiz option rows as posted by the form (for re-rendering after errors). + * + * @return list + */ + protected function postedQuizOptions(): array + { + $rows = []; + foreach ((array)$this->request->getData('quiz_options', []) as $row) { + if (is_array($row)) { + $rows[] = [ + 'label' => (string)($row['label'] ?? ''), + 'correct' => filter_var($row['correct'] ?? false, FILTER_VALIDATE_BOOLEAN), + ]; + } + } + + return $rows; + } + /** * Patches and saves a slide incl. its options. * @@ -162,27 +195,40 @@ class SlidesController extends AdminAppController $data = (array)$this->request->getData(); // The type of an existing slide cannot change (would invalidate responses). $data['type'] = $slide->type; - $this->Slides->patchEntity($slide, $data, [ - 'fields' => ['type', 'question', 'description', 'settings', 'is_voting_open'], - 'associated' => [], - ]); + $fields = ['type', 'question', 'description', 'settings', 'is_voting_open']; + if ($slide->isQuiz()) { + // Quiz voting is controlled by the presenter only. + $fields = array_values(array_diff($fields, ['is_voting_open'])); + } + $this->Slides->patchEntity($slide, $data, ['fields' => $fields, 'associated' => []]); $labels = SlidesTable::parseOptionLines($optionsText); + $correct = []; if ($slide->type === Slide::TYPE_CHOICE && count($labels) < 2) { $slide->setError('options_text', __('Bitte gib mindestens zwei Antwortoptionen an (eine pro Zeile).')); } + if ($slide->isQuiz()) { + ['labels' => $labels, 'correct' => $correct] = SlidesTable::parseQuizOptions( + (array)$this->request->getData('quiz_options', []), + ); + if (count($labels) < 2) { + $slide->setError('quiz_options', __('Bitte gib mindestens zwei Antworten an.')); + } elseif ($correct === []) { + $slide->setError('quiz_options', __('Bitte markiere mindestens eine Antwort als richtig.')); + } + } if ($slide->hasErrors()) { $this->Flash->error(__('Bitte prüfe deine Eingaben.')); return false; } - return (bool)$this->Slides->getConnection()->transactional(function () use ($slide, $labels): bool { + return (bool)$this->Slides->getConnection()->transactional(function () use ($slide, $labels, $correct): bool { if (!$this->Slides->save($slide)) { return false; } - if ($slide->type === Slide::TYPE_CHOICE) { - $this->Slides->syncOptions($slide, $labels); + if ($slide->type === Slide::TYPE_CHOICE || $slide->isQuiz()) { + $this->Slides->syncOptions($slide, $labels, $correct); } return true; diff --git a/src/Model/Entity/Slide.php b/src/Model/Entity/Slide.php index cc26744..346a114 100644 --- a/src/Model/Entity/Slide.php +++ b/src/Model/Entity/Slide.php @@ -3,6 +3,7 @@ declare(strict_types=1); namespace App\Model\Entity; +use Cake\I18n\DateTime; use Cake\ORM\Entity; /** @@ -17,6 +18,8 @@ use Cake\ORM\Entity; * @property int $position * @property array|null $settings * @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 \Cake\I18n\DateTime $created * @property \Cake\I18n\DateTime $modified * @property \App\Model\Entity\Poll $poll @@ -30,6 +33,21 @@ class Slide extends Entity public const TYPE_OPEN = 'open'; public const TYPE_SCALE = 'scale'; public const TYPE_CONTENT = 'content'; + public const TYPE_QUIZ = 'quiz'; + + /** + * Quiz phases, see quizPhase(). + */ + public const QUIZ_READY = 'ready'; + public const QUIZ_RUNNING = 'running'; + public const QUIZ_FINISHED = 'finished'; + + /** + * Selectable quiz time limits in seconds (0 = presenter ends the quiz manually). + * + * @var list + */ + public const QUIZ_TIME_LIMITS = [0, 10, 15, 20, 30, 45, 60, 90, 120, 180, 300]; /** * Default settings per type. Unknown keys are dropped on save. @@ -43,6 +61,8 @@ class Slide extends Entity self::TYPE_OPEN => [], self::TYPE_SCALE => ['scale_min' => 1, 'scale_max' => 5, 'min_label' => '', 'max_label' => ''], self::TYPE_CONTENT => [], + // time_limit in seconds, 0 = no limit (presenter ends the quiz) + self::TYPE_QUIZ => ['time_limit' => 30], ]; /** @@ -66,6 +86,7 @@ class Slide extends Entity self::TYPE_WORDCLOUD => __('Wortwolke'), self::TYPE_OPEN => __('Offene Frage'), self::TYPE_SCALE => __('Skala'), + self::TYPE_QUIZ => __('Quiz'), self::TYPE_CONTENT => __('Inhaltsfolie'), ]; } @@ -80,6 +101,7 @@ class Slide extends Entity self::TYPE_WORDCLOUD => __('Teilnehmende geben Begriffe ein oder unterstützen vorhandene, häufige werden größer.'), 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_CONTENT => __('Nur Text anzeigen, ohne Abstimmung.'), ]; } @@ -102,6 +124,95 @@ class Slide extends Entity return $this->type !== self::TYPE_CONTENT; } + /** + * Whether answers are accepted right now: voting is open and the deadline + * of a timed quiz has not passed. + * + * @param \Cake\I18n\DateTime|null $now Reference time (default: now) + * @return bool + */ + public function isVotingOpen(?DateTime $now = null): bool + { + if (!$this->is_voting_open) { + return false; + } + + return $this->voting_ends_at === null || ($now ?? DateTime::now())->lessThan($this->voting_ends_at); + } + + /** + * Whether a timed quiz is still flagged open although its deadline has passed. + * + * @param \Cake\I18n\DateTime|null $now Reference time (default: now) + * @return bool + */ + public function isExpired(?DateTime $now = null): bool + { + return $this->is_voting_open && !$this->isVotingOpen($now); + } + + /** + * @return bool + */ + public function isQuiz(): bool + { + return $this->type === self::TYPE_QUIZ; + } + + /** + * Phase of a quiz: ready (not started yet), running, finished (time up or + * closed by the presenter). Results and correct answers are only revealed + * when finished. + * + * @param \Cake\I18n\DateTime|null $now Reference time (default: now) + * @return string One of the QUIZ_* constants + */ + public function quizPhase(?DateTime $now = null): string + { + if ($this->isVotingOpen($now)) { + return self::QUIZ_RUNNING; + } + + return $this->voting_started_at === null ? self::QUIZ_READY : self::QUIZ_FINISHED; + } + + /** + * Seconds left of a running timed quiz, null without time limit. + * + * @param \Cake\I18n\DateTime|null $now Reference time (default: now) + * @return int|null + */ + public function remainingSeconds(?DateTime $now = null): ?int + { + if ($this->voting_ends_at === null) { + return null; + } + if (!$this->isVotingOpen($now)) { + return 0; + } + + return max(0, $this->voting_ends_at->getTimestamp() - ($now ?? DateTime::now())->getTimestamp()); + } + + /** + * Opens or closes voting. Opening a quiz that is not running (re)starts its + * voting window and timer; opening a running quiz changes nothing. + * + * @param bool $open Open or close + * @param \Cake\I18n\DateTime|null $now Reference time (default: now) + * @return void + */ + public function setVotingOpen(bool $open, ?DateTime $now = null): void + { + $now ??= DateTime::now(); + if ($open && $this->isQuiz() && !$this->isVotingOpen($now)) { + $limit = (int)$this->setting('time_limit'); + $this->voting_started_at = $now; + $this->voting_ends_at = $limit > 0 ? $now->addSeconds($limit) : null; + } + $this->is_voting_open = $open; + } + /** * Settings merged with the type defaults. * diff --git a/src/Model/Entity/SlideOption.php b/src/Model/Entity/SlideOption.php index c9a93ca..54398e1 100644 --- a/src/Model/Entity/SlideOption.php +++ b/src/Model/Entity/SlideOption.php @@ -10,6 +10,7 @@ use Cake\ORM\Entity; * @property int $slide_id * @property string $label * @property int $position + * @property bool $is_correct Quiz: correct answer (never expose before the quiz is finished) */ class SlideOption extends Entity { diff --git a/src/Model/Table/SlidesTable.php b/src/Model/Table/SlidesTable.php index 0d79db8..5ecc7a6 100644 --- a/src/Model/Table/SlidesTable.php +++ b/src/Model/Table/SlidesTable.php @@ -21,6 +21,7 @@ use Cake\Validation\Validator; class SlidesTable extends Table { public const MAX_OPTIONS = 20; + public const MAX_QUIZ_OPTIONS = 10; /** * @param array $config The configuration for the Table. @@ -151,6 +152,12 @@ class SlidesTable extends Table $settings['min_label'] = mb_substr(trim((string)($input['min_label'] ?? '')), 0, 60); $settings['max_label'] = mb_substr(trim((string)($input['max_label'] ?? '')), 0, 60); break; + case Slide::TYPE_QUIZ: + $limit = (int)($input['time_limit'] ?? $settings['time_limit']); + if (in_array($limit, Slide::QUIZ_TIME_LIMITS, true)) { + $settings['time_limit'] = $limit; + } + break; } return $settings; @@ -175,6 +182,53 @@ class SlidesTable extends Table return array_slice($labels, 0, self::MAX_OPTIONS); } + /** + * Parses the quiz option rows of the slide form (`quiz_options[i][label|correct]`). + * Empty rows are skipped, duplicate labels are merged. + * + * @param array $rows Raw form rows + * @return array{labels: list, correct: list} + */ + public static function parseQuizOptions(array $rows): array + { + $labels = []; + $correct = []; + foreach ($rows as $row) { + if (!is_array($row)) { + continue; + } + $label = mb_substr(trim((string)($row['label'] ?? '')), 0, 255); + if ($label === '' || count($labels) >= self::MAX_QUIZ_OPTIONS) { + continue; + } + if (!in_array($label, $labels, true)) { + $labels[] = $label; + } + if (filter_var($row['correct'] ?? false, FILTER_VALIDATE_BOOLEAN) && !in_array($label, $correct, true)) { + $correct[] = $label; + } + } + + return ['labels' => $labels, 'correct' => $correct]; + } + + /** + * Persists the end of a timed quiz once its deadline has passed. Safe to + * call repeatedly (no-op unless the slide is still flagged open). + * + * @param \App\Model\Entity\Slide $slide Slide + * @return \App\Model\Entity\Slide + */ + public function closeIfExpired(Slide $slide): Slide + { + if ($slide->isExpired()) { + $slide->is_voting_open = false; + $this->saveOrFail($slide); + } + + return $slide; + } + /** * Synchronises the answer options of a slide with the given labels. * Options whose label is unchanged keep their id (and therefore their votes); @@ -182,9 +236,10 @@ class SlidesTable extends Table * * @param \App\Model\Entity\Slide $slide Saved slide * @param list $labels New labels in display order + * @param list $correct Labels of the correct options (quiz) * @return void */ - public function syncOptions(Slide $slide, array $labels): void + public function syncOptions(Slide $slide, array $labels, array $correct = []): void { $existing = $this->SlideOptions->find() ->where(['slide_id' => $slide->id]) @@ -192,11 +247,12 @@ class SlidesTable extends Table ->indexBy('label') ->toArray(); - $this->getConnection()->transactional(function () use ($slide, $labels, $existing): void { + $this->getConnection()->transactional(function () use ($slide, $labels, $correct, $existing): void { foreach ($labels as $index => $label) { $option = $existing[$label] ?? $this->SlideOptions->newEntity(['label' => $label]); $option->set('slide_id', $slide->id); $option->set('position', $index + 1); + $option->set('is_correct', in_array($label, $correct, true)); $this->SlideOptions->saveOrFail($option); unset($existing[$label]); } diff --git a/src/Service/PollStateService.php b/src/Service/PollStateService.php index 9ebe407..f4a9a9e 100644 --- a/src/Service/PollStateService.php +++ b/src/Service/PollStateService.php @@ -17,6 +17,11 @@ use Cake\ORM\Locator\LocatorAwareTrait; * the participant has answered (or voting is closed). Exception: word clouds * with upvotes enabled show the live cloud while voting is open, because * participants upvote by clicking words in it. + * + * Quiz slides reveal results (and the participant's own correctness) only + * once the quiz is finished – then always, independent of + * `show_results_to_participants`. Timed quizzes are closed lazily here + * when their deadline has passed. */ class PollStateService { @@ -58,7 +63,7 @@ class PollStateService ->contain(['SlideOptions']) ->first(); - return $slide; + return $slide ? $this->Slides->closeIfExpired($slide) : null; } /** @@ -72,7 +77,7 @@ class PollStateService $index = null; foreach ($slides as $i => $slide) { if ($slide->id === $poll->current_slide_id) { - $current = $slide; + $current = $this->Slides->closeIfExpired($slide); $index = $i; } } @@ -105,27 +110,29 @@ 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); + $isVotingOpen = $slide?->isVotingOpen() ?? false; $showResults = $slide !== null && $slide->isInteractive() - && ( - ($poll->show_results_to_participants && ($hasResponded || !$slide->is_voting_open)) - || ($words !== null && $words['allowUpvotes'] && $slide->is_voting_open) - ); + && ($quiz !== null + ? $quiz['phase'] === Slide::QUIZ_FINISHED + : ($poll->show_results_to_participants && ($hasResponded || !$isVotingOpen)) + || ($words !== null && $words['allowUpvotes'] && $isVotingOpen)); return [ 'isActive' => $poll->is_active, 'slideId' => $slide?->id, - 'isVotingOpen' => $slide?->is_voting_open ?? false, + 'isVotingOpen' => $isVotingOpen, 'hasResponded' => $hasResponded, // Changes whenever the participant page must re-render. 'version' => implode(':', [ (int)$poll->is_active, $slide?->id ?? 0, - (int)($slide?->is_voting_open ?? 0), + (int)$isVotingOpen, // Word clouds are answered word by word without reload. $words !== null ? 0 : (int)$hasResponded, $slide?->modified?->toUnixString() ?? 0, @@ -133,6 +140,44 @@ class PollStateService 'slide' => $showResults ? $this->slidePayload($slide) : null, 'results' => $showResults ? $this->results->forSlide($slide) : null, 'words' => $words, + 'quiz' => $quiz, + ]; + } + + /** + * Quiz progress of one participant. The own answer and its correctness are + * only included once the quiz is finished. + * + * @param \App\Model\Entity\Slide $slide Quiz slide incl. slide_options + * @param string $participantHash Participant hash + * @return array{phase: string, remaining: int|null, answerId: int|null, isCorrect: bool|null} + */ + public function quizState(Slide $slide, string $participantHash): array + { + $phase = $slide->quizPhase(); + $answerId = null; + $isCorrect = null; + if ($phase === Slide::QUIZ_FINISHED) { + $response = $this->Responses->find() + ->select(['slide_option_id']) + ->where(['slide_id' => $slide->id, 'participant_hash' => $participantHash]) + ->first(); + $answerId = $response?->slide_option_id; + if ($answerId !== null) { + $isCorrect = false; + foreach ($slide->slide_options ?? [] as $option) { + if ($option->id === $answerId) { + $isCorrect = $option->is_correct; + } + } + } + } + + return [ + 'phase' => $phase, + 'remaining' => $phase === Slide::QUIZ_RUNNING ? $slide->remainingSeconds() : null, + 'answerId' => $answerId, + 'isCorrect' => $isCorrect, ]; } @@ -171,7 +216,7 @@ class PollStateService 'typeLabel' => $slide->typeLabel(), 'question' => $slide->question, 'description' => (string)$slide->description, - 'isVotingOpen' => $slide->is_voting_open, + 'isVotingOpen' => $slide->isVotingOpen(), 'isInteractive' => $slide->isInteractive(), 'settings' => $slide->getSettings(), ]; diff --git a/src/Service/ResultsService.php b/src/Service/ResultsService.php index 263065f..100a018 100644 --- a/src/Service/ResultsService.php +++ b/src/Service/ResultsService.php @@ -19,6 +19,11 @@ use Cake\ORM\Locator\LocatorAwareTrait; * - open: 'answers' => [['text', 'created']] newest first * - scale: 'buckets' => [['value', 'count', 'percent']], 'average' => float|null, * 'min', 'max', 'minLabel', 'maxLabel' + * - quiz: 'phase' (ready|running|finished), 'timeLimit' (s, 0 = manual), 'remaining' (s|null), + * 'revealed' (bool), 'options' => [['id', 'label']] while not finished; + * 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. */ class ResultsService { @@ -54,6 +59,7 @@ class ResultsService Slide::TYPE_WORDCLOUD => $this->wordcloud($slide), Slide::TYPE_OPEN => $this->open($slide), Slide::TYPE_SCALE => $this->scale($slide), + Slide::TYPE_QUIZ => $this->quiz($slide), default => [], }; } @@ -88,6 +94,46 @@ class ResultsService return ['options' => $options, 'votes' => $total]; } + /** + * @param \App\Model\Entity\Slide $slide Slide + * @return array + */ + protected function quiz(Slide $slide): array + { + $phase = $slide->quizPhase(); + $result = [ + 'phase' => $phase, + 'timeLimit' => (int)$slide->setting('time_limit'), + 'remaining' => $phase === Slide::QUIZ_RUNNING ? $slide->remainingSeconds() : null, + 'revealed' => $phase === Slide::QUIZ_FINISHED, + ]; + if ($phase !== Slide::QUIZ_FINISHED) { + $result['options'] = array_map(fn($option) => [ + 'id' => $option->id, + 'label' => $option->label, + ], $slide->slide_options ?? []); + + return $result; + } + + $choice = $this->choice($slide); + $correctIds = []; + foreach ($slide->slide_options ?? [] as $option) { + if ($option->is_correct) { + $correctIds[] = $option->id; + } + } + $result['options'] = array_map(fn(array $option) => $option + [ + 'correct' => in_array($option['id'], $correctIds, true), + ], $choice['options']); + $result['correctCount'] = $correctIds === [] ? 0 : $this->Responses->find() + ->where(['slide_id' => $slide->id, 'slide_option_id IN' => $correctIds]) + ->distinct(['participant_hash']) + ->count(); + + return $result; + } + /** * @param \App\Model\Entity\Slide $slide Slide * @return array diff --git a/src/Service/VoteService.php b/src/Service/VoteService.php index 39fd668..48ba226 100644 --- a/src/Service/VoteService.php +++ b/src/Service/VoteService.php @@ -21,6 +21,8 @@ use Cake\Utility\Security; * exists in the cloud is an upvote – both are stored as the same row. * `vote=down` stores a downvote (numeric_value = DOWNVOTE) for an existing * 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). */ class VoteService { @@ -78,8 +80,12 @@ class VoteService if (!$slide->isInteractive()) { throw new VoteException(__('Auf dieser Folie kann nicht abgestimmt werden.')); } - if (!$slide->is_voting_open) { - throw new VoteException(__('Die Abstimmung zu dieser Frage ist geschlossen.')); + if (!$slide->isVotingOpen()) { + 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.'), + default => __('Die Abstimmung zu dieser Frage ist geschlossen.'), + }); } if ($slide->type !== Slide::TYPE_WORDCLOUD && $this->Responses->hasResponded($slide->id, $participantHash)) { throw new VoteException(__('Du hast bereits abgestimmt.')); @@ -90,6 +96,7 @@ class VoteService Slide::TYPE_WORDCLOUD => $this->wordRows($slide, $participantHash, $data), Slide::TYPE_OPEN => $this->openRows($data), Slide::TYPE_SCALE => $this->scaleRows($slide, $data), + Slide::TYPE_QUIZ => $this->quizRows($slide, $data), default => throw new VoteException(__('Unbekannter Folientyp.')), }; @@ -125,6 +132,23 @@ class VoteService return array_map(fn(int $id) => ['slide_option_id' => $id], $selected); } + /** + * @param \App\Model\Entity\Slide $slide Slide + * @param array $data Request data + * @return list> + */ + protected function quizRows(Slide $slide, array $data): array + { + $selected = $data['option_id'] ?? null; + $id = is_scalar($selected) ? filter_var($selected, FILTER_VALIDATE_INT) : false; + $validIds = array_map(fn($option) => $option->id, $slide->slide_options ?? []); + if ($id === false || !in_array($id, $validIds, true)) { + throw new VoteException(__('Bitte wähle eine Antwort aus.')); + } + + return [['slide_option_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 9300f12..808526f 100644 --- a/templates/Admin/index.php +++ b/templates/Admin/index.php @@ -65,12 +65,23 @@ $url = fn(string $name, array $params = []) => ['_name' => $name, 'token' => $ad isInteractive()) : ?> - is_voting_open) : ?>· + isQuiz()) : ?> + · __('Quiz noch nicht gestartet'), + 'running' => __('Quiz läuft'), + 'finished' => __('Quiz beendet'), + ][$slide->quizPhase()]) ?> + is_voting_open) : ?>· question) ?> type === 'choice' && $slide->slide_options) : ?>

$o->label, $slide->slide_options))) ?>

+ isQuiz() && $slide->slide_options) : ?> +

$o->is_correct ? '✓ ' . $o->label : $o->label, + $slide->slide_options, + ))) ?>

diff --git a/templates/Participate/view.php b/templates/Participate/view.php index de257e4..49160f6 100644 --- a/templates/Participate/view.php +++ b/templates/Participate/view.php @@ -13,6 +13,17 @@ $this->assign('title', $poll->title); $this->assign('bodyClass', 'participant'); $voteUrl = ['_name' => 'participate:vote', 'code' => $poll->join_code]; $words = $state['words'] ?? null; +$quiz = $state['quiz'] ?? null; +$countdown = function (?int $remaining): string { + if ($remaining === null) { + return ''; + } + + return '

' + . '' . h(__('Noch')) . ' ' + . '' . sprintf('%d:%02d', intdiv($remaining, 60), $remaining % 60) . '' + . '

'; +}; ?>
description)) ?>

- is_voting_open) : ?> + + +
+ +

+
+ + +

✓

+

+ + + Form->create(null, ['url' => $voteUrl, 'class' => 'vote-form', 'data-quiz-form' => true]) ?> + Form->hidden('slide_id', ['value' => $slide->id]) ?> +
+ + slide_options as $index => $option) : ?> + + +
+ Form->button(__('Antwort abgeben'), ['class' => 'button button--primary button--block']) ?> + Form->end() ?> + +

✓

+ +

✗

+ +

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

@@ -113,7 +156,11 @@ $words = $state['words'] ?? null;
> -

+

__('Wortwolke'), + $quiz !== null => __('Auflösung'), + default => __('Ergebnisse'), + } ?>

is_voting_open) : ?>

$quizOptions * @var bool|null $hasResponses */ $isNew = $slide->isNew(); @@ -85,9 +86,61 @@ $optionsError = $slide->getError('options_text'); 'placeholder' => __('z. B. sehr'), 'value' => $settings['max_label'], ]) ?>

+ type === 'quiz') : + $quizError = $slide->getError('quiz_options'); + $rows = $quizOptions; + // Always offer a few empty rows (more via "Antwort hinzufügen" with JS). + $rowCount = min(\App\Model\Table\SlidesTable::MAX_QUIZ_OPTIONS, max(4, count($rows) + 1)); + $rows = array_pad($rows, $rowCount, ['label' => '', 'correct' => false]); + ?> +
> + +

+
    + $row) : ?> +
  1. + + > + +
  2. + +
+ + +
+ + +

+ +
+ __('Kein Zeitlimit – ich beende das Quiz selbst'), + $seconds < 60 => __('{0} Sekunden', $seconds), + $seconds % 60 === 0 => __n('{0} Minute', '{0} Minuten', intdiv($seconds, 60), intdiv($seconds, 60)), + default => __('{0} Minuten', number_format($seconds / 60, 1, ',', '')), + }; + } + ?> + Form->control('settings.time_limit', [ + 'type' => 'select', + 'options' => $limits, + 'label' => __('Zeitlimit'), + 'value' => $settings['time_limit'], + ]) ?> +

- isInteractive()) : ?> + isInteractive() && !$slide->isQuiz()) : ?> Form->control('is_voting_open', [ 'type' => 'checkbox', 'label' => __('Abstimmung geöffnet'), diff --git a/tests/TestCase/Controller/AdminControllerTest.php b/tests/TestCase/Controller/AdminControllerTest.php index 72d58ed..5498309 100644 --- a/tests/TestCase/Controller/AdminControllerTest.php +++ b/tests/TestCase/Controller/AdminControllerTest.php @@ -88,6 +88,67 @@ class AdminControllerTest extends TestCase $this->assertSame(1, $slide->position); } + public function testAddQuizSlide(): void + { + [, $token] = $this->createPoll(); + $data = [ + 'type' => 'quiz', + 'question' => 'Hauptstadt von Frankreich?', + 'settings' => ['time_limit' => '20'], + 'is_voting_open' => '1', + 'quiz_options' => [ + ['label' => 'Lyon', 'correct' => '0'], + ['label' => 'Paris', 'correct' => '1'], + ['label' => ''], + ], + ]; + + $this->get("/admin/$token/slides/add?type=quiz"); + $this->assertResponseOk(); + $this->assertResponseContains('name="quiz_options[0][label]"'); + $this->assertResponseNotContains('name="is_voting_open"'); + + $this->post("/admin/$token/slides/add?type=quiz", ['quiz_options' => [['label' => 'A'], ['label' => 'B']]] + $data); + $this->assertResponseOk(); + $this->assertResponseContains('Bitte markiere mindestens eine Antwort als richtig.'); + + $this->post("/admin/$token/slides/add?type=quiz", $data); + $this->assertRedirect(['_name' => 'admin', 'token' => $token]); + $slide = $this->slidesTable()->find()->contain(['SlideOptions'])->firstOrFail(); + $this->assertSame(['Lyon', 'Paris'], array_map(fn($o) => $o->label, $slide->slide_options)); + $this->assertSame([false, true], array_map(fn($o) => $o->is_correct, $slide->slide_options)); + $this->assertSame(['time_limit' => 20], $slide->settings); + $this->assertFalse($slide->is_voting_open, 'quiz starts closed until the presenter starts it'); + } + + public function testPresenterStartsAndEndsQuiz(): void + { + [$poll, $token] = $this->createPoll(); + $slide = $this->createSlide($poll, Slide::TYPE_QUIZ, ['is_voting_open' => false], ['Richtig', 'Falsch']); + $this->goLive($poll, $slide); + $control = function (string $action) use ($token): array { + $this->configRequest(['headers' => ['Accept' => 'application/json']]); + $this->post("/admin/$token/control", ['action' => $action]); + $this->assertResponseOk(); + + return json_decode((string)$this->_response->getBody(), true); + }; + + $state = $control('toggle'); + $this->assertSame('running', $state['results']['phase']); + $this->assertGreaterThan(25, $state['results']['remaining']); + $this->assertStringNotContainsString('correct', (string)$this->_response->getBody()); + $this->assertNotNull($this->slidesTable()->get($slide->id)->voting_ends_at); + + $state = $control('toggle'); + $this->assertSame('finished', $state['results']['phase']); + $this->assertTrue($state['results']['options'][0]['correct']); + + $this->post("/admin/$token/slides/{$slide->id}/reset"); + $slide = $this->slidesTable()->get($slide->id); + $this->assertSame(Slide::QUIZ_READY, $slide->quizPhase()); + } + public function testEditKeepsVotesOfUnchangedOptions(): void { [$poll, $token] = $this->createPoll(); diff --git a/tests/TestCase/PlenarioTestTrait.php b/tests/TestCase/PlenarioTestTrait.php index 1a4c4f6..49c48d4 100644 --- a/tests/TestCase/PlenarioTestTrait.php +++ b/tests/TestCase/PlenarioTestTrait.php @@ -32,7 +32,7 @@ trait PlenarioTestTrait * @param \App\Model\Entity\Poll $poll Poll * @param string $type Slide type * @param array $data Extra slide data - * @param list $options Option labels (choice) + * @param list $options Option labels (choice, quiz: the first one is correct) * @return \App\Model\Entity\Slide Slide incl. slide_options */ protected function createSlide(Poll $poll, string $type = Slide::TYPE_CHOICE, array $data = [], array $options = ['Ja', 'Nein']): Slide @@ -49,6 +49,10 @@ trait PlenarioTestTrait if ($type === Slide::TYPE_CHOICE) { $slides->syncOptions($slide, $options); } + if ($type === Slide::TYPE_QUIZ) { + // First option is the correct one. + $slides->syncOptions($slide, $options, [$options[0]]); + } return $slides->get($slide->id, contain: ['SlideOptions']); } diff --git a/tests/TestCase/Service/QuizTest.php b/tests/TestCase/Service/QuizTest.php new file mode 100644 index 0000000..9518606 --- /dev/null +++ b/tests/TestCase/Service/QuizTest.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 createQuiz(int $timeLimit = 30): array + { + [$poll] = $this->createPoll(); + $slide = $this->createSlide($poll, Slide::TYPE_QUIZ, [ + 'is_voting_open' => false, + 'settings' => ['time_limit' => $timeLimit], + ], ['Berlin', 'Hamburg', 'München']); + + return [$this->goLive($poll, $slide), $slide]; + } + + protected function setOpen(Slide $slide, bool $open, ?DateTime $now = null): Slide + { + $slide->setVotingOpen($open, $now); + $this->slidesTable()->saveOrFail($slide); + + return $this->slidesTable()->get($slide->id, contain: ['SlideOptions']); + } + + protected function optionId(Slide $slide, string $label): int + { + foreach ($slide->slide_options as $option) { + if ($option->label === $label) { + return $option->id; + } + } + $this->fail('Unknown option ' . $label); + } + + protected function participantState(Poll $poll, string $participant): array + { + return (new PollStateService())->forParticipant($this->pollsTable()->get($poll->id), $participant); + } + + public function testSanitizesTimeLimit(): void + { + [, $slide] = $this->createQuiz(); + $this->assertSame(30, $slide->setting('time_limit')); + + $slide = $this->slidesTable()->patchEntity($slide, ['type' => 'quiz', 'settings' => ['time_limit' => '7']]); + $this->assertSame(30, $slide->setting('time_limit'), 'unknown limits fall back to the default'); + $slide = $this->slidesTable()->patchEntity($slide, ['type' => 'quiz', 'settings' => ['time_limit' => '0']]); + $this->assertSame(0, $slide->setting('time_limit')); + } + + public function testNotStartedQuizRejectsVotes(): void + { + [$poll, $slide] = $this->createQuiz(); + $this->assertSame(Slide::QUIZ_READY, $slide->quizPhase()); + + $this->expectExceptionMessage('Das Quiz hat noch nicht begonnen.'); + (new VoteService())->submit($poll, $slide, 'p1', ['option_id' => $this->optionId($slide, 'Berlin')]); + } + + public function testStartingSetsTimerAndReopeningRunningQuizKeepsIt(): void + { + [, $slide] = $this->createQuiz(30); + $now = DateTime::now(); + $slide = $this->setOpen($slide, true, $now); + + $this->assertSame(Slide::QUIZ_RUNNING, $slide->quizPhase()); + $this->assertNotNull($slide->voting_ends_at); + $endsAt = $slide->voting_ends_at->getTimestamp(); + $this->assertSame($now->getTimestamp() + 30, $endsAt); + + // Idempotent: "open" on a running quiz does not restart the timer. + $slide = $this->setOpen($slide, true, $now->addSeconds(10)); + $this->assertSame($endsAt, $slide->voting_ends_at->getTimestamp()); + } + + public function testQuizWithoutTimeLimitRunsUntilClosed(): void + { + [, $slide] = $this->createQuiz(0); + $slide = $this->setOpen($slide, true); + $this->assertNull($slide->voting_ends_at); + $this->assertNull($slide->remainingSeconds()); + $this->assertTrue($slide->isVotingOpen(DateTime::now()->addHours(5))); + + $slide = $this->setOpen($slide, false); + $this->assertSame(Slide::QUIZ_FINISHED, $slide->quizPhase()); + } + + public function testRunningQuizHidesCountsAndCorrectAnswers(): void + { + [$poll, $slide] = $this->createQuiz(); + $slide = $this->setOpen($slide, true); + (new VoteService())->submit($poll, $slide, 'p1', ['option_id' => $this->optionId($slide, 'Berlin')]); + + $results = (new ResultsService())->forSlide($slide); + $this->assertSame('running', $results['phase']); + $this->assertFalse($results['revealed']); + $this->assertSame(1, $results['participants']); + $this->assertArrayNotHasKey('correctCount', $results); + foreach ($results['options'] as $option) { + $this->assertSame(['id', 'label'], array_keys($option)); + } + + $state = $this->participantState($poll, 'p1'); + $this->assertTrue($state['hasResponded']); + $this->assertNull($state['results']); + $this->assertNull($state['quiz']['answerId']); + $this->assertNull($state['quiz']['isCorrect']); + $this->assertStringNotContainsString('is_correct', (string)json_encode($state)); + } + + public function testAnswerOnceAndOnlyValidSingleOption(): void + { + [$poll, $slide] = $this->createQuiz(); + $slide = $this->setOpen($slide, true); + $service = new VoteService(); + + foreach ([[], ['option_id' => 999999], ['option_id' => ['1', '2']]] as $data) { + try { + $service->submit($poll, $slide, 'p1', $data); + $this->fail('VoteException expected'); + } catch (VoteException $e) { + $this->assertSame('Bitte wähle eine Antwort aus.', $e->getMessage()); + } + } + + $service->submit($poll, $slide, 'p1', ['option_id' => $this->optionId($slide, 'Hamburg')]); + $this->expectExceptionMessage('Du hast bereits abgestimmt.'); + $service->submit($poll, $slide, 'p1', ['option_id' => $this->optionId($slide, 'Berlin')]); + } + + public function testFinishedQuizRevealsResults(): void + { + [$poll, $slide] = $this->createQuiz(); + $slide = $this->setOpen($slide, true); + $service = new VoteService(); + $service->submit($poll, $slide, 'p1', ['option_id' => $this->optionId($slide, 'Berlin')]); + $service->submit($poll, $slide, 'p2', ['option_id' => $this->optionId($slide, 'Hamburg')]); + $service->submit($poll, $slide, 'p3', ['option_id' => $this->optionId($slide, 'Berlin')]); + $slide = $this->setOpen($slide, false); + + $results = (new ResultsService())->forSlide($slide); + $this->assertTrue($results['revealed']); + $this->assertSame(2, $results['correctCount']); + $this->assertSame(3, $results['participants']); + $this->assertSame(['Berlin', true, 2], [$results['options'][0]['label'], $results['options'][0]['correct'], $results['options'][0]['count']]); + $this->assertFalse($results['options'][1]['correct']); + + // Revealed to participants even without show_results_to_participants. + $poll->show_results_to_participants = false; + $this->pollsTable()->saveOrFail($poll); + $state = $this->participantState($poll, 'p2'); + $this->assertSame('finished', $state['quiz']['phase']); + $this->assertFalse($state['quiz']['isCorrect']); + $this->assertSame($this->optionId($slide, 'Hamburg'), $state['quiz']['answerId']); + $this->assertNotNull($state['results']); + $this->assertTrue($this->participantState($poll, 'p1')['quiz']['isCorrect']); + $this->assertNull($this->participantState($poll, 'nobody')['quiz']['isCorrect']); + } + + public function testExpiredQuizIsClosedAndRejectsVotes(): void + { + [$poll, $slide] = $this->createQuiz(30); + $slide = $this->setOpen($slide, true, DateTime::now()->subSeconds(60)); + $this->assertTrue($slide->is_voting_open); + $this->assertFalse($slide->isVotingOpen()); + $this->assertSame(Slide::QUIZ_FINISHED, $slide->quizPhase()); + + try { + (new VoteService())->submit($poll, $slide, 'p1', ['option_id' => $this->optionId($slide, 'Berlin')]); + $this->fail('VoteException expected'); + } catch (VoteException $e) { + $this->assertSame('Die Zeit für dieses Quiz ist abgelaufen.', $e->getMessage()); + } + + // Reading the state persists the end of the quiz. + $state = $this->participantState($poll, 'p1'); + $this->assertFalse($state['isVotingOpen']); + $this->assertFalse($this->slidesTable()->get($slide->id)->is_voting_open); + } +} diff --git a/webroot/css/plenario.css b/webroot/css/plenario.css index 26ac3af..d328eae 100644 --- a/webroot/css/plenario.css +++ b/webroot/css/plenario.css @@ -143,6 +143,7 @@ h3 { font-size: 1.05rem; margin-top: 1.6em; } .badge--type-open { background: #dcf5f0; color: #0b7766; } .badge--type-scale { background: #fdeed8; color: #9a5a00; } .badge--type-content { background: #e3eefb; color: #1f6bb0; } +.badge--type-quiz { background: #f1e3fb; color: #7a2fb0; } .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); } @@ -207,6 +208,18 @@ textarea { resize: vertical; } .type-card--open { border-top-color: var(--c2); } .type-card--scale { border-top-color: var(--c3); } .type-card--content { border-top-color: var(--c4); } +.type-card--quiz { border-top-color: var(--c5); } + +/* ---------------------------------------------------------------- slide form: quiz answers */ +.quiz-options { border: 0; padding: 0; margin: 0 0 16px; } +.quiz-options legend { font-weight: 600; margin-bottom: 4px; } +.quiz-options__list { list-style: none; padding: 0; margin: 0 0 10px; display: grid; gap: 8px; } +.quiz-option { display: flex; gap: 10px; align-items: center; } +.quiz-option input[type=text] { flex: 1; margin: 0; } +.quiz-option__correct { display: inline-flex; gap: 6px; align-items: center; white-space: nowrap; padding: 8px 10px; border: 2px solid var(--border); border-radius: 8px; cursor: pointer; font-weight: 600; } +.quiz-option__correct:has(input:checked) { border-color: var(--ok); color: var(--ok); } +.quiz-option__correct input { width: 18px; height: 18px; margin: 0; accent-color: var(--ok); } +.quiz-options.error .quiz-options__list input[type=text] { border-color: var(--danger); } .join-code { font-size: 2rem; font-weight: 800; letter-spacing: .12em; text-align: center; margin: 0 0 12px; } .qr { display: block; margin: 0 auto 16px; background: #fff; border-radius: 8px; padding: 6px; } @@ -247,6 +260,21 @@ textarea { resize: vertical; } @keyframes pulse { 0% { box-shadow: 0 0 0 0 rgba(75, 63, 224, .5); } 100% { box-shadow: 0 0 0 24px rgba(75, 63, 224, 0); } } .prose { font-size: 1.1rem; } +/* quiz (participant) */ +.choice--quiz { border-left-width: 8px; border-left-color: var(--c0); font-size: 1.1rem; } +.choice--c1 { border-left-color: var(--c1); } +.choice--c2 { border-left-color: var(--c2); } +.choice--c3 { border-left-color: var(--c3); } +.choice--c4 { border-left-color: var(--c4); } +.choice--c5 { border-left-color: var(--c5); } +.choices--quiz { border: 0; padding: 0; } +.countdown { display: flex; align-items: baseline; justify-content: center; gap: 8px; margin: 8px 0 0; color: var(--muted); } +.countdown__value { font-size: 2rem; font-variant-numeric: tabular-nums; color: var(--text); } +.countdown.is-urgent .countdown__value { color: var(--danger); } +.verdict { font-size: 1.6rem; font-weight: 800; margin: 12px 0 0; } +.verdict--correct { color: var(--ok); } +.verdict--wrong { color: var(--danger); } + /* ---------------------------------------------------------------- results (shared) */ .results-empty { color: var(--muted); font-style: italic; } .is-hidden { visibility: hidden; } @@ -304,6 +332,25 @@ textarea { resize: vertical; } .cloud__word.is-mine .cloud__vote--up, .cloud__word.is-down .cloud__vote--down { background: var(--surface-2); } .cloud__word.is-down .cloud__vote--up { opacity: .55; } +/* quiz results */ +.quiz-status { color: var(--muted); font-style: italic; margin: 0 0 1em; } +.quiz-timer { margin: 0 0 .6em; font-size: 2.6em; font-weight: 800; font-variant-numeric: tabular-nums; color: var(--c5); } +.quiz-timer.is-urgent { color: var(--danger); } +.quiz-timer.is-over { opacity: .5; } +.quiz-grid { list-style: none; padding: 0; margin: 0; display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 260px), 1fr)); gap: 12px; } +.quiz-tile { padding: .8em 1em; border-radius: 10px; background: var(--surface-2); border-left: .4em solid var(--c0); font-weight: 700; word-break: break-word; } +.quiz-tile--c1 { border-left-color: var(--c1); } +.quiz-tile--c2 { border-left-color: var(--c2); } +.quiz-tile--c3 { border-left-color: var(--c3); } +.quiz-tile--c4 { border-left-color: var(--c4); } +.quiz-tile--c5 { border-left-color: var(--c5); } +.quiz-summary { margin: 0 0 1em; font-size: 1.2em; } +.quiz-summary strong { color: var(--ok); } +.bar--correct .bar__fill { background: var(--ok); } +.bar--correct .bar__label { color: var(--ok); } +.bar--wrong .bar__fill { background: var(--muted); opacity: .6; } +.bar.is-mine .bar__label { text-decoration: underline; text-underline-offset: 3px; } + .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; } @@ -339,6 +386,11 @@ body.present { .stage .average__track { height: 1em; box-shadow: none; background: linear-gradient(90deg, var(--surface-2), var(--c1)); } .stage .cloud { font-size: clamp(1.4rem, 2.6vw, 2.6rem); } .stage .answers { columns: 340px; } +.stage .quiz-timer { font-size: clamp(3rem, 7vw, 6rem); } +.stage .quiz-tile { font-size: clamp(1.2rem, 2.2vw, 2rem); } +/* 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__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 3278578..8e2be2e 100644 --- a/webroot/js/plenario.js +++ b/webroot/js/plenario.js @@ -5,6 +5,8 @@ * - [data-copy] copy the value of the sibling [data-copy-source] * - [data-presenter] presenter screen, polls /admin/{token}/state * - [data-participant] participant page, polls /p/{code}/state + * - [data-countdown] quiz timer (data-remaining = seconds), fires `plenario:timeup` on document + * - [data-quiz-options] slide form: "add answer" button for quiz slides * * Results JSON shape: see src/Service/ResultsService.php */ @@ -95,6 +97,49 @@ return Number(value).toLocaleString('de-DE'); } + function formatSeconds(seconds) { + var s = Math.max(0, Math.ceil(seconds)); + return Math.floor(s / 60) + ':' + String(s % 60).padStart(2, '0'); + } + + // ------------------------------------------------------------------ countdown + + /** + * Ticks every [data-countdown] element (data-remaining = seconds left when it + * was rendered). The server stays authoritative: when a timer reaches zero, + * `plenario:timeup` is dispatched so the page fetches the new state. + */ + var Countdown = { + timer: null, + + start: function () { + if (Countdown.timer === null) { + Countdown.timer = setInterval(Countdown.tick, 250); + } + Countdown.tick(); + }, + + tick: function () { + document.querySelectorAll('[data-countdown]').forEach(function (node) { + if (!node.plenarioDeadline) { + node.plenarioDeadline = Date.now() + parseFloat(node.getAttribute('data-remaining')) * 1000; + } + var left = (node.plenarioDeadline - Date.now()) / 1000; + var value = node.querySelector('[data-countdown-value]') || node; + var text = formatSeconds(left); + if (value.textContent !== text) { + value.textContent = text; + } + node.classList.toggle('is-urgent', left <= 5); + if (left <= 0 && !node.plenarioDone) { + node.plenarioDone = true; + node.classList.add('is-over'); + document.dispatchEvent(new CustomEvent('plenario:timeup')); + } + }); + } + }; + // ------------------------------------------------------------------ word matching /** @@ -247,7 +292,8 @@ if (typeof renderer !== 'function') { return; } - if (results.participants === 0) { + // A quiz shows its answer options even before anyone has answered. + if (results.participants === 0 && !(results.type === 'quiz' && !results.revealed)) { container.appendChild(el('p', { class: 'results-empty', text: 'Noch keine Antworten' })); return; } @@ -394,6 +440,53 @@ })); }, + /** + * Before the end only the answer options (and the timer) are shown; + * counts and correct answers arrive with `revealed` (see ResultsService). + * options: {answerId: id of the participant's own answer|null} + */ + quiz: function (results, options) { + var answerId = options && options.answerId; + if (!results.revealed) { + var children = []; + if (results.phase === 'running' && results.remaining !== null) { + children.push(el('p', { + class: 'quiz-timer', + role: 'timer', + 'data-countdown': '', + 'data-remaining': String(results.remaining) + }, [el('strong', { 'data-countdown-value': '', text: formatSeconds(results.remaining) })])); + } else if (results.phase === 'running') { + children.push(el('p', { class: 'quiz-status', text: 'Quiz läuft – ohne Zeitlimit' })); + } else { + children.push(el('p', { class: 'quiz-status', text: 'Bereit – starte das Quiz, um die Antworten freizugeben' })); + } + children.push(el('ol', { class: 'quiz-grid' }, results.options.map(function (option, index) { + return el('li', { class: 'quiz-tile quiz-tile--c' + (index % 6), text: option.label }); + }))); + return el('div', { class: 'quiz-results quiz-results--' + results.phase }, children); + } + + var max = Math.max.apply(null, results.options.map(function (o) { return o.count; }).concat([1])); + var percent = results.participants > 0 ? Math.round(results.correctCount / results.participants * 100) : 0; + var summary = el('p', { class: 'quiz-summary' }, [ + el('strong', { text: results.correctCount + ' von ' + results.participants }), + el('span', { text: ' richtig (' + percent + ' %)' }) + ]); + var bars = el('div', { class: 'bars' }, results.options.map(function (option) { + var mine = answerId !== null && answerId !== undefined && option.id === answerId; + var label = (option.correct ? '✓ ' : '') + option.label + (mine ? ' (deine Antwort)' : ''); + return el('div', { class: 'bar ' + (option.correct ? 'bar--correct' : 'bar--wrong') + (mine ? ' is-mine' : '') }, [ + el('div', { class: 'bar__label', text: label }), + el('div', { class: 'bar__track' }, [ + el('div', { class: 'bar__fill', style: 'width:' + (option.count / max * 100) + '%' }) + ]), + el('div', { class: 'bar__value', text: formatNumber(option.percent) + ' % (' + option.count + ')' }) + ]); + })); + return el('div', { class: 'quiz-results quiz-results--finished' }, [summary, bars]); + }, + open: function (results) { return el('ul', { class: 'answers' }, results.answers.map(function (answer) { return el('li', { class: 'answer', text: answer.text }); @@ -467,15 +560,20 @@ return; } - q('[data-type]').textContent = slide.typeLabel; + var quizPhase = slide.type === 'quiz' && state.results ? state.results.phase : null; + q('[data-type]').textContent = quizPhase + ? slide.typeLabel + ' · ' + { ready: 'bereit', running: 'läuft', finished: 'Auflösung' }[quizPhase] + : 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--closed', slide.isInteractive && !slide.isVotingOpen); + root.classList.toggle('stage--closed', slide.isInteractive && !slide.isVotingOpen && !quizPhase); var voting = q('[data-voting]'); voting.hidden = !slide.isInteractive; - voting.textContent = slide.isVotingOpen ? 'Abstimmung schließen' : 'Abstimmung öffnen'; + voting.textContent = quizPhase + ? { ready: 'Quiz starten', running: 'Quiz beenden', finished: 'Quiz erneut öffnen' }[quizPhase] + : (slide.isVotingOpen ? 'Abstimmung schließen' : 'Abstimmung öffnen'); q('[data-participants]').textContent = slide.isInteractive ? state.results.participants + ' ' + (state.results.participants === 1 ? 'Antwort' : 'Antworten') @@ -484,6 +582,7 @@ var container = q('[data-results]'); container.classList.toggle('is-hidden', hideResults); Results.render(container, slide.isInteractive ? state.results : null); + Countdown.start(); } function refresh() { @@ -564,7 +663,11 @@ } }); - poll(refresh, interval); + var poller = poll(refresh, interval); + document.addEventListener('plenario:timeup', function () { + // The server closes the quiz once the deadline has passed. + setTimeout(poller.now, 300); + }); } // ------------------------------------------------------------------ participant @@ -604,6 +707,7 @@ Results.render(container, state.results, { mine: state.words ? state.words.mine : [], down: state.words ? state.words.down : [], + answerId: state.quiz ? state.quiz.answerId : null, onUpvote: upvote ? function (word) { sendWord(word.text); } : null, onDownvote: upvote && state.words.allowDownvotes ? function (word) { sendWord(word.text, 'down'); } : null }); @@ -759,7 +863,16 @@ } catch (e) { /* ignore */ } } - poll(function () { + var quizForm = root.querySelector('[data-quiz-form]'); + document.addEventListener('plenario:timeup', function () { + if (quizForm) { + quizForm.querySelectorAll('input, button').forEach(function (input) { input.disabled = true; }); + } + setTimeout(participantPoller.now, 300); + }); + Countdown.start(); + + var participantPoller = poll(function () { return getJson(stateUrl).then(function (state) { if (state.version !== version) { // Do not destroy what the participant is typing right now. @@ -775,12 +888,52 @@ }, interval); } + // ------------------------------------------------------------------ slide form + + /** Quiz slide form: add further answer rows (the server renders a few already). */ + function initQuizOptions(fieldset) { + var list = fieldset.querySelector('[data-quiz-list]'); + var button = fieldset.querySelector('[data-quiz-add]'); + var max = parseInt(fieldset.getAttribute('data-max'), 10) || 10; + function rows() { + return list.querySelectorAll('[data-quiz-row]'); + } + function update() { + button.hidden = rows().length >= max; + } + button.addEventListener('click', function () { + var index = rows().length; + if (index >= max) { + return; + } + var row = rows()[0].cloneNode(true); + var label = row.querySelector('label[for]'); + var text = row.querySelector('input[type=text]'); + var check = row.querySelector('input[type=checkbox]'); + var id = 'quiz-option-' + index; + label.setAttribute('for', id); + label.textContent = 'Antwort ' + (index + 1); + text.id = id; + text.name = 'quiz_options[' + index + '][label]'; + text.value = ''; + text.placeholder = 'Antwort ' + (index + 1); + text.required = false; + check.name = 'quiz_options[' + index + '][correct]'; + check.checked = false; + list.appendChild(row); + text.focus(); + update(); + }); + update(); + } + // ------------------------------------------------------------------ boot document.addEventListener('DOMContentLoaded', function () { initCopy(); document.querySelectorAll('[data-presenter]').forEach(initPresenter); document.querySelectorAll('[data-participant]').forEach(initParticipant); + document.querySelectorAll('[data-quiz-options]').forEach(initQuizOptions); // Prevent double submits of vote forms. document.querySelectorAll('.vote-form').forEach(function (form) { @@ -796,5 +949,5 @@ }); }); - window.Plenario = { Results: Results, Words: Words }; + window.Plenario = { Results: Results, Words: Words, Countdown: Countdown }; })(); -- 2.54.1