From 27771e747026504f407eab6943cf06c2ac9fa475 Mon Sep 17 00:00:00 2001 From: Patrick Niebeling Date: Sat, 21 Nov 2026 12:18:33 +0100 Subject: [PATCH] Add an optional countdown to every slide that collects answers Choice, word cloud, open question, scale and ordering slides get a time limit like the quiz. With a limit the slide waits ("ready") showing only the question; next starts the countdown, the next one ends it, the third moves on. Stage results and the ordering solution are withheld until the countdown has started. The countdown music plays during any countdown. Co-Authored-By: Claude Sonnet 5.5 --- AGENTS.md | 6 +- docs/slide-types.md | 24 +- src/Controller/AdminController.php | 11 +- src/Controller/SlidesController.php | 6 + src/Model/Entity/Slide.php | 70 ++++- src/Model/Table/SlidesTable.php | 11 +- src/Service/PollStateService.php | 6 +- src/Service/ResultsService.php | 42 +++ src/Service/VoteService.php | 2 + templates/Admin/index.php | 6 + templates/Admin/present.php | 1 + templates/Participate/view.php | 9 + templates/Slides/form.php | 2 + templates/element/slide_time_limit.php | 32 +++ .../Controller/AdminControllerTest.php | 2 +- tests/TestCase/Controller/TimedSlideTest.php | 241 ++++++++++++++++++ tests/TestCase/Service/VoteServiceTest.php | 4 +- webroot/css/plenario.css | 2 + webroot/js/plenario.js | 37 ++- 19 files changed, 480 insertions(+), 34 deletions(-) create mode 100644 templates/element/slide_time_limit.php create mode 100644 tests/TestCase/Controller/TimedSlideTest.php diff --git a/AGENTS.md b/AGENTS.md index 995e172..f355a82 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -104,7 +104,11 @@ Vollständige Struktur und Datenmodell: [docs/architecture.md](docs/architecture Q&A nutzt eigenes `qa`. Es gibt keinen Schalter dafür pro Umfrage. - **Quiz:** Zählungen und `is_correct` dürfen vor `finished` nie im JSON/HTML landen (weder Presenter noch Teilnehmende); „offen“ heißt immer `Slide::isVotingOpen()`, nicht nur `is_voting_open`. Details: [docs/slide-types.md](docs/slide-types.md). -- **Reihenfolge:** richtige Reihenfolge und Zählungen erst nach dem Schließen der Abstimmung im JSON. +- **Reihenfolge:** richtige Reihenfolge und Zählungen erst nach dem Schließen der Abstimmung im JSON, nie vor dem Start eines Countdowns + (`Slide::isOrderRevealed()` ist in der Phase `ready` falsch). +- **Countdown:** jede Folie mit Antworten außer Q&A kann ein Zeitlimit haben (`time_limit`, 0 = keins). Mit Countdown startet sie geschlossen + (`ready`), zeigt nur die Frage, „Weiter“ startet/beendet ihn wie beim Quiz. Auf die Bühne gehen Ergebnisse dafür nur über + `ResultsService::forStage()`. Details: [docs/slide-types.md](docs/slide-types.md). - **Pause/Live-Folie:** `current_slide_id`/`paused_slide_id` nur über `Poll::showSlide()` / `showEmbeddedSlide()` / `pause()` / `forgetSlide()` setzen, nie direkt. Details: [docs/presenter.md](docs/presenter.md). - `Poll`/`Response` haben `_hidden` für sensible Felder; mass assignment über `_accessible` restriktiv halten. diff --git a/docs/slide-types.md b/docs/slide-types.md index f52572d..e2c47bc 100644 --- a/docs/slide-types.md +++ b/docs/slide-types.md @@ -29,17 +29,37 @@ geändert wird es nur über die Presenter-Steuerung (`SlideControlService`) bzw. JSON/HTML landen** (weder Presenter noch Teilnehmende); danach sehen Teilnehmende die Lösung und ob sie richtig lagen (ohne Verteilung). Zurücksetzen setzt das Quiz wieder auf `ready`. - **Quiz-Musik:** je **Präsentation** (nicht je Folie) eine Audiodatei (`polls.audio`), hochgeladen im Menü unter „Einstellungen → - Musik zum Quiz-Countdown“ (`Admin::audio`, Route `admin:audio`; Entfernen = Feld `remove`; Dropzone wie bei Folienbildern, nur kompakter: `initAudioForm()` sendet die Datei sofort nach Auswahl/Drop, ohne JavaScript der Button „Hochladen“). Gespeichert wird die Datei unverändert + Musik zum Quiz-Countdown“ (gilt für alle Countdowns) (`Admin::audio`, Route `admin:audio`; Entfernen = Feld `remove`; Dropzone wie bei Folienbildern, nur kompakter: `initAudioForm()` sendet die Datei sofort nach Auswahl/Drop, ohne JavaScript der Button „Hochladen“). Gespeichert wird die Datei unverändert (`AudioService`: Format nur an den ersten Bytes erkannt – MP3, M4A, OGG, WAV –, Zufallsname mit fester Endung, Obergrenze `Plenario.audio.maxUploadBytes`) im Upload-Verzeichnis der Umfrage, ausgeliefert über `participate:audio` (`/p/{code}/audio/{file}`, nur die Datei dieser Umfrage, feste Content-Type, Range-Anfragen). Im State steht `poll.audioUrl`. Abgespielt wird nur in der - Referentenansicht/Einbettung (`StageAudio` in `plenario.js`): als Schleife, solange irgendein Quiz `running` ist, Stopp bei + Referentenansicht/Einbettung (`StageAudio` in `plenario.js`): als Schleife, solange irgendeine Folie mit Countdown (Quiz oder Zeitlimit) `running` ist, Stopp bei Ende/Folienwechsel/Pause. Teilnehmende hören nichts. Blockiert der Browser den Start (keine Nutzeraktion), wird er beim nächsten Klick/Tastendruck wiederholt. „Umfrage kopieren“ kopiert die Datei, Löschen der Umfrage und `images_cleanup` räumen sie mit auf. **Klicker/Presenter-Stick** (sendet nur →/← bzw. Bild↑/↓): `AdminController::control` behandelt `next` auf einem Quiz als Schritt – `ready` → starten, `running` → beenden (Lösung), erst `finished` → nächste Folie. `prev` geht immer zur vorigen Folie und startet nie ein Quiz. Tests: `QuizClickerTest.php`. +## Countdown für alle Folien mit Antworten + +- Jede Folie, auf der geantwortet wird, außer Q&A (`Slide::supportsTimer()`: Auswahl, Wortwolke, offene Frage, Skala, Reihenfolge, Quiz), + hat die Einstellung `time_limit` (Sekunden, `Slide::TIME_LIMITS`, **0 = kein Countdown**, Standard bei allen außer dem Quiz). + Formularfeld: `element/slide_time_limit`; das Quiz behält sein eigenes Feld (dort heißt 0 „ich beende selbst“). +- Mit Countdown (`Slide::usesPhases()`, beim Quiz immer) durchläuft die Folie dieselben **Phasen wie das Quiz**: `ready` → `running` → + `finished` (`Slide::phase()`, `null` ohne Countdown). `startFresh()` lässt sie geschlossen starten (`ready`), `setVotingOpen(true)` + startet das Zeitfenster (Start + Deadline), `SlidesTable::closeIfExpired()` schließt nach Ablauf. Nach dem Speichern im Formular wird eine + noch nicht gezeigte Folie neu initialisiert (`startFresh()`), damit eine geänderte Zeit sofort wirkt. +- Ablauf im Presenter (`AdminController::control()`): „Weiter“ startet den Countdown (`ready` → `running`), das nächste „Weiter“ beendet + ihn vorzeitig, erst das dritte geht zur nächsten Folie (wie beim Quiz; „Zurück“ rührt ihn nie an). **V** schaltet ebenso (erneutes + Öffnen startet den Countdown neu). Ohne Countdown wechselt das erste „Weiter“ direkt zur nächsten Folie. +- **`ready` zeigt nur die Frage:** `ResultsService::forStage()` (Presenter/Einbettung) liefert dann nur `{ready: true, timer}`, nie + Antworten, Zählungen oder Lösung; die Auswertung/PDF nutzt weiter `forSlide()` (ungegatet). `Slide::isOrderRevealed()` ist in `ready` + falsch, sonst würde die Reihenfolge-Lösung vor dem Start verraten. Teilnehmende sehen „Die Abstimmung startet gleich“ und können nicht + abstimmen (`VoteService`: „… noch nicht begonnen“). Private Folien zeigen wie sonst nur die Anzahl. +- State: `results.timer` = `{phase, timeLimit, remaining}` (Presenter/Einbettung, auch beim Quiz), `timer` im Teilnehmer-State (nicht beim + Quiz, der hat `quiz`). Die Bühne zeigt den Countdown unter der Frage (`[data-stage-timer]`, beim Quiz im Ergebnis); die Musik + (`poll.audioUrl`) läuft bei jeder laufenden Phase. Tests: `TimedSlideTest.php`, `QuizClickerTest.php`. + ## Fragen & Antworten (Q&A) - Q&A-Folie (`qa`, „Fragen & Antworten“): Phasen `collect` → `vote` → `discuss` (`Slide::qaStage()`, `QaService`), diff --git a/src/Controller/AdminController.php b/src/Controller/AdminController.php index 8bd0d92..67889dd 100644 --- a/src/Controller/AdminController.php +++ b/src/Controller/AdminController.php @@ -323,7 +323,7 @@ class AdminController extends AdminAppController * SlideControlService (open, close, toggle, stage, question). * * On a Q&A slide that is being discussed, next/prev step through the questions - * first (like builds in presentation software); on a quiz, next starts it and then ends it + * first (like builds in presentation software); on a slide with a countdown (quiz, or any slide with a time limit), next starts it and then ends it * before moving on, on an open ordering slide next closes it (reveals the solution), * prev always goes to the previous slide. While paused, next/prev resume * the slide that was live before. @@ -349,9 +349,10 @@ class AdminController extends AdminAppController ) { $action = 'none'; } - // Forward on a quiz is a build step too: start it, then end it, only then the next slide. - // Back never touches the quiz, so a clicker can page through the slides afterwards. - if ($current !== null && $current->isQuiz() && $action === 'next') { + // Forward on a slide with a countdown (every quiz, any other slide with a time limit) is a build step too: + // start it, then end it, only then the next slide. + // Back never touches it, so a clicker can page through the slides afterwards. + if ($current !== null && $current->usesPhases() && $action === 'next') { $phase = $current->quizPhase(); if ($phase !== Slide::QUIZ_FINISHED) { (new SlideControlService())->apply($current, $phase === Slide::QUIZ_READY ? 'open' : 'close'); @@ -359,7 +360,7 @@ class AdminController extends AdminAppController } } - // Same for an ordering slide: forward first closes the voting (reveals the solution). + // An ordering slide without countdown: forward first closes the voting (reveals the solution). if ($current !== null && $current->isOrder() && $action === 'next' && $current->isVotingOpen()) { (new SlideControlService())->apply($current, 'close'); $action = 'none'; diff --git a/src/Controller/SlidesController.php b/src/Controller/SlidesController.php index 381615c..02519bc 100644 --- a/src/Controller/SlidesController.php +++ b/src/Controller/SlidesController.php @@ -302,7 +302,13 @@ class SlidesController extends AdminAppController // is_voting_open is presenter state (SlideControlService), never editable via the form. $fields = ['type', 'question', 'description', 'settings']; $youtube = $slide->isYouTube() ? $this->prepareYouTube($data) : ['errors' => [], 'warning' => null]; + // A slide that has not been presented yet starts again after the (possibly changed) time limit is known: + // with a countdown it waits for the presenter, without it is open. + $fresh = $slide->isNew() || $slide->isFresh(); $this->Slides->patchEntity($slide, $data, ['fields' => $fields, 'associated' => []]); + if ($fresh) { + $slide->startFresh(); + } foreach ($youtube['errors'] as $field => $message) { $slide->setError($field, $message); } diff --git a/src/Model/Entity/Slide.php b/src/Model/Entity/Slide.php index 5cc90ce..f766eb2 100644 --- a/src/Model/Entity/Slide.php +++ b/src/Model/Entity/Slide.php @@ -61,6 +61,13 @@ class Slide extends Entity */ public const QUIZ_TIME_LIMITS = [0, 10, 15, 20, 30, 45, 60, 90, 120, 180, 300]; + /** + * Selectable time limits of every slide with a countdown (same list as for quizzes). + * + * @var list + */ + public const TIME_LIMITS = self::QUIZ_TIME_LIMITS; + /** * Display styles of a scale: numbered steps or a star rating (always starts at 1 star). */ @@ -108,11 +115,11 @@ class Slide extends Entity public const DEFAULT_SETTINGS = [ // comments: optional comment field (stored in text_value of the participant's first row), // comments rotate in the presentation like those of a scale - self::TYPE_CHOICE => ['multiple' => false, 'comments' => false], + self::TYPE_CHOICE => ['multiple' => false, 'comments' => false, 'time_limit' => 0], // allow_downvotes only takes effect together with allow_upvotes - self::TYPE_WORDCLOUD => ['allow_upvotes' => true, 'allow_downvotes' => true], + self::TYPE_WORDCLOUD => ['allow_upvotes' => true, 'allow_downvotes' => true, 'time_limit' => 0], // private: anonymous feedback, answers only visible in the admin area (never on the stage) - self::TYPE_OPEN => ['private' => false], + self::TYPE_OPEN => ['private' => false, 'time_limit' => 0], // private: internal feedback, ratings only visible in the admin area (never on the stage) // comments: optional comment field, comments rotate in the presentation (unless private) // comment_ratings: show the rating next to each comment in the presentation @@ -125,6 +132,7 @@ class Slide extends Entity 'scale_min' => 1, 'scale_max' => 5, 'min_label' => '', 'max_label' => '', 'private' => false, 'comments' => false, 'comment_ratings' => false, 'scale_view' => self::SCALE_VIEW_BOTH, + 'time_limit' => 0, ], self::TYPE_CONTENT => [], // time_limit in seconds, 0 = no limit (presenter ends the quiz) @@ -136,10 +144,12 @@ class Slide extends Entity // max_upvotes_per_question: own upvotes per question (0 = no limit besides the budget); // allow_self_upvote: upvotes on own questions (for prioritizing topics, off by default) self::TYPE_QA => ['upvote_share' => 25, 'max_upvotes_per_question' => 0, 'allow_self_upvote' => false], + // time_limit (all slides with answers but Q&A): seconds, 0 = no countdown. With a countdown the slide waits + // ("ready") until the presenter starts it, like a quiz (see usesPhases()). // The correct order is the order of the slide_options (position), revealed when voting closes. // ranking: no correct order, everyone sorts by personal preference; the presenter sees the // average ranking live (nothing to hide), participants never get results - self::TYPE_ORDER => ['ranking' => false], + self::TYPE_ORDER => ['ranking' => false, 'time_limit' => 0], ]; /** @@ -173,6 +183,20 @@ class Slide extends Entity return $type !== self::TYPE_YOUTUBE; } + /** + * Whether slides of this type can have a countdown: every type that collects answers except Q&A (its three + * stages take as long as the discussion needs). A quiz always has the ready/running/finished phases. + * + * @param string $type Slide type + * @return bool + */ + public static function supportsTimer(string $type): bool + { + return in_array($type, [ + self::TYPE_CHOICE, self::TYPE_WORDCLOUD, self::TYPE_OPEN, self::TYPE_SCALE, self::TYPE_QUIZ, self::TYPE_ORDER, + ], true); + } + /** * @return bool */ @@ -344,7 +368,8 @@ class Slide extends Entity */ public function isOrderRevealed(): bool { - return $this->isOrder() && !$this->isRanking() && !$this->isVotingOpen(); + // Not yet started (phase "ready") is closed too, but nothing may be resolved before the countdown ran. + return $this->isOrder() && !$this->isRanking() && !$this->isVotingOpen() && $this->phase() !== self::QUIZ_READY; } /** @@ -461,6 +486,28 @@ class Slide extends Entity return in_array($this->type, [self::TYPE_WORDCLOUD, self::TYPE_QA], true); } + /** + * Whether the slide goes through the phases ready (shows only the question), running (countdown, answers + * accepted) and finished: every quiz, and any other slide with a time limit. + * + * @return bool + */ + public function usesPhases(): bool + { + return $this->isQuiz() || (self::supportsTimer($this->type) && (int)$this->setting('time_limit') > 0); + } + + /** + * Phase of a slide with a countdown (one of the QUIZ_* constants), null for slides without. + * + * @param \Cake\I18n\DateTime|null $now Reference time (default: now) + * @return string|null + */ + public function phase(?DateTime $now = null): ?string + { + return $this->usesPhases() ? $this->quizPhase($now) : null; + } + /** * Phase of a quiz: ready (not started yet), running, finished (time up or * closed by the presenter). Results and correct answers are only revealed @@ -498,13 +545,14 @@ class Slide extends Entity /** * Sets the state of a slide that has not been presented yet (new slide, copy): - * a quiz waits for the presenter to start it, Q&A collects questions, others are open. + * a quiz or a slide with a countdown waits for the presenter to start it, Q&A collects questions, + * others are open. * * @return void */ public function startFresh(): void { - $this->is_voting_open = !$this->isQuiz(); + $this->is_voting_open = !$this->usesPhases(); $this->voting_started_at = null; $this->voting_ends_at = null; $this->stage = $this->isQa() ? self::QA_COLLECT : null; @@ -519,7 +567,7 @@ class Slide extends Entity */ public function isFresh(): bool { - return $this->is_voting_open === !$this->isQuiz() + return $this->is_voting_open === !$this->usesPhases() && $this->voting_started_at === null && $this->voting_ends_at === null && $this->stage === ($this->isQa() ? self::QA_COLLECT : null) @@ -527,8 +575,8 @@ class Slide extends Entity } /** - * Opens or closes voting. Opening a quiz that is not running (re)starts its - * voting window and timer; opening a running quiz changes nothing. + * Opens or closes voting. Opening a slide with a countdown that is not running (re)starts its + * voting window and timer; opening a running one changes nothing. * * @param bool $open Open or close * @param \Cake\I18n\DateTime|null $now Reference time (default: now) @@ -537,7 +585,7 @@ class Slide extends Entity public function setVotingOpen(bool $open, ?DateTime $now = null): void { $now ??= DateTime::now(); - if ($open && $this->isQuiz() && !$this->isVotingOpen($now)) { + if ($open && $this->usesPhases() && !$this->isVotingOpen($now)) { $limit = (int)$this->setting('time_limit'); $this->voting_started_at = $now; $this->voting_ends_at = $limit > 0 ? $now->addSeconds($limit) : null; diff --git a/src/Model/Table/SlidesTable.php b/src/Model/Table/SlidesTable.php index da8c205..c45bc25 100644 --- a/src/Model/Table/SlidesTable.php +++ b/src/Model/Table/SlidesTable.php @@ -184,10 +184,7 @@ class SlidesTable extends Table $settings['ranking'] = filter_var($input['ranking'] ?? false, FILTER_VALIDATE_BOOLEAN); 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; - } + // The time limit is validated for every slide with a countdown below. break; case Slide::TYPE_QA: $share = (int)($input['upvote_share'] ?? $settings['upvote_share']); @@ -214,6 +211,12 @@ class SlidesTable extends Table $settings['autoplay'] = filter_var($input['autoplay'] ?? false, FILTER_VALIDATE_BOOLEAN); break; } + if (Slide::supportsTimer($type)) { + $limit = (int)($input['time_limit'] ?? $settings['time_limit']); + $settings['time_limit'] = in_array($limit, Slide::TIME_LIMITS, true) + ? $limit + : Slide::DEFAULT_SETTINGS[$type]['time_limit']; + } return $settings; } diff --git a/src/Service/PollStateService.php b/src/Service/PollStateService.php index 83a7598..1a7bb79 100644 --- a/src/Service/PollStateService.php +++ b/src/Service/PollStateService.php @@ -134,7 +134,7 @@ class PollStateService 'next' => $this->nextPreview($poll, $slides, $index), 'hiddenCount' => $this->Slides->find()->where(['poll_id' => $poll->id, 'is_hidden' => true])->count(), 'slide' => $current ? $this->slidePayload($current, $poll) : null, - 'results' => $current ? $this->results->forSlide($current) : null, + 'results' => $current ? $this->results->forStage($current) : null, ]; } @@ -196,7 +196,7 @@ class PollStateService 'index' => null, 'count' => null, 'slide' => $this->slidePayload($slide, $poll), - 'results' => $this->results->forSlide($slide), + 'results' => $this->results->forStage($slide), ]; } @@ -250,6 +250,8 @@ class PollStateService ]), 'slide' => $showResults ? $this->slidePayload($slide, $poll) : null, 'results' => $showResults ? $this->participantResults($slide) : null, + // Countdown of a slide that is not a quiz (a quiz has its own state below) + 'timer' => $slide !== null && !$slide->isQuiz() && $slide->usesPhases() ? $this->results->timer($slide) : null, 'words' => $words, 'quiz' => $quiz, 'qa' => $qa, diff --git a/src/Service/ResultsService.php b/src/Service/ResultsService.php index 81a0b10..1737182 100644 --- a/src/Service/ResultsService.php +++ b/src/Service/ResultsService.php @@ -78,6 +78,9 @@ class ResultsService 'type' => $slide->type, 'participants' => $slide->isInteractive() ? $this->Responses->countParticipants($slide->id) : 0, ]; + if ($slide->usesPhases()) { + $result['timer'] = $this->timer($slide); + } return $result + match ($slide->type) { Slide::TYPE_CHOICE => $this->choice($slide, $limit), @@ -91,6 +94,45 @@ class ResultsService }; } + /** + * Results for the stage (presenter view and embed). A slide with a countdown that has not been started yet + * shows only its question: no answers, no counts, no solution (`ready`), whatever is stored for it. + * The evaluation (admin, PDF) uses forSlide(), which is never gated. + * + * @param \App\Model\Entity\Slide $slide Slide + * @return array + */ + public function forStage(Slide $slide): array + { + if ($slide->phase() === Slide::QUIZ_READY && !$slide->isQuiz()) { + return [ + 'type' => $slide->type, + 'participants' => 0, + 'ready' => true, + 'timer' => $this->timer($slide), + ]; + } + + return $this->forSlide($slide); + } + + /** + * Countdown of a slide: phase (ready|running|finished), the limit and the seconds left while running. + * + * @param \App\Model\Entity\Slide $slide Slide with a countdown + * @return array{phase: string|null, timeLimit: int, remaining: int|null} + */ + public function timer(Slide $slide): array + { + $phase = $slide->phase(); + + return [ + 'phase' => $phase, + 'timeLimit' => (int)$slide->setting('time_limit'), + 'remaining' => $phase === Slide::QUIZ_RUNNING ? $slide->remainingSeconds() : null, + ]; + } + /** * @param \App\Model\Entity\Slide $slide Slide * @return array diff --git a/src/Service/VoteService.php b/src/Service/VoteService.php index 07831e0..332fdb6 100644 --- a/src/Service/VoteService.php +++ b/src/Service/VoteService.php @@ -226,6 +226,8 @@ 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->usesPhases() && $slide->voting_started_at === null => __('Die Abstimmung hat noch nicht begonnen.'), + $slide->usesPhases() => __('Die Zeit für diese Frage ist abgelaufen.'), $slide->isQa() => __('Die Fragerunde läuft – Fragen und Stimmen sind nicht mehr möglich.'), default => __('Die Abstimmung zu dieser Frage ist geschlossen.'), }); diff --git a/templates/Admin/index.php b/templates/Admin/index.php index f986b60..e5a6b70 100644 --- a/templates/Admin/index.php +++ b/templates/Admin/index.php @@ -119,6 +119,12 @@ $hasInternal = array_filter($slides, fn($slide) => !$slide->is_hidden && $slide- 'running' => __('Quiz läuft'), 'finished' => __('Quiz beendet'), ][$slide->quizPhase()]) ?> + usesPhases()) : ?> + · ⏱ setting('time_limit')) ?> · __('noch nicht gestartet'), + 'running' => __('Countdown läuft'), + 'finished' => __('beendet'), + ][$slide->phase()]) ?> isQa()) : ?> · __('Fragen sammeln'), diff --git a/templates/Admin/present.php b/templates/Admin/present.php index 53dbf02..09e7568 100644 --- a/templates/Admin/present.php +++ b/templates/Admin/present.php @@ -43,6 +43,7 @@ $host = preg_replace('#^https?://#', '', $joinBaseUrl);

+
diff --git a/templates/Participate/view.php b/templates/Participate/view.php index 339949a..8aa0778 100644 --- a/templates/Participate/view.php +++ b/templates/Participate/view.php @@ -18,6 +18,7 @@ $this->assign('bodyClass', 'participant'); $voteUrl = ['_name' => 'participate:vote', 'code' => $poll->join_code]; $words = $state['words'] ?? null; $quiz = $state['quiz'] ?? null; +$timer = $state['timer'] ?? null; $qa = $state['qa'] ?? null; $order = $state['order'] ?? null; $countdown = function (?int $remaining): string { @@ -100,6 +101,13 @@ $countdown = function (?int $remaining): string { element('slide_image', compact('slide', 'poll')) ?> + +
+ +

+
+ +
@@ -336,6 +344,7 @@ $countdown = function (?int $remaining): string { Form->button(__('Absenden'), ['class' => 'button button--primary button--block']) ?> Form->end() ?> +
> diff --git a/templates/Slides/form.php b/templates/Slides/form.php index d2f0a04..ef69db1 100644 --- a/templates/Slides/form.php +++ b/templates/Slides/form.php @@ -354,6 +354,8 @@ $optionsError = $slide->getError('options_text');

+ element('slide_time_limit', ['slide' => $slide]) ?> +
Form->button($isNew ? __('Folie anlegen') : __('Speichern'), ['class' => 'button button--primary']) ?> diff --git a/templates/element/slide_time_limit.php b/templates/element/slide_time_limit.php new file mode 100644 index 0000000..bfae21e --- /dev/null +++ b/templates/element/slide_time_limit.php @@ -0,0 +1,32 @@ +isQuiz() || !Slide::supportsTimer($slide->type)) { + return; +} +$limits = []; +foreach (Slide::TIME_LIMITS as $seconds) { + $limits[$seconds] = match (true) { + $seconds === 0 => __('Kein Countdown'), + $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' => __('Countdown'), + 'value' => $slide->getSettings()['time_limit'], + 'aria-describedby' => 'time-limit-hint', +]) ?> +

diff --git a/tests/TestCase/Controller/AdminControllerTest.php b/tests/TestCase/Controller/AdminControllerTest.php index c7a4e38..10af497 100644 --- a/tests/TestCase/Controller/AdminControllerTest.php +++ b/tests/TestCase/Controller/AdminControllerTest.php @@ -107,7 +107,7 @@ class AdminControllerTest extends TestCase $slide = $this->slidesTable()->find()->contain(['SlideOptions'])->firstOrFail(); $this->assertSame($poll->id, $slide->poll_id); $this->assertSame(['Pizza', 'Pasta'], array_map(fn($o) => $o->label, $slide->slide_options)); - $this->assertSame(['multiple' => true, 'comments' => false], $slide->settings); + $this->assertSame(['multiple' => true, 'comments' => false, 'time_limit' => 0], $slide->settings); $this->assertSame(1, $slide->position); } diff --git a/tests/TestCase/Controller/TimedSlideTest.php b/tests/TestCase/Controller/TimedSlideTest.php new file mode 100644 index 0000000..696ed32 --- /dev/null +++ b/tests/TestCase/Controller/TimedSlideTest.php @@ -0,0 +1,241 @@ + + */ + protected array $fixtures = ['app.Polls', 'app.Slides', 'app.SlideOptions', 'app.Responses']; + + protected function setUp(): void + { + parent::setUp(); + $this->enableCsrfToken(); + } + + /** + * @return array + */ + protected function control(string $token, string $action): array + { + $this->configRequest(['headers' => ['Accept' => 'application/json']]); + $this->post("/admin/$token/control", ['action' => $action]); + $this->assertResponseOk(); + + return json_decode((string)$this->_response->getBody(), true); + } + + /** + * A fresh slide of the given type with a time limit (waits for the presenter). + */ + protected function createTimed(Poll $poll, string $type = Slide::TYPE_CHOICE, int $limit = 30): Slide + { + $slide = $this->createSlide($poll, $type, ['settings' => ['time_limit' => $limit] + Slide::DEFAULT_SETTINGS[$type]]); + $slide->startFresh(); + + return $this->slidesTable()->saveOrFail($slide); + } + + public function testSlideWithoutLimitStaysOpenAndHasNoPhases(): void + { + [$poll] = $this->createPoll(); + $slide = $this->createSlide($poll); + $slide->startFresh(); + + $this->assertFalse($slide->usesPhases()); + $this->assertNull($slide->phase()); + $this->assertTrue($slide->isVotingOpen()); + $this->assertTrue($slide->isFresh()); + } + + public function testTimedSlideWaitsUntilStartedAndShowsNoResults(): void + { + [$poll] = $this->createPoll(); + $slide = $this->createTimed($poll); + $poll = $this->goLive($poll, $slide); + + $this->assertTrue($slide->usesPhases()); + $this->assertSame(Slide::QUIZ_READY, $slide->phase()); + $this->assertFalse($slide->isVotingOpen()); + $this->assertTrue($slide->isFresh()); + + // Presenter: only the question, no answers, no counts. + $state = (new PollStateService())->forPresenter($poll); + $this->assertTrue($state['results']['ready']); + $this->assertSame(0, $state['results']['participants']); + $this->assertArrayNotHasKey('options', $state['results']); + $this->assertSame(Slide::QUIZ_READY, $state['results']['timer']['phase']); + + // Participants know about the timer, can not vote yet. + $participant = (new PollStateService())->forParticipant($poll, str_repeat('a', 32)); + $this->assertSame(Slide::QUIZ_READY, $participant['timer']['phase']); + $this->assertFalse($participant['isVotingOpen']); + $this->post('/p/' . $poll->join_code . '/vote', ['slide_id' => $slide->id, 'option_id' => $slide->slide_options[0]->id]); + $this->assertRedirect(); + $this->assertFlashMessage('Die Abstimmung hat noch nicht begonnen.'); + $this->get('/p/' . $poll->join_code); + $this->assertResponseContains('Die Abstimmung startet gleich'); + $this->assertResponseNotContains('name="option_id"'); + } + + public function testOrderSolutionDoesNotLeakBeforeTheCountdownStarts(): void + { + [$poll] = $this->createPoll(); + $slide = $this->createTimed($poll, Slide::TYPE_ORDER); + $poll = $this->goLive($poll, $slide); + + $this->assertFalse($slide->isOrderRevealed()); + $state = (new PollStateService())->forPresenter($poll); + $this->assertTrue($state['results']['ready']); + $this->assertArrayNotHasKey('items', $state['results']); + $participant = (new PollStateService())->forParticipant($poll, str_repeat('b', 32)); + $this->assertFalse($participant['order']['revealed']); + $this->assertNull($participant['results']); + } + + public function testNextStartsEndsAndMovesOn(): void + { + [$poll, $token] = $this->createPoll(); + $slide = $this->createTimed($poll); + $after = $this->createSlide($poll, Slide::TYPE_CONTENT); + $this->goLive($poll, $slide); + + // 1st: start the countdown, the slide stays. + $state = $this->control($token, 'next'); + $this->assertSame($slide->id, $state['slide']['id']); + $running = $this->slidesTable()->get($slide->id); + $this->assertSame(Slide::QUIZ_RUNNING, $running->phase()); + $this->assertNotNull($running->voting_ends_at); + $this->assertSame(Slide::QUIZ_RUNNING, $state['results']['timer']['phase']); + $this->assertGreaterThan(0, $state['results']['timer']['remaining']); + $this->assertArrayNotHasKey('ready', $state['results']); + + // 2nd: end it, results stay on stage. + $state = $this->control($token, 'next'); + $this->assertSame($slide->id, $state['slide']['id']); + $this->assertSame(Slide::QUIZ_FINISHED, $this->slidesTable()->get($slide->id)->phase()); + + // 3rd: next slide. Back goes straight back without restarting. + $state = $this->control($token, 'next'); + $this->assertSame($after->id, $state['slide']['id']); + $state = $this->control($token, 'prev'); + $this->assertSame($slide->id, $state['slide']['id']); + $this->assertSame(Slide::QUIZ_FINISHED, $this->slidesTable()->get($slide->id)->phase()); + } + + public function testSlideWithoutLimitMovesOnWithTheFirstNext(): void + { + [$poll, $token] = $this->createPoll(); + $slide = $this->createSlide($poll); + $after = $this->createSlide($poll, Slide::TYPE_CONTENT); + $this->goLive($poll, $slide); + + $state = $this->control($token, 'next'); + $this->assertSame($after->id, $state['slide']['id']); + } + + public function testRestartingTheCountdownWithTheToggle(): void + { + [$poll, $token] = $this->createPoll(); + $slide = $this->createTimed($poll, Slide::TYPE_WORDCLOUD, 10); + $this->goLive($poll, $slide); + + $this->control($token, 'toggle'); + $this->assertSame(Slide::QUIZ_RUNNING, $this->slidesTable()->get($slide->id)->phase()); + $this->control($token, 'toggle'); + $this->assertSame(Slide::QUIZ_FINISHED, $this->slidesTable()->get($slide->id)->phase()); + $this->control($token, 'toggle'); + $reopened = $this->slidesTable()->get($slide->id); + $this->assertSame(Slide::QUIZ_RUNNING, $reopened->phase()); + $this->assertLessThanOrEqual(10, $reopened->remainingSeconds()); + } + + public function testRunningVotingResultsAreShownLive(): void + { + [$poll, $token] = $this->createPoll(); + $slide = $this->createTimed($poll); + $poll = $this->goLive($poll, $slide); + $this->control($token, 'next'); + + $this->cookie('plenario_pid', str_repeat('c', 32)); + $this->post('/p/' . $poll->join_code . '/vote', ['slide_id' => $slide->id, 'option_id' => $slide->slide_options[0]->id]); + $this->assertRedirect(); + + $state = (new PollStateService())->forPresenter($this->pollsTable()->get($poll->id)); + $this->assertArrayNotHasKey('ready', $state['results']); + $this->assertSame(1, $state['results']['participants']); + $this->assertSame(1, $state['results']['options'][0]['count']); + } + + public function testExpiredCountdownClosesTheSlide(): void + { + [$poll] = $this->createPoll(); + $slide = $this->createTimed($poll); + $slide->setVotingOpen(true); + $slide->voting_ends_at = $slide->voting_started_at->subSeconds(1); + $this->slidesTable()->saveOrFail($slide); + $poll = $this->goLive($poll, $slide); + + $state = (new PollStateService())->forPresenter($poll); + $this->assertSame(Slide::QUIZ_FINISHED, $state['results']['timer']['phase']); + $this->assertFalse($state['slide']['isVotingOpen']); + } + + public function testFormSavesTheLimitAndStartsTheNewSlideReady(): void + { + [$poll, $token] = $this->createPoll(); + $this->post("/admin/$token/slides/add?type=choice", [ + 'type' => 'choice', 'question' => 'Mit Zeit?', 'options_text' => "Ja\nNein", 'settings' => ['time_limit' => '45'], + ]); + $this->assertRedirect(['_name' => 'admin', 'token' => $token]); + $slide = $this->slidesTable()->find()->where(['poll_id' => $poll->id])->firstOrFail(); + $this->assertSame(45, $slide->setting('time_limit')); + $this->assertSame(Slide::QUIZ_READY, $slide->phase()); + + // Removing the countdown from a slide nobody started opens it again. + $this->post("/admin/$token/slides/{$slide->id}/edit", [ + 'type' => 'choice', 'question' => 'Mit Zeit?', 'options_text' => "Ja\nNein", 'settings' => ['time_limit' => '0'], + ]); + $slide = $this->slidesTable()->get($slide->id); + $this->assertNull($slide->phase()); + $this->assertTrue($slide->isVotingOpen()); + + // An invalid limit falls back to "none". + $this->post("/admin/$token/slides/{$slide->id}/edit", [ + 'type' => 'choice', 'question' => 'Mit Zeit?', 'options_text' => "Ja\nNein", 'settings' => ['time_limit' => '7'], + ]); + $this->assertSame(0, $this->slidesTable()->get($slide->id)->setting('time_limit')); + + // Q&A has no countdown. + $this->assertFalse(Slide::supportsTimer(Slide::TYPE_QA)); + $this->assertArrayNotHasKey('time_limit', Slide::DEFAULT_SETTINGS[Slide::TYPE_QA]); + } + + public function testEvaluationIsNotGatedByTheCountdown(): void + { + [$poll] = $this->createPoll(); + $slide = $this->createTimed($poll); + + $results = (new ResultsService())->forSlide($slide); + $this->assertArrayNotHasKey('ready', $results); + $this->assertSame(Slide::QUIZ_READY, $results['timer']['phase']); + } +} diff --git a/tests/TestCase/Service/VoteServiceTest.php b/tests/TestCase/Service/VoteServiceTest.php index 347e4a4..dfea7b8 100644 --- a/tests/TestCase/Service/VoteServiceTest.php +++ b/tests/TestCase/Service/VoteServiceTest.php @@ -143,9 +143,9 @@ class VoteServiceTest extends TestCase public function testWordcloudSettingsSanitizing(): void { $settings = SlidesTable::sanitizeSettings(Slide::TYPE_WORDCLOUD, ['max_words' => '3', 'allow_upvotes' => '0']); - $this->assertSame(['allow_upvotes' => false, 'allow_downvotes' => true], $settings); + $this->assertSame(['allow_upvotes' => false, 'allow_downvotes' => true, 'time_limit' => 0], $settings); $settings = SlidesTable::sanitizeSettings(Slide::TYPE_WORDCLOUD, ['allow_downvotes' => '0']); - $this->assertSame(['allow_upvotes' => true, 'allow_downvotes' => false], $settings); + $this->assertSame(['allow_upvotes' => true, 'allow_downvotes' => false, 'time_limit' => 0], $settings); } public function testWordcloudDownvotes(): void diff --git a/webroot/css/plenario.css b/webroot/css/plenario.css index a77c8ab..b509921 100644 --- a/webroot/css/plenario.css +++ b/webroot/css/plenario.css @@ -794,6 +794,8 @@ body.present { .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__timer:empty { display: none; } +.stage__timer .quiz-timer { margin: .2em 0 0; } .stage .quiz-tile { font-size: clamp(1.2rem, 2.2vw, 2rem); } .stage .quiz-summary strong, .stage .bar--correct .bar__label { color: var(--stage-ok); } .stage .bar--correct .bar__fill { background: var(--stage-ok); } diff --git a/webroot/js/plenario.js b/webroot/js/plenario.js index ec4c565..39a5365 100644 --- a/webroot/js/plenario.js +++ b/webroot/js/plenario.js @@ -652,7 +652,8 @@ var active = document.activeElement; var focusKey = active && container.contains(active) ? active.getAttribute('data-comment-action') : null; container.innerHTML = ''; - if (!results) { + if (!results || results.ready) { + // A slide with a countdown that has not started shows only its question. return; } var renderer = Results[results.type]; @@ -1514,6 +1515,7 @@ ? 'Teilnehmende sehen gerade eine Pause-Seite. Drücke B oder → zum Fortsetzen.' : 'Drücke → um zu starten.'); q('[data-results]').innerHTML = ''; + q('[data-stage-timer]').textContent = ''; renderMedia(null); renderImage(null); root.classList.remove('stage--video'); @@ -1526,12 +1528,18 @@ var quizPhase = slide.type === 'quiz' && state.results ? state.results.phase : null; var qaStage = slide.type === 'qa' && state.results ? state.results.stage : null; var orderRevealed = slide.type === 'order' && state.results ? state.results.revealed : null; - var closed = slide.isInteractive && !slide.isVotingOpen && !quizPhase && !qaStage && !orderRevealed; + // Countdown of any slide that has one (a quiz shows its timer inside its results). + var timer = state.results && state.results.timer ? state.results.timer : null; + var phase = timer ? timer.phase : null; + var timed = phase && !quizPhase ? phase : null; + var closed = slide.isInteractive && !slide.isVotingOpen && !quizPhase && !qaStage && !orderRevealed && timed !== 'ready'; // Status line above the question: only what the room needs to know, not the slide type. q('[data-status]').textContent = quizPhase ? { ready: 'Bereit', running: 'Läuft', finished: 'Auflösung' }[quizPhase] : (qaStage ? Qa.labels[qaStage] - : (orderRevealed ? 'Auflösung' : (closed ? 'Abstimmung geschlossen' : ''))); + : (orderRevealed ? 'Auflösung' + : (timed === 'ready' ? 'Bereit' : (timed === 'running' ? 'Läuft' : (closed ? 'Abstimmung geschlossen' : ''))))); + renderStageTimer(timed === 'running' && timer.remaining !== null ? timer.remaining : null); q('[data-question]').textContent = slide.question; Format.render(q('[data-description]'), slide.description); root.classList.toggle('stage--content', !slide.isInteractive); @@ -1548,12 +1556,14 @@ ? { ready: 'Quiz starten', running: 'Quiz beenden', finished: 'Quiz erneut öffnen' }[quizPhase] : (qaStage ? { collect: 'Einreichen beenden', vote: 'Abstimmung beenden', discuss: '' }[qaStage] - : (slide.type === 'order' + : (timed + ? { ready: 'Countdown starten', running: 'Abstimmung schließen', finished: 'Countdown erneut starten' }[timed] + : slide.type === 'order' ? (slide.isVotingOpen ? 'Schließen & auflösen' : 'Abstimmung wieder öffnen') : (slide.isVotingOpen ? 'Abstimmung schließen' : 'Abstimmung öffnen'))); var count = qaStage ? state.results.questions.length : (slide.isInteractive ? state.results.participants : 0); - setText('[data-participants]', !slide.isInteractive ? '' : (qaStage + setText('[data-participants]', !slide.isInteractive || timed === 'ready' ? '' : (qaStage ? count + (count === 1 ? ' Frage' : ' Fragen') : count + ' ' + (count === 1 ? 'Antwort' : 'Antworten'))); @@ -1564,7 +1574,22 @@ } renderResults(); Countdown.start(); - StageAudio.sync(quizPhase === 'running' ? state.poll.audioUrl : null); + StageAudio.sync(phase === 'running' ? state.poll.audioUrl : null); + } + + /** Big countdown below the question for slides that are not a quiz; null removes it. */ + function renderStageTimer(remaining) { + var box = q('[data-stage-timer]'); + box.textContent = ''; + if (remaining === null) { + return; + } + box.appendChild(el('p', { + class: 'quiz-timer', + role: 'timer', + 'data-countdown': '', + 'data-remaining': String(remaining) + }, [el('strong', { 'data-countdown-value': '', text: formatSeconds(remaining) })])); } function isPrivate() { -- 2.54.1