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

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

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

+ + +

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

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

+

- isInteractive() && !$slide->isQuiz()) : ?> + isInteractive() && !$slide->isQuiz() && !$slide->isQa()) : ?> Form->control('is_voting_open', [ 'type' => 'checkbox', 'label' => __('Abstimmung geöffnet'), diff --git a/tests/TestCase/Controller/QaSlideTest.php b/tests/TestCase/Controller/QaSlideTest.php new file mode 100644 index 0000000..5fcd6b6 --- /dev/null +++ b/tests/TestCase/Controller/QaSlideTest.php @@ -0,0 +1,166 @@ + + */ + protected array $fixtures = ['app.Polls', 'app.Slides', 'app.SlideOptions', 'app.Responses']; + + protected const PID = '0123456789abcdef0123456789abcdef'; + + protected function setUp(): void + { + parent::setUp(); + $this->enableCsrfToken(); + } + + /** + * @return array + */ + protected function control(string $token, array $data): array + { + $this->configRequest(['headers' => ['Accept' => 'application/json']]); + $this->post("/admin/$token/control", $data); + $this->assertResponseOk(); + + return json_decode((string)$this->_response->getBody(), true); + } + + /** + * @return array + */ + protected function participantPost(string $code, array $data): array + { + $this->cookie('plenario_pid', self::PID); + $this->configRequest(['headers' => ['Accept' => 'application/json', 'X-Requested-With' => 'XMLHttpRequest']]); + $this->post("/p/$code/vote", $data); + $this->assertResponseOk(); + + return json_decode((string)$this->_response->getBody(), true); + } + + public function testAddQaSlide(): void + { + [$poll, $token] = $this->createPoll(); + $this->get("/admin/$token/slides/add?type=qa"); + $this->assertResponseOk(); + $this->assertResponseContains('Upvotes (Stimmen) pro Person'); + $this->assertResponseNotContains('Abstimmung geöffnet'); + + $this->post("/admin/$token/slides/add?type=qa", [ + 'type' => 'qa', + 'question' => 'Eure Fragen an den Vorstand', + 'settings' => ['max_upvotes' => '5'], + ]); + $this->assertRedirect(); + $slide = $this->slidesTable()->find()->where(['poll_id' => $poll->id])->firstOrFail(); + $this->assertSame([Slide::TYPE_QA, 5, Slide::QA_COLLECT, true], [ + $slide->type, $slide->setting('max_upvotes'), $slide->stage, $slide->is_voting_open, + ]); + + $this->get("/admin/$token"); + $this->assertResponseContains('Fragen sammeln'); + $this->assertResponseContains('max. 5 Upvotes pro Person'); + } + + public function testFullRoundTrip(): void + { + [$poll, $token] = $this->createPoll(); + $slide = $this->createSlide($poll, Slide::TYPE_QA, ['settings' => ['max_upvotes' => 1]]); + $next = $this->createSlide($poll, Slide::TYPE_CONTENT); + $this->goLive($poll, $slide); + $code = $poll->join_code; + + $this->cookie('plenario_pid', self::PID); + $this->get("/p/$code"); + $this->assertResponseContains('Frage einreichen'); + + $answer = $this->participantPost($code, ['slide_id' => $slide->id, 'question' => 'Meine Frage']); + $this->assertTrue($answer['ok']); + $this->assertSame('Danke, deine Frage ist angekommen!', $answer['message']); + $this->assertSame(['Meine Frage'], array_column($answer['state']['qa']['questions'], 'text')); + + // Others ask too (directly via the service). + $hash = VoteService::participantHash('ffffffffffffffffffffffffffffffff', $poll->id); + (new VoteService())->submit($this->pollsTable()->get($poll->id), $this->slidesTable()->get($slide->id), $hash, ['question' => 'Andere Frage']); + + // V: collect → vote + $state = $this->control($token, ['action' => 'toggle']); + $this->assertSame('vote', $state['results']['stage']); + $this->assertTrue($state['slide']['isVotingOpen']); + + $this->cookie('plenario_pid', self::PID); + $this->get("/p/$code"); + $this->assertResponseContains('Du hast eine Stimme'); + + $other = $state['results']['questions'][1]['id']; + $answer = $this->participantPost($code, ['slide_id' => $slide->id, 'vote' => 'up', 'question_id' => $other]); + $this->assertTrue($answer['ok'], $answer['message']); + $this->assertSame(0, $answer['state']['qa']['votesLeft']); + + // Presenter clicks "Besprechen" in the stepper. + $state = $this->control($token, ['action' => 'stage', 'stage' => 'discuss']); + $this->assertSame(['discuss', 0], [$state['results']['stage'], $state['results']['focusIndex']]); + $this->assertSame('Andere Frage', $state['results']['questions'][0]['text']); + $this->assertStringNotContainsString('participant_hash', (string)json_encode($state)); + $this->cookie('plenario_pid', self::PID); + $this->get("/p/$code"); + $this->assertResponseContains('Die Fragen werden jetzt besprochen'); + $this->get("/admin/$token/present"); + $this->assertResponseOk(); + + // → steps through the questions first, then to the next slide. + $state = $this->control($token, ['action' => 'next']); + $this->assertSame([$slide->id, 1], [$state['slide']['id'], $state['results']['focusIndex']]); + $state = $this->control($token, ['action' => 'question', 'step' => '-1']); + $this->assertSame(0, $state['results']['focusIndex']); + $this->control($token, ['action' => 'next']); + $state = $this->control($token, ['action' => 'next']); + $this->assertSame($next->id, $state['slide']['id']); + + $this->get("/admin/$token/export.csv"); + $this->assertResponseOk(); + $this->assertResponseContains('Upvote: Andere Frage'); + $this->assertResponseContains('Meine Frage'); + } + + public function testResetStartsOver(): void + { + [$poll, $token] = $this->createPoll(); + $slide = $this->createSlide($poll, Slide::TYPE_QA); + $this->goLive($poll, $slide); + (new VoteService())->submit($this->pollsTable()->get($poll->id), $slide, 'p1', ['question' => 'Frage']); + $this->control($token, ['action' => 'stage', 'stage' => 'discuss']); + + $this->post("/admin/$token/slides/{$slide->id}/reset"); + $this->assertRedirect(); + $slide = $this->slidesTable()->get($slide->id); + $this->assertSame([Slide::QA_COLLECT, true, null], [$slide->stage, $slide->is_voting_open, $slide->focus_response_id]); + $this->assertSame(0, $this->fetchTable('Responses')->find()->where(['slide_id' => $slide->id])->count()); + } + + public function testStageActionRequiresQaSlide(): void + { + [$poll, $token] = $this->createPoll(); + $this->goLive($poll, $this->createSlide($poll, Slide::TYPE_CHOICE)); + $this->configRequest(['headers' => ['Accept' => 'application/json']]); + $this->post("/admin/$token/control", ['action' => 'stage', 'stage' => 'vote']); + $this->assertResponseCode(400); + } +} diff --git a/tests/TestCase/Service/QaTest.php b/tests/TestCase/Service/QaTest.php new file mode 100644 index 0000000..d08270e --- /dev/null +++ b/tests/TestCase/Service/QaTest.php @@ -0,0 +1,205 @@ + + */ + protected array $fixtures = ['app.Polls', 'app.Slides', 'app.SlideOptions', 'app.Responses']; + + /** + * @return array{0: \App\Model\Entity\Poll, 1: \App\Model\Entity\Slide} + */ + protected function createQa(int $maxUpvotes = 2): array + { + [$poll] = $this->createPoll(); + $slide = $this->createSlide($poll, Slide::TYPE_QA, ['settings' => ['max_upvotes' => $maxUpvotes]]); + + return [$this->goLive($poll, $slide), $slide]; + } + + protected function ask(Poll $poll, Slide $slide, string $participant, string $question): int + { + (new VoteService())->submit($poll, $slide, $participant, ['question' => $question]); + + return (int)$this->fetchTable('Responses')->find() + ->where(['slide_id' => $slide->id, 'participant_hash' => $participant]) + ->orderBy(['id' => 'DESC']) + ->firstOrFail() + ->get('id'); + } + + protected function vote(Poll $poll, Slide $slide, string $participant, int $questionId, string $vote = 'up'): void + { + (new VoteService())->submit($poll, $slide, $participant, ['vote' => $vote, 'question_id' => $questionId]); + } + + protected function stage(Slide $slide, string $stage): Slide + { + (new QaService())->setStage($slide, $stage); + + return $this->slidesTable()->get($slide->id, contain: ['SlideOptions']); + } + + protected function assertVoteFails(string $message, callable $fn): void + { + try { + $fn(); + $this->fail('VoteException expected'); + } catch (VoteException $e) { + $this->assertSame($message, $e->getMessage()); + } + } + + public function testSanitizesMaxUpvotes(): void + { + [, $slide] = $this->createQa(); + $this->assertSame(2, $slide->setting('max_upvotes')); + $this->assertSame(Slide::QA_COLLECT, $slide->qaStage()); + + $table = $this->slidesTable(); + $this->assertSame(1, $table->patchEntity($slide, ['type' => 'qa', 'settings' => ['max_upvotes' => '0']])->setting('max_upvotes')); + $this->assertSame(10, $table->patchEntity($slide, ['type' => 'qa', 'settings' => ['max_upvotes' => '99']])->setting('max_upvotes')); + } + + public function testCollectQuestionsSeveralPerParticipantWithoutDuplicates(): void + { + [$poll, $slide] = $this->createQa(); + $this->ask($poll, $slide, 'p1', 'Wann kommt das neue Fahrzeug?'); + $this->ask($poll, $slide, 'p1', 'Wer organisiert das Sommerfest?'); + + $this->assertVoteFails('Diese Frage wurde schon gestellt. Du kannst sie gleich beim Abstimmen unterstützen.', fn() => $this->ask($poll, $slide, 'p2', 'wann kommt das neue fahrzeug?')); + $this->assertVoteFails('Bitte gib eine Frage ein.', fn() => $this->ask($poll, $slide, 'p2', ' ')); + $this->assertVoteFails('Die Abstimmung über die Fragen hat noch nicht begonnen.', fn() => $this->vote($poll, $slide, 'p2', 1)); + + $results = (new ResultsService())->forSlide($slide); + $this->assertSame('collect', $results['stage']); + $this->assertSame(['Wann kommt das neue Fahrzeug?', 'Wer organisiert das Sommerfest?'], array_column($results['questions'], 'text')); + + // Participants see all questions while collecting (to avoid duplicates), even before asking. + $state = (new PollStateService())->forParticipant($poll, 'p2'); + $this->assertSame(['Wann kommt das neue Fahrzeug?', 'Wer organisiert das Sommerfest?'], array_column($state['qa']['questions'], 'text')); + $this->assertSame([], $state['qa']['mine']); + $this->assertArrayNotHasKey('votes', $state['qa']['questions'][0]); + $this->assertNull($state['results']); + $this->assertCount(2, (new PollStateService())->forParticipant($poll, 'p1')['qa']['questions']); + } + + public function testQuestionLimitPerParticipant(): void + { + [$poll, $slide] = $this->createQa(); + for ($i = 1; $i <= VoteService::MAX_QA_QUESTIONS; $i++) { + $this->ask($poll, $slide, 'p1', 'Frage ' . $i); + } + $this->assertVoteFails('Du kannst höchstens 10 Fragen stellen.', fn() => $this->ask($poll, $slide, 'p1', 'Noch eine')); + } + + public function testUpvotesAreABudgetThatCanBeStackedAndWithdrawn(): void + { + [$poll, $slide] = $this->createQa(3); + $a = $this->ask($poll, $slide, 'p1', 'Frage A'); + $b = $this->ask($poll, $slide, 'p2', 'Frage B'); + $c = $this->ask($poll, $slide, 'p2', 'Frage C'); + $slide = $this->stage($slide, Slide::QA_VOTE); + $this->assertTrue($slide->isVotingOpen()); + + $this->assertVoteFails('Es können keine neuen Fragen mehr eingereicht werden.', fn() => $this->ask($poll, $slide, 'p3', 'Zu spät')); + $this->assertVoteFails('Deine eigene Frage kannst du nicht unterstützen.', fn() => $this->vote($poll, $slide, 'p1', $a)); + $this->assertVoteFails('Diese Frage gibt es nicht.', fn() => $this->vote($poll, $slide, 'p1', 999999)); + + $this->vote($poll, $slide, 'p1', $b); + // Several upvotes on one question push it. + $this->vote($poll, $slide, 'p3', $c); + $this->vote($poll, $slide, 'p3', $b); + $this->vote($poll, $slide, 'p3', $b); + $this->assertVoteFails('Du hast alle 3 Stimmen vergeben. Nimm eine zurück, um eine andere Frage zu unterstützen.', fn() => $this->vote($poll, $slide, 'p3', $a)); + + // Withdraw one vote at a time and use it elsewhere. + $this->vote($poll, $slide, 'p3', $c, 'remove'); + $this->assertVoteFails('Du hast diese Frage nicht unterstützt.', fn() => $this->vote($poll, $slide, 'p3', $c, 'remove')); + $this->vote($poll, $slide, 'p3', $a); + + $results = (new ResultsService())->forSlide($slide); + $this->assertSame([[$b, 3], [$a, 1], [$c, 0]], array_map(fn($q) => [$q['id'], $q['votes']], $results['questions'])); + $this->assertSame(4, $results['upvotes']); + + $this->vote($poll, $slide, 'p3', $b, 'remove'); + $this->assertSame(2, (new ResultsService())->forSlide($slide)['questions'][0]['votes'], 'remove withdraws only one upvote'); + $this->vote($poll, $slide, 'p3', $b); + + // Voting view of participants: all questions, submission order, no counts. + $state = (new PollStateService())->forParticipant($poll, 'p3'); + $this->assertSame([$a, $b, $c], array_column($state['qa']['questions'], 'id')); + $this->assertArrayNotHasKey('votes', $state['qa']['questions'][0]); + $this->assertSame([$b => 2, $a => 1], $state['qa']['upvoted']); + $this->assertSame(0, $state['qa']['votesLeft']); + $this->assertTrue($state['hasResponded']); + } + + public function testDiscussStepsThroughQuestionsByRank(): void + { + [$poll, $slide] = $this->createQa(3); + $a = $this->ask($poll, $slide, 'p1', 'Frage A'); + $b = $this->ask($poll, $slide, 'p1', 'Frage B'); + $slide = $this->stage($slide, Slide::QA_VOTE); + $this->vote($poll, $slide, 'p2', $b); + + $slide = $this->stage($slide, Slide::QA_DISCUSS); + $this->assertFalse($slide->isVotingOpen()); + $this->assertSame($b, $slide->focus_response_id, 'most upvoted question first'); + $this->assertVoteFails('Die Fragerunde läuft – Fragen und Stimmen sind nicht mehr möglich.', fn() => $this->vote($poll, $slide, 'p2', $a)); + + $qa = new QaService(); + $this->assertFalse($qa->moveFocus($slide, -1)); + $modified = $slide->modified; + $this->assertTrue($qa->moveFocus($slide, 1)); + $this->assertFalse($qa->moveFocus($slide, 1), 'no question after the last one'); + $slide = $this->slidesTable()->get($slide->id, contain: ['SlideOptions']); + $this->assertSame($a, $slide->focus_response_id); + $this->assertEquals($modified, $slide->modified, 'focus changes do not reload participant pages'); + + $results = (new ResultsService())->forSlide($slide); + $this->assertSame([$a, 1], [$results['focusId'], $results['focusIndex']]); + $state = (new PollStateService())->forParticipant($poll, 'p2'); + $this->assertSame($a, $state['qa']['focusId']); + $this->assertSame([1, 0], array_column($state['qa']['questions'], 'votes')); + + // Idempotent: setting the same stage again keeps the focus. + $slide = $this->stage($slide, Slide::QA_DISCUSS); + $this->assertSame($a, $slide->focus_response_id); + } + + public function testAdvanceAndReset(): void + { + [$poll, $slide] = $this->createQa(); + $this->ask($poll, $slide, 'p1', 'Frage A'); + $qa = new QaService(); + $this->assertTrue($qa->advance($slide)); + $this->assertTrue($qa->advance($slide)); + $this->assertFalse($qa->advance($slide)); + $this->assertSame(Slide::QA_DISCUSS, $slide->qaStage()); + + $this->fetchTable('Responses')->deleteAll(['slide_id' => $slide->id]); + $qa->reset($slide); + $slide = $this->slidesTable()->get($slide->id); + $this->assertSame([Slide::QA_COLLECT, true, null], [$slide->qaStage(), $slide->is_voting_open, $slide->focus_response_id]); + } +} diff --git a/webroot/css/plenario.css b/webroot/css/plenario.css index 51daabd..c994186 100644 --- a/webroot/css/plenario.css +++ b/webroot/css/plenario.css @@ -27,6 +27,7 @@ --c3: #f29a1f; --c4: #2f8fe0; --c5: #8e44c9; + --qa: #1f6bb0; /* Q&A accent, AA contrast with white text */ } @media (prefers-color-scheme: dark) { @@ -39,6 +40,7 @@ --border: #30334a; --primary: #7f75ff; --primary-soft: #2a2752; + --qa: #7cc4ff; --shadow: none; } } @@ -146,6 +148,7 @@ h3 { font-size: 1.05rem; margin-top: 1.6em; } .badge--type-content { background: #e3eefb; color: #1f6bb0; } .badge--type-quiz { background: #f1e3fb; color: #7a2fb0; } .badge--type-youtube { background: #fde4e1; color: #b3261e; } +.badge--type-qa { background: #dff1fb; color: #0b5f8a; } .message { padding: 12px 16px; border-radius: 8px; margin-bottom: 20px; cursor: pointer; background: var(--surface-2); border-left: 4px solid var(--muted); } .message.success { border-color: var(--ok); } @@ -227,6 +230,7 @@ textarea { resize: vertical; } .type-card--content { border-top-color: var(--c4); } .type-card--quiz { border-top-color: var(--c5); } .type-card--youtube { border-top-color: #d93025; } +.type-card--qa { border-top-color: #0b8bc9; } /* ---------------------------------------------------------------- slide form: youtube */ .youtube-status { margin: 6px 0 0; font-size: .9rem; color: var(--muted); } @@ -382,6 +386,46 @@ textarea { resize: vertical; } .answers { list-style: none; padding: 0; margin: 0; columns: 280px; column-gap: 12px; } .answer { break-inside: avoid; background: var(--surface-2); border-radius: 10px; padding: 10px 14px; margin-bottom: 12px; word-break: break-word; } +/* Q&A (participants + presenter) */ +.qa-form__label { display: block; font-weight: 600; margin-bottom: 6px; } +.qa-message { min-height: 1.4em; margin: 8px 0; font-size: .9rem; color: var(--ok); } +.qa-message.is-error { color: var(--danger); } +.qa-heading { font-size: 1rem; margin: 16px 0 8px; } +.qa-list { list-style: none; padding: 0; margin: 0; display: grid; gap: 10px; } +.qa-item { position: relative; display: flex; align-items: center; gap: 12px; padding: 12px 14px; border-radius: 10px; background: var(--surface-2); overflow: hidden; } +.qa-item__text { flex: 1; min-width: 0; word-break: break-word; position: relative; } +.qa-item__bar { position: absolute; left: 0; bottom: 0; height: 4px; background: var(--qa); border-radius: 0 4px 4px 0; transition: width .6s ease; } +.qa-item.is-mine { border-left: 4px solid var(--qa); } +.qa-item.is-upvoted { box-shadow: inset 0 0 0 2px var(--qa); } +.qa-item.is-done { opacity: .55; } +.qa-item.is-current { box-shadow: inset 0 0 0 2px var(--c1); } +.qa-votes { font-weight: 700; font-variant-numeric: tabular-nums; white-space: nowrap; color: var(--qa); position: relative; } +.qa-own { font-size: .85rem; color: var(--muted); white-space: nowrap; } +.qa-stepper { flex: none; display: inline-flex; align-items: center; gap: 6px; } +.qa-stepper__count { min-width: 3.2em; text-align: center; font-weight: 700; font-variant-numeric: tabular-nums; color: var(--muted); } +.qa-stepper.is-active .qa-stepper__count { color: var(--qa); } +.qa-upvote { width: 44px; height: 44px; padding: 0; border-radius: 50%; border: 2px solid var(--qa); background: var(--surface); color: var(--qa); font: inherit; font-size: 1.3rem; font-weight: 700; line-height: 1; cursor: pointer; } +.qa-upvote--up { background: var(--qa); color: var(--surface); } +.qa-upvote:disabled { opacity: .45; cursor: not-allowed; } +.qa-upvote:focus-visible { outline: 3px solid var(--primary); outline-offset: 2px; } +.qa-budget { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; margin: 0 0 12px; } +.qa-budget strong { font-size: 1.4rem; color: var(--qa); } +.qa-budget__dot { width: 12px; height: 12px; border-radius: 50%; background: var(--qa); } +.qa-budget__dot.is-used { background: transparent; box-shadow: inset 0 0 0 2px var(--border); } +.qa-budget__dot:first-of-type { margin-left: 6px; } +.qa-focus { padding: 16px 18px; margin: 0 0 16px; border-radius: 14px; background: var(--surface-2); border-left: 6px solid var(--c1); } +.qa-focus__meta { display: flex; gap: 16px; justify-content: space-between; margin: 0 0 6px; font-size: .85rem; font-weight: 700; text-transform: uppercase; letter-spacing: .08em; color: var(--muted); } +.qa-focus__text { margin: 0; font-size: 1.3rem; font-weight: 700; word-break: break-word; } +.qa-focus__nav { display: flex; gap: 8px; justify-content: flex-end; margin-top: 12px; } +.qa-focus__nav:empty { display: none; } +.qa-list--compact .qa-item { padding: 8px 12px; } +.qa-summary { color: var(--muted); margin: 0 0 1em; } +.qa-steps { list-style: none; padding: 0; margin: 0 0 1em; display: flex; flex-wrap: wrap; gap: 6px; counter-reset: none; } +.qa-steps__step { display: inline-block; padding: 4px 12px; border-radius: 99px; border: 1px solid var(--border); background: transparent; color: var(--muted); font: inherit; font-size: .85em; } +button.qa-steps__step { cursor: pointer; } +button.qa-steps__step:hover:not(:disabled) { color: var(--text); border-color: var(--text); } +.qa-steps .is-current .qa-steps__step { background: var(--qa); border-color: var(--qa); color: var(--surface); font-weight: 700; cursor: default; } + /* ---------------------------------------------------------------- presenter */ body.present { --bg: #0f1020; @@ -422,6 +466,16 @@ body.present { /* brighter green for contrast on the dark stage */ .stage .quiz-summary strong, .stage .bar--correct .bar__label { color: #3ddc97; } .stage .bar--correct .bar__fill { background: #3ddc97; } +.stage .qa-steps { font-size: .7em; } +.stage .qa-steps__step { border-color: rgba(255, 255, 255, .25); } +.stage .qa-item { background: rgba(255, 255, 255, .06); } +.stage { --qa: #7cc4ff; } +.stage .qa-steps .is-current .qa-steps__step { color: var(--bg); } +.stage .qa-focus { background: rgba(255, 255, 255, .08); padding: 3vh 3vw; } +.stage .qa-focus__meta { font-size: .7em; } +.stage .qa-focus__text { font-size: clamp(1.8rem, 3.6vw, 3.2rem); line-height: 1.2; } +.stage .qa-list--compact { font-size: .75em; } +.stage--qa .stage__question { font-size: clamp(1.5rem, 3vw, 2.6rem); } .stage__controls { display: flex; gap: 8px; align-items: center; justify-content: center; flex-wrap: wrap; opacity: .35; transition: opacity .2s; padding-top: 12px; } .stage__controls:hover, .stage__controls:focus-within { opacity: 1; } diff --git a/webroot/js/plenario.js b/webroot/js/plenario.js index 2342eb3..2dff7c4 100644 --- a/webroot/js/plenario.js +++ b/webroot/js/plenario.js @@ -300,7 +300,8 @@ return; } // A quiz shows its answer options even before anyone has answered. - if (results.participants === 0 && !(results.type === 'quiz' && !results.revealed)) { + // A Q&A slide always shows its stages. + if (results.participants === 0 && results.type !== 'qa' && !(results.type === 'quiz' && !results.revealed)) { container.appendChild(el('p', { class: 'results-empty', text: 'Noch keine Antworten' })); return; } @@ -498,6 +499,111 @@ return el('ul', { class: 'answers' }, results.answers.map(function (answer) { return el('li', { class: 'answer', text: answer.text }); })); + }, + + /** + * Presenter view of a Q&A slide: stage stepper, then per stage the + * collected questions, the live ranking or the question being discussed. + * options: {onStage: fn(stage)|null, onQuestion: fn(step)|null} + */ + qa: function (results, options) { + var onStage = options && options.onStage; + var onQuestion = options && options.onQuestion; + var questions = results.questions; + var maxVotes = Math.max.apply(null, questions.map(function (q) { return q.votes; }).concat([1])); + var children = [Qa.steps(results.stage, onStage)]; + + function votes(question) { + return el('span', { + class: 'qa-votes', + 'aria-label': question.votes + (question.votes === 1 ? ' Stimme' : ' Stimmen'), + text: '▲ ' + question.votes + }); + } + + if (results.stage === 'collect') { + children.push(el('p', { class: 'qa-summary', text: questions.length === 0 + ? 'Noch keine Fragen – jetzt mitmachen und Fragen einreichen!' + : questions.length + (questions.length === 1 ? ' Frage eingereicht' : ' Fragen eingereicht') })); + children.push(el('ul', { class: 'answers' }, questions.slice().reverse().map(function (question) { + return el('li', { class: 'answer', text: question.text }); + }))); + } else if (results.stage === 'vote') { + children.push(el('p', { class: 'qa-summary', text: 'Abstimmen: jede Person hat ' + + results.maxUpvotes + (results.maxUpvotes === 1 ? ' Stimme' : ' Stimmen') + + ' · bisher ' + results.upvotes + ' vergeben' })); + children.push(el('ol', { class: 'qa-list' }, questions.map(function (question) { + return el('li', { class: 'qa-item' }, [ + el('span', { class: 'qa-item__text', text: question.text }), + votes(question), + el('span', { class: 'qa-item__bar', style: 'width:' + (question.votes / maxVotes * 100) + '%' }) + ]); + }))); + } else if (questions.length === 0) { + children.push(el('p', { class: 'qa-summary', text: 'Es wurden keine Fragen eingereicht.' })); + } else { + var index = results.focusIndex === null ? 0 : results.focusIndex; + var focus = questions[index]; + var nav = function (step, label, symbol, disabled) { + if (!onQuestion) { + return null; + } + var button = el('button', { type: 'button', class: 'ctrl', title: label }, [ + el('span', { 'aria-hidden': 'true', text: symbol }), + el('span', { class: 'sr-only', text: label }) + ]); + button.disabled = disabled; + button.addEventListener('click', function () { onQuestion(step); }); + return button; + }; + children.push(el('div', { class: 'qa-focus', 'aria-live': 'polite' }, [ + el('p', { class: 'qa-focus__meta' }, [ + el('span', { text: 'Frage ' + (index + 1) + ' von ' + questions.length }), + votes(focus) + ]), + el('p', { class: 'qa-focus__text', text: focus.text }), + el('div', { class: 'qa-focus__nav' }, [ + nav(-1, 'Vorherige Frage', '←', index === 0), + nav(1, 'Nächste Frage', '→', index === questions.length - 1) + ]) + ])); + children.push(el('ol', { class: 'qa-list qa-list--compact' }, questions.map(function (question, i) { + var attrs = { class: 'qa-item' + (i < index ? ' is-done' : '') + (i === index ? ' is-current' : '') }; + if (i === index) { + attrs['aria-current'] = 'true'; + } + return el('li', attrs, [ + el('span', { class: 'qa-item__text', text: (i < index ? '✓ ' : '') + question.text }), + votes(question) + ]); + }))); + } + return el('div', { class: 'qa-results qa-results--' + results.stage }, children); + } + }; + + // ------------------------------------------------------------------ Q&A + + var Qa = { + labels: { collect: 'Fragen sammeln', vote: 'Abstimmen', discuss: 'Besprechen' }, + + /** Stepper of the three stages; clickable for the presenter (onStage). */ + steps: function (stage, onStage) { + return el('ol', { class: 'qa-steps', 'aria-label': 'Ablauf' }, ['collect', 'vote', 'discuss'].map(function (key, i) { + var current = key === stage; + var label = (i + 1) + ' ' + Qa.labels[key]; + var item = onStage + ? el('button', { type: 'button', class: 'qa-steps__step', text: label }) + : el('span', { class: 'qa-steps__step', text: label }); + if (current) { + item.setAttribute('aria-current', 'step'); + } + if (onStage) { + item.disabled = current; + item.addEventListener('click', function () { onStage(key); }); + } + return el('li', { class: current ? 'is-current' : '' }, [item]); + })); } }; @@ -704,29 +810,38 @@ } var quizPhase = slide.type === 'quiz' && state.results ? state.results.phase : null; + var qaStage = slide.type === 'qa' && state.results ? state.results.stage : null; q('[data-type]').textContent = quizPhase ? slide.typeLabel + ' · ' + { ready: 'bereit', running: 'läuft', finished: 'Auflösung' }[quizPhase] - : slide.typeLabel; + : (qaStage ? slide.typeLabel + ' · ' + Qa.labels[qaStage] : slide.typeLabel); q('[data-question]').textContent = slide.question; q('[data-description]').textContent = slide.description; root.classList.toggle('stage--content', !slide.isInteractive); root.classList.toggle('stage--video', slide.type === 'youtube'); renderMedia(slide); - root.classList.toggle('stage--closed', slide.isInteractive && !slide.isVotingOpen && !quizPhase); + root.classList.toggle('stage--closed', slide.isInteractive && !slide.isVotingOpen && !quizPhase && !qaStage); + root.classList.toggle('stage--qa', !!qaStage); var voting = q('[data-voting]'); - voting.hidden = !slide.isInteractive; + // Q&A: V switches to the next stage, there is none after "discuss". + voting.hidden = !slide.isInteractive || qaStage === 'discuss'; voting.querySelector('[data-label]').textContent = quizPhase ? { ready: 'Quiz starten', running: 'Quiz beenden', finished: 'Quiz erneut öffnen' }[quizPhase] - : (slide.isVotingOpen ? 'Abstimmung schließen' : 'Abstimmung öffnen'); + : (qaStage + ? { collect: 'Einreichen beenden', vote: 'Abstimmung beenden', discuss: '' }[qaStage] + : (slide.isVotingOpen ? 'Abstimmung schließen' : 'Abstimmung öffnen')); - q('[data-participants]').textContent = slide.isInteractive - ? state.results.participants + ' ' + (state.results.participants === 1 ? 'Antwort' : 'Antworten') - : ''; + var count = qaStage ? state.results.questions.length : (slide.isInteractive ? state.results.participants : 0); + q('[data-participants]').textContent = !slide.isInteractive ? '' : (qaStage + ? count + (count === 1 ? ' Frage' : ' Fragen') + : count + ' ' + (count === 1 ? 'Antwort' : 'Antworten')); var container = q('[data-results]'); container.classList.toggle('is-hidden', hideResults); - Results.render(container, slide.isInteractive ? state.results : null); + Results.render(container, slide.isInteractive ? state.results : null, { + onStage: function (stage) { control('stage', { stage: stage }); }, + onQuestion: function (step) { control('question', { step: step }); } + }); Countdown.start(); } @@ -833,8 +948,178 @@ && state.isVotingOpen); } + // --- Q&A: submit questions, upvote, follow the discussion ---------- + var qaRoot = root.querySelector('[data-qa]'); + var qaList = qaRoot ? qaRoot.querySelector('[data-qa-list]') : null; + var qaMessage = qaRoot ? qaRoot.querySelector('[data-qa-message]') : null; + var qaForm = qaRoot ? qaRoot.querySelector('[data-qa-form]') : null; + var qaRendered = ''; + var qaSending = false; + + function qaSay(text, isError) { + qaMessage.textContent = text; + qaMessage.classList.toggle('is-error', !!isError); + } + + function sendQa(data) { + if (qaSending) { + return Promise.resolve(null); + } + qaSending = true; + data.slide_id = root.querySelector('[name=slide_id]').value; + return postJson(voteUrl, data).then(function (response) { + qaSay(response.message, !response.ok); + if (response.state.version !== version) { + window.location.reload(); + return null; + } + renderQa(response.state); + return response; + }).catch(function () { + qaSay('Das hat nicht geklappt. Bitte versuche es noch einmal.', true); + return null; + }).then(function (response) { + qaSending = false; + return response; + }); + } + + function renderQa(state) { + var qa = state.qa; + if (!qaList || !qa) { + return; + } + var key = JSON.stringify(qa); + if (key === qaRendered) { + return; + } + qaRendered = key; + // Keep keyboard focus on the same question after re-rendering. + var focused = document.activeElement && document.activeElement.getAttribute('data-question-id'); + qaList.textContent = ''; + + if (qa.stage === 'collect') { + // All questions so far, so participants can spot duplicates before asking. + qaList.appendChild(el('h2', { class: 'qa-heading', text: 'Bereits gestellte Fragen (' + qa.questions.length + ')' })); + if (!qa.questions.length) { + qaList.appendChild(el('p', { class: 'results-empty', text: 'Noch keine – stell gern die erste Frage!' })); + return; + } + qaList.appendChild(el('ul', { class: 'qa-list' }, qa.questions.map(function (question) { + var mine = qa.mine.indexOf(question.id) >= 0; + return el('li', { class: 'qa-item' + (mine ? ' is-mine' : '') }, [ + el('span', { class: 'qa-item__text', text: question.text }), + mine ? el('span', { class: 'qa-own', text: 'deine Frage' }) : null + ]); + }))); + return; + } + + if (qa.stage === 'vote') { + var used = qa.maxUpvotes - qa.votesLeft; + qaList.appendChild(el('p', { class: 'qa-budget', 'aria-live': 'polite' }, [ + el('strong', { text: String(qa.votesLeft) }), + el('span', { text: ' von ' + qa.maxUpvotes + (qa.maxUpvotes === 1 ? ' Stimme' : ' Stimmen') + ' übrig' }) + ].concat(Array.apply(null, Array(qa.maxUpvotes)).map(function (_, i) { + return el('span', { class: 'qa-budget__dot' + (i < used ? ' is-used' : ''), 'aria-hidden': 'true' }); + })))); + if (!qa.questions.length) { + qaList.appendChild(el('p', { class: 'results-empty', text: 'Es wurden keine Fragen eingereicht.' })); + return; + } + qaList.appendChild(el('ul', { class: 'qa-list' }, qa.questions.map(function (question) { + var mine = qa.mine.indexOf(question.id) >= 0; + // Own upvotes on this question – several are allowed to push important questions. + var given = (qa.upvoted || {})[question.id] || 0; + var action; + if (mine) { + action = el('span', { class: 'qa-own', text: 'deine Frage' }); + } else { + var button = function (vote, symbol, label, disabled) { + var b = el('button', { + type: 'button', + class: 'qa-upvote qa-upvote--' + vote, + 'aria-label': label + ': ' + question.text, + 'data-question-id': question.id + '-' + vote + }, [el('span', { 'aria-hidden': 'true', text: symbol })]); + b.disabled = disabled; + b.addEventListener('click', function () { + sendQa({ vote: vote, question_id: question.id }); + }); + return b; + }; + action = el('span', { class: 'qa-stepper' + (given > 0 ? ' is-active' : '') }, [ + button('remove', '−', 'Stimme zurücknehmen', given === 0), + el('span', { + class: 'qa-stepper__count', + 'aria-label': given === 0 ? 'keine Stimme von dir' : given + (given === 1 ? ' Stimme' : ' Stimmen') + ' von dir', + text: '▲ ' + given + }), + button('up', '+', 'Stimme geben', qa.votesLeft === 0) + ]); + } + return el('li', { class: 'qa-item' + (mine ? ' is-mine' : '') + (given > 0 ? ' is-upvoted' : '') }, [ + el('span', { class: 'qa-item__text', text: question.text }), + action + ]); + }))); + } else { + if (!qa.questions.length) { + qaList.appendChild(el('p', { class: 'results-empty', text: 'Es wurden keine Fragen eingereicht.' })); + return; + } + var index = -1; + qa.questions.forEach(function (question, i) { + if (question.id === qa.focusId) { + index = i; + } + }); + if (index >= 0) { + qaList.appendChild(el('div', { class: 'qa-focus', 'aria-live': 'polite' }, [ + el('p', { class: 'qa-focus__meta', text: 'Wird gerade besprochen · Frage ' + (index + 1) + ' von ' + qa.questions.length }), + el('p', { class: 'qa-focus__text', text: qa.questions[index].text }) + ])); + } + qaList.appendChild(el('ol', { class: 'qa-list qa-list--compact' }, qa.questions.map(function (question, i) { + var mine = qa.mine.indexOf(question.id) >= 0; + var attrs = { class: 'qa-item' + (i < index ? ' is-done' : '') + (i === index ? ' is-current' : '') + (mine ? ' is-mine' : '') }; + if (i === index) { + attrs['aria-current'] = 'true'; + } + return el('li', attrs, [ + el('span', { class: 'qa-item__text', text: (i < index ? '✓ ' : '') + question.text + (mine ? ' (deine Frage)' : '') }), + el('span', { class: 'qa-votes', 'aria-label': question.votes + (question.votes === 1 ? ' Stimme' : ' Stimmen'), text: '▲ ' + question.votes }) + ]); + }))); + } + + if (focused) { + var again = qaList.querySelector('[data-question-id="' + focused + '"]'); + if (again && !again.disabled) { + again.focus(); + } + } + } + + if (qaForm) { + qaForm.addEventListener('submit', function (event) { + event.preventDefault(); + var field = qaForm.querySelector('[name=question]'); + var text = field.value.trim(); + if (!text) { + return; + } + sendQa({ question: text }).then(function (response) { + if (response && response.ok) { + field.value = ''; + } + }); + }); + } + function renderResults(state) { current = state; + renderQa(state); if (!card || !container) { return; } From 58145e9753adfe4d94ae9a2d595b74fbb3a5a180 Mon Sep 17 00:00:00 2001 From: Patrick Niebeling Date: Sat, 7 Nov 2026 16:15:14 +0100 Subject: [PATCH 2/3] Add light/dark theme switch Theme follows the system by default; the header switch cycles auto/light/dark and is stored per browser. The presenter has its own switch (T), dark by default. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 9 +++- templates/Admin/present.php | 8 +++- templates/element/theme_init.php | 24 ++++++++++ templates/element/theme_switch.php | 25 ++++++++++ templates/layout/default.php | 2 + templates/layout/error.php | 1 + templates/layout/present.php | 3 +- webroot/css/plenario.css | 75 ++++++++++++++++++++++++------ webroot/js/plenario.js | 58 +++++++++++++++++++++++ 9 files changed, 187 insertions(+), 18 deletions(-) create mode 100644 templates/element/theme_init.php create mode 100644 templates/element/theme_switch.php diff --git a/AGENTS.md b/AGENTS.md index f52b853..3005a9f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -68,7 +68,7 @@ src/ YouTubeService YouTube-Links/Timecodes parsen, Watch-/Embed-URLs, Prüfung per oEmbed (Http\Client) QaService Q&A: Phasen wechseln, Fragen nach Upvotes ranken, Fokus beim Besprechen templates/ Deutsche UI, Layouts: default, present (Vollbild, dunkel), error, email -webroot/css/plenario.css Eigenes CSS, kein Framework +webroot/css/plenario.css Eigenes CSS, kein Framework; Farben nur als Tokens (Hell/Dunkel, siehe Theme unten) webroot/js/plenario.js Vanilla JS: Polling, Ergebnis-Rendering, Presenter-Steuerung, Folien-Sortierung (Pointer Events + Pfeiltasten) tests/ PHPUnit; PlenarioTestTrait erzeugt Testdaten, Fixtures sind leer ``` @@ -147,6 +147,13 @@ tests/ PHPUnit; PlenarioTestTrait erzeugt Testdaten, Fixtures 7. Tests in `tests/TestCase/Service/VoteServiceTest.php` (Quiz: `QuizTest.php`, Q&A: `QaTest.php`) 8. Nach neuen Spalten lokal `bin/cake cache clear_all`, sonst nutzt das ORM das alte Schema aus dem Cache +### Farbschema (Tag/Nacht) + +`data-theme="light|dark"` auf ``, ohne Attribut gilt die Systemeinstellung. `element/theme_init` setzt die +Wahl aus `localStorage` vor dem ersten Rendern (Inline-Skript im ``), `element/theme_switch` ist der Schalter +(`Theme` in `plenario.js`). Presenter: eigener Schlüssel `plenario-theme-present`, Standard dunkel, Taste T. +Neue Farben als Token in beiden Dark-Blöcken von `plenario.css` pflegen; auf der Bühne Overlays mit `rgba(var(--tint), …)`. + ### Live-Updates Kein WebSocket: Presenter (`/admin/{token}/state`) und Teilnehmende (`/p/{code}/state`) pollen per `fetch` diff --git a/templates/Admin/present.php b/templates/Admin/present.php index 7c03ffd..13a6be5 100644 --- a/templates/Admin/present.php +++ b/templates/Admin/present.php @@ -3,7 +3,7 @@ * Presenter screen. Rendered empty and filled by webroot/js/plenario.js * (Plenario.presenter) from /admin/{token}/state. * - * Keyboard: ←/→ slides, V voting on/off, H hide results, F fullscreen, Q QR code. + * Keyboard: ←/→ slides, V voting on/off, H hide results, F fullscreen, Q QR code, T light/dark. * Q&A slides: V switches to the next stage; while discussing ←/→ step through the questions first. * * @var \App\View\AppView $this @@ -57,6 +57,12 @@ $host = preg_replace('#^https?://#', '', $joinBaseUrl); + element('theme_switch', [ + 'key' => 'plenario-theme-present', + 'modes' => 'dark,light', + 'class' => 'ctrl ctrl--wide', + 'shortcut' => 'T', + ]) ?> diff --git a/templates/layout/default.php b/templates/layout/default.php index f43e159..15ae39c 100644 --- a/templates/layout/default.php +++ b/templates/layout/default.php @@ -16,6 +16,7 @@ $title = $this->fetch('title'); <?= $title ? h($title) . ' · ' : '' ?>Plenario + element('theme_init') ?> Html->meta('icon') ?> Html->css(['normalize.min', 'plenario']) ?> fetch('meta') ?> @@ -31,6 +32,7 @@ $title = $this->fetch('title'); + element('theme_switch') ?>
diff --git a/templates/layout/error.php b/templates/layout/error.php index 5eecf82..fa11cf4 100644 --- a/templates/layout/error.php +++ b/templates/layout/error.php @@ -12,6 +12,7 @@ <?= h($this->fetch('title')) ?> · Plenario + element('theme_init') ?> Html->meta('icon') ?> Html->css(['normalize.min', 'plenario']) ?> diff --git a/templates/layout/present.php b/templates/layout/present.php index b06937e..7d3e60a 100644 --- a/templates/layout/present.php +++ b/templates/layout/present.php @@ -1,6 +1,6 @@ <?= h($this->fetch('title')) ?> · Plenario + element('theme_init', ['key' => 'plenario-theme-present', 'fallback' => 'dark']) ?> Html->meta('icon') ?> Html->css(['normalize.min', 'plenario']) ?> diff --git a/webroot/css/plenario.css b/webroot/css/plenario.css index c994186..041f8ca 100644 --- a/webroot/css/plenario.css +++ b/webroot/css/plenario.css @@ -28,10 +28,33 @@ --c4: #2f8fe0; --c5: #8e44c9; --qa: #1f6bb0; /* Q&A accent, AA contrast with white text */ + --notice-bg: #fff6e0; + --notice-ink: #6b4a00; + color-scheme: light; +} + +/* + * Theme: data-theme="light|dark" on (set by the theme switch, stored per browser), + * without it the system setting decides. Keep both dark blocks in sync. + */ +:root[data-theme="dark"] { + --bg: #12131d; + --surface: #1b1d2b; + --surface-2: #24263a; + --text: #eceefa; + --muted: #a1a6c3; + --border: #30334a; + --primary: #7f75ff; + --primary-soft: #2a2752; + --qa: #7cc4ff; + --shadow: none; + --notice-bg: #3a2f12; + --notice-ink: #f3d98f; + color-scheme: dark; } @media (prefers-color-scheme: dark) { - :root:not(.present) { + :root:not([data-theme="light"]) { --bg: #12131d; --surface: #1b1d2b; --surface-2: #24263a; @@ -42,6 +65,9 @@ --primary-soft: #2a2752; --qa: #7cc4ff; --shadow: none; + --notice-bg: #3a2f12; + --notice-ink: #f3d98f; + color-scheme: dark; } } @@ -156,8 +182,7 @@ h3 { font-size: 1.05rem; margin-top: 1.6em; } .message.warning { border-color: var(--warn); } .message.hidden { display: none; } -.notice { padding: 12px 16px; border-radius: 8px; background: #fff6e0; color: #6b4a00; margin-bottom: 24px; font-size: .95rem; } -@media (prefers-color-scheme: dark) { .notice { background: #3a2f12; color: #f3d98f; } } +.notice { padding: 12px 16px; border-radius: 8px; background: var(--notice-bg); color: var(--notice-ink); margin-bottom: 24px; font-size: .95rem; } .devnote { margin-top: 24px; padding: 16px; border: 2px dashed var(--warn); border-radius: var(--radius); } .icon-circle { width: 64px; height: 64px; margin: 0 auto 16px; border-radius: 50%; display: grid; place-items: center; font-size: 28px; background: var(--primary-soft); color: var(--primary); } @@ -427,19 +452,34 @@ button.qa-steps__step:hover:not(:disabled) { color: var(--text); border-color: v .qa-steps .is-current .qa-steps__step { background: var(--qa); border-color: var(--qa); color: var(--surface); font-weight: 700; cursor: default; } /* ---------------------------------------------------------------- presenter */ +/* Dark by default (beamer); the presenter's own switch can make it light (data-theme="light"). */ body.present { --bg: #0f1020; --surface-2: #1f2140; --text: #f3f4ff; --muted: #a3a7cf; - background: radial-gradient(1200px 600px at 10% -10%, #2a1f6e 0%, transparent 60%), var(--bg); + --tint: 255, 255, 255; /* overlays on the stage: rgba(var(--tint), alpha) */ + --stage-glow: #2a1f6e; + --stage-ok: #3ddc97; /* brighter green for contrast on the dark stage */ + --overlay-bg: rgba(8, 9, 20, .92); + background: radial-gradient(1200px 600px at 10% -10%, var(--stage-glow) 0%, transparent 60%), var(--bg); color: var(--text); overflow: hidden; } .stage { display: grid; grid-template-rows: auto 1fr auto; height: 100vh; padding: 20px 4vw; } +:root[data-theme="light"] body.present { + --bg: #f5f6fb; + --surface-2: #e4e7f4; + --text: #1d1f33; + --muted: #4f5473; + --tint: 20, 22, 50; + --stage-glow: #dcd8ff; + --stage-ok: var(--ok); + --overlay-bg: rgba(245, 246, 251, .95); +} .stage__top { display: flex; justify-content: space-between; align-items: center; gap: 16px; font-size: clamp(1rem, 1.6vw, 1.4rem); color: var(--muted); } .stage__top strong { color: var(--text); } -.stage__code { letter-spacing: .12em; background: rgba(255, 255, 255, .1); padding: 2px 10px; border-radius: 8px; } +.stage__code { letter-spacing: .12em; background: rgba(var(--tint), .1); padding: 2px 10px; border-radius: 8px; } .stage__qr { border: 0; padding: 4px; background: #fff; border-radius: 8px; cursor: zoom-in; } .stage__qr img { display: block; width: 72px; height: 72px; } .stage__main { display: flex; flex-direction: column; justify-content: center; min-height: 0; overflow: auto; padding: 2vh 0; } @@ -454,7 +494,7 @@ body.present { .stage--closed .stage__type::after { content: " · Abstimmung geschlossen"; color: var(--muted); } .stage .bar__track { height: 1.1em; } .stage .columns { height: 34vh; } -.stage .average { padding: 2vh 2.5vw; gap: 2vh 4vw; background: rgba(255, 255, 255, .06); } +.stage .average { padding: 2vh 2.5vw; gap: 2vh 4vw; background: rgba(var(--tint), .06); } .stage .average__value strong { font-size: clamp(4rem, 9vw, 8rem); } .stage .average__of { font-size: clamp(1.6rem, 3vw, 2.8rem); } .stage .average__label, .stage .average__count, .stage .average__ends { font-size: clamp(.9rem, 1.4vw, 1.3rem); } @@ -463,15 +503,15 @@ body.present { .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 .quiz-summary strong, .stage .bar--correct .bar__label { color: var(--stage-ok); } +.stage .bar--correct .bar__fill { background: var(--stage-ok); } .stage .qa-steps { font-size: .7em; } -.stage .qa-steps__step { border-color: rgba(255, 255, 255, .25); } -.stage .qa-item { background: rgba(255, 255, 255, .06); } +.stage .qa-steps__step { border-color: rgba(var(--tint), .25); } +.stage .qa-item { background: rgba(var(--tint), .06); } .stage { --qa: #7cc4ff; } +:root[data-theme="light"] .stage { --qa: #1f6bb0; } .stage .qa-steps .is-current .qa-steps__step { color: var(--bg); } -.stage .qa-focus { background: rgba(255, 255, 255, .08); padding: 3vh 3vw; } +.stage .qa-focus { background: rgba(var(--tint), .08); padding: 3vh 3vw; } .stage .qa-focus__meta { font-size: .7em; } .stage .qa-focus__text { font-size: clamp(1.8rem, 3.6vw, 3.2rem); line-height: 1.2; } .stage .qa-list--compact { font-size: .75em; } @@ -479,8 +519,8 @@ body.present { .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; } -.ctrl { min-width: 44px; height: 40px; padding: 0 12px; border-radius: 8px; border: 1px solid rgba(255, 255, 255, .2); background: rgba(255, 255, 255, .06); color: var(--text); font: inherit; cursor: pointer; display: inline-flex; align-items: center; justify-content: center; text-decoration: none; } -.ctrl:hover { background: rgba(255, 255, 255, .15); } +.ctrl { min-width: 44px; height: 40px; padding: 0 12px; border-radius: 8px; border: 1px solid rgba(var(--tint), .2); background: rgba(var(--tint), .06); color: var(--text); font: inherit; cursor: pointer; display: inline-flex; align-items: center; justify-content: center; text-decoration: none; } +.ctrl:hover { background: rgba(var(--tint), .15); } .ctrl { gap: 6px; } /* Visible keyboard shortcuts – nobody hovers for tooltips during a talk. */ .ctrl__key { font: inherit; font-size: .8em; font-variant-numeric: tabular-nums; color: var(--muted); white-space: nowrap; } @@ -492,6 +532,11 @@ body.present { } .ctrl-counter { color: var(--muted); min-width: 64px; text-align: center; font-variant-numeric: tabular-nums; } -.qr-overlay { position: fixed; inset: 0; background: rgba(8, 9, 20, .92); display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 16px; cursor: zoom-out; z-index: 10; } +.qr-overlay { position: fixed; inset: 0; background: var(--overlay-bg); display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 16px; cursor: zoom-out; z-index: 10; } .qr-overlay img { width: min(70vh, 80vw); height: auto; background: #fff; border-radius: 16px; padding: 16px; } .qr-overlay p { font-size: 1.4rem; } + +/* ---------------------------------------------------------------- theme switch */ +.theme-switch { display: inline-flex; align-items: center; gap: 6px; padding: 6px 10px; border-radius: 8px; border: 1px solid var(--border); background: transparent; color: var(--text); font: inherit; font-size: .9rem; cursor: pointer; } +.theme-switch:hover { border-color: var(--primary); } +.theme-switch__icon { font-size: 1.05em; line-height: 1; } diff --git a/webroot/js/plenario.js b/webroot/js/plenario.js index 2dff7c4..2541d72 100644 --- a/webroot/js/plenario.js +++ b/webroot/js/plenario.js @@ -10,6 +10,8 @@ * - [data-countdown] quiz timer (data-remaining = seconds), fires `plenario:timeup` on document * - [data-quiz-options] slide form: "add answer" button for quiz slides * - [data-sortable] admin slide list: drag & drop / arrow keys via [data-drag-handle], POSTs ids[] to the URL + * - [data-theme-switch] cycles the colour scheme (data-theme on , stored in localStorage), + * see templates/element/theme_init.php for the pre-paint part * * Results JSON shape: see src/Service/ResultsService.php */ @@ -917,11 +919,18 @@ case 'Q': toggleQr(); break; + case 't': + case 'T': + if (themeSwitch) { + themeSwitch.click(); + } + break; case 'Escape': overlay.hidden = true; break; } }); + var themeSwitch = q('[data-theme-switch]'); var poller = poll(refresh, interval); document.addEventListener('plenario:timeup', function () { @@ -1523,9 +1532,58 @@ } } + // ------------------------------------------------------------------ theme switch + + var THEME_ICONS = { auto: '◐', light: '☀', dark: '☾' }; + + function initThemeSwitch(button) { + var key = button.getAttribute('data-theme-key'); + var modes = button.getAttribute('data-theme-modes').split(','); + var root = document.documentElement; + + function current() { + var theme = root.getAttribute('data-theme') || 'auto'; + return modes.indexOf(theme) >= 0 ? theme : modes[0]; + } + + function label(mode) { + return button.getAttribute('data-label-' + mode); + } + + function render() { + var mode = current(); + var next = modes[(modes.indexOf(mode) + 1) % modes.length]; + button.querySelector('[data-theme-icon]').textContent = THEME_ICONS[mode]; + button.querySelector('[data-theme-label]').textContent = label(mode); + var text = button.getAttribute('data-label-prefix') + ': ' + label(mode) + ', ' + + button.getAttribute('data-label-next') + ' ' + label(next); + button.setAttribute('aria-label', text); + button.title = text + (button.hasAttribute('aria-keyshortcuts') ? ' (' + button.getAttribute('aria-keyshortcuts') + ')' : ''); + } + + button.addEventListener('click', function () { + var next = modes[(modes.indexOf(current()) + 1) % modes.length]; + if (next === 'auto') { + root.removeAttribute('data-theme'); + } else { + root.setAttribute('data-theme', next); + } + try { + localStorage.setItem(key, next); + } catch (e) { + // private mode: the choice just lasts until reload + } + render(); + }); + + render(); + button.hidden = false; + } + // ------------------------------------------------------------------ boot document.addEventListener('DOMContentLoaded', function () { + document.querySelectorAll('[data-theme-switch]').forEach(initThemeSwitch); initCopy(); initShare(); document.querySelectorAll('[data-youtube-form]').forEach(initYouTubeForm); From 07a292d1095c8833cbe24f29aa9737f1c2797df6 Mon Sep 17 00:00:00 2001 From: Patrick Niebeling Date: Sat, 7 Nov 2026 16:26:05 +0100 Subject: [PATCH 3/3] Add embeddable slides and pause mode Every slide gets an embed URL /e/{key}/{id} for presentation software like Canva. The page goes live while it is visible, keeps itself live with heartbeats and pauses when it disappears; stale embeds are paused lazily. The embed key is separate from the admin token and only allows showing, activating, pausing and voting controls of that slide. Participants see a pause page while no slide is live. The presenter can pause (P) and resume the paused slide with the arrow keys; the dashboard has a pause button. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 19 +- config/.env.example | 5 + .../20261107150000_AddEmbedToPolls.php | 29 ++ config/app.php | 9 + config/routes.php | 16 ++ src/Application.php | 11 +- src/Controller/AdminController.php | 101 +++---- src/Controller/EmbedController.php | 223 ++++++++++++++ src/Model/Entity/Poll.php | 53 ++++ src/Model/Table/PollsTable.php | 79 +++++ src/Service/PollStateService.php | 39 +++ src/Service/SlideControlService.php | 90 ++++++ templates/Admin/index.php | 31 ++ templates/Admin/present.php | 6 +- templates/Embed/view.php | 66 +++++ templates/Participate/view.php | 7 + tests/TestCase/Controller/EmbedTest.php | 271 ++++++++++++++++++ webroot/css/plenario.css | 9 + webroot/js/plenario.js | 120 +++++++- 19 files changed, 1116 insertions(+), 68 deletions(-) create mode 100644 config/Migrations/20261107150000_AddEmbedToPolls.php create mode 100644 src/Controller/EmbedController.php create mode 100644 src/Service/SlideControlService.php create mode 100644 templates/Embed/view.php create mode 100644 tests/TestCase/Controller/EmbedTest.php diff --git a/AGENTS.md b/AGENTS.md index 3005a9f..b172d4a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -58,6 +58,7 @@ src/ SlidesController Folien-CRUD, Sortieren (Drag & Drop/Pfeiltasten via `reorder`, JSON; erfordert JS), Antworten zurücksetzen, YouTube-Link prüfen (`youtubeCheck`, JSON) ParticipateController /p/{code}: Ansicht, State-JSON, Abstimmen; anonymes Cookie plenario_pid + EmbedController /e/{key}/{id}: eine Folie zum Einbetten (z. B. Canva), activate/heartbeat/pause/control Mailer/ PollMailer (adminLink, recovery), Transport/FileTransport (lokal) Model/ Polls → Slides → SlideOptions, Slides → Responses Service/ @@ -67,6 +68,7 @@ src/ ThrottleService Rate-Limit pro IP (Cache 'throttle') YouTubeService YouTube-Links/Timecodes parsen, Watch-/Embed-URLs, Prüfung per oEmbed (Http\Client) QaService Q&A: Phasen wechseln, Fragen nach Upvotes ranken, Fokus beim Besprechen + SlideControlService Folien-Aktionen open/close/toggle/stage/question (Presenter und Einbettung gemeinsam) templates/ Deutsche UI, Layouts: default, present (Vollbild, dunkel), error, email webroot/css/plenario.css Eigenes CSS, kein Framework; Farben nur als Tokens (Hell/Dunkel, siehe Theme unten) webroot/js/plenario.js Vanilla JS: Polling, Ergebnis-Rendering, Presenter-Steuerung, Folien-Sortierung (Pointer Events + Pfeiltasten) @@ -76,7 +78,9 @@ tests/ PHPUnit; PlenarioTestTrait erzeugt Testdaten, Fixtures ### Datenmodell - `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` + `join_code` (6 Zeichen, ohne 0/O/1/I/L), `current_slide_id`, `is_active`, `show_results_to_participants`, + `embed_key` (Einbett-Schlüssel), `embed_seen_at` (letztes Lebenszeichen der eingebetteten Live-Folie), + `paused_slide_id` (Folie vor der Pause) - `slides`: `type` (`choice|wordcloud|open|scale|content|quiz|youtube|qa`), `question`, `description`, `position`, `settings` (JSON, je Typ siehe `Slide::DEFAULT_SETTINGS`), `is_voting_open`, `voting_started_at` / `voting_ends_at` (nur Quiz: Start und Deadline, `null` = manuell beenden), @@ -136,6 +140,19 @@ tests/ PHPUnit; PlenarioTestTrait erzeugt Testdaten, Fixtures Iframes brauchen `referrerpolicy="strict-origin"`, weil Admin-Seiten `no-referrer` senden und YouTube ohne Referrer nicht abspielt (nur Origin, nie der Pfad mit Token). Tests mocken YouTube über `HttpClientTrait` (`mockClientGet`). +- **Pause:** `current_slide_id = null` + `paused_slide_id` = Pause (Teilnehmende sehen „Kurze Pause“), ohne + `paused_slide_id` = noch nicht gestartet. Immer über `Poll::showSlide()` / `showEmbeddedSlide()` / `pause()` setzen, + nie `current_slide_id` direkt. Presenter: P pausiert, ←/→ setzt bei der pausierten Folie fort. +- **Einbettung** (`/e/{key}/{id}`, `EmbedController`): eigener `embed_key` statt Admin-Token (darf nur diese Folie zeigen, + live schalten, pausieren und `SlideControlService`-Aktionen), wird beim ersten Dashboard-Aufruf erzeugt + (`ensureEmbedKey`, idempotent) und lässt sich neu erzeugen. Die Seite schaltet sich live, solange sie sichtbar ist + (IntersectionObserver + `visibilitychange`), sendet Heartbeats und beim Verschwinden `pause` (sendBeacon). + `pause` wirkt nur, wenn die eigene Folie noch live ist; `heartbeat` holt keine Folie zurück, die im Presenter + gewechselt wurde. Bleiben Heartbeats aus (`Plenario.embed.timeoutSeconds`), pausiert `PollsTable::pauseIfEmbedStale()` + beim nächsten State-Abruf. Embed-Routen haben **keinen CSRF-Check** (Third-Party-Iframe ohne Cookies, der Schlüssel + ist die Berechtigung, siehe `Application::middleware()`) und erlauben Framing per CSP `frame-ancestors` + (`EMBED_FRAME_ANCESTORS`); alle anderen Seiten bleiben `X-Frame-Options: SAMEORIGIN`. + ### Neuen Folientyp hinzufügen (Checkliste) 1. Konstante + Label + Beschreibung + `DEFAULT_SETTINGS` in `src/Model/Entity/Slide.php` diff --git a/config/.env.example b/config/.env.example index 243de31..87cd847 100644 --- a/config/.env.example +++ b/config/.env.example @@ -36,3 +36,8 @@ THROTTLE_CREATE_PER_HOUR=10 THROTTLE_RECOVER_PER_HOUR=5 # How often presenter and participant pages poll for updates (ms) POLL_INTERVAL_MS=2000 +# Embedded slides (/e/{key}/{slide}, e.g. Canva): heartbeat interval and timeout until pause (s) +EMBED_HEARTBEAT_SECONDS=5 +EMBED_TIMEOUT_SECONDS=20 +# CSP frame-ancestors of embed pages, e.g. "https://*.canva.com https://*.iframe.ly" ('*' = any site) +EMBED_FRAME_ANCESTORS=* diff --git a/config/Migrations/20261107150000_AddEmbedToPolls.php b/config/Migrations/20261107150000_AddEmbedToPolls.php new file mode 100644 index 0000000..ec78029 --- /dev/null +++ b/config/Migrations/20261107150000_AddEmbedToPolls.php @@ -0,0 +1,29 @@ +table('polls') + ->addColumn('embed_key', 'string', ['limit' => 64, 'null' => true, 'default' => null, 'after' => 'join_code']) + ->addColumn('embed_seen_at', 'datetime', ['null' => true, 'default' => null, 'after' => 'current_slide_id']) + ->addColumn('paused_slide_id', 'integer', ['null' => true, 'default' => null, 'after' => 'embed_seen_at']) + ->addIndex(['embed_key'], ['unique' => true]) + ->update(); + } +} diff --git a/config/app.php b/config/app.php index 7d776f2..7e27c73 100644 --- a/config/app.php +++ b/config/app.php @@ -40,6 +40,15 @@ return [ 'recoverPerHour' => (int)env('THROTTLE_RECOVER_PER_HOUR', 5), ], 'pollIntervalMs' => (int)env('POLL_INTERVAL_MS', 2000), + // Slides embedded in other presentation software (/e/{key}/{slide}, e.g. Canva). + 'embed' => [ + // A visible embedded slide reports every N seconds that it is still on screen ... + 'heartbeatSeconds' => (int)env('EMBED_HEARTBEAT_SECONDS', 5), + // ... without a report for this long, the poll is paused (presentation moved on / closed). + 'timeoutSeconds' => (int)env('EMBED_TIMEOUT_SECONDS', 20), + // CSP frame-ancestors of the embed pages ('*' = any site; the URL itself is the secret). + 'frameAncestors' => (string)env('EMBED_FRAME_ANCESTORS', '*'), + ], ], /* diff --git a/config/routes.php b/config/routes.php index b8522c0..1775391 100644 --- a/config/routes.php +++ b/config/routes.php @@ -38,6 +38,20 @@ return function (RouteBuilder $routes): void { ->setPass(['code']) ->setMethods(['POST']); + // --- embedded slides (secret embed key, e.g. Canva) ----------------- + // No CSRF check here (see Application::middleware()): runs in third-party iframes + // without cookies, the key in the URL is the authorisation. + $builder->scope('/e/{key}/{id}', function (RouteBuilder $embed): void { + $patterns = ['key' => '[A-Za-z0-9_-]{20,64}', 'id' => '\d+']; + + $embed->connect('/', 'Embed::view', ['_name' => 'embed'])->setPatterns($patterns); + $embed->connect('/state', 'Embed::state', ['_name' => 'embed:state'])->setPatterns($patterns); + foreach (['activate', 'heartbeat', 'pause', 'control'] as $action) { + $embed->connect('/' . $action, 'Embed::' . $action, ['_name' => 'embed:' . $action]) + ->setPatterns($patterns)->setMethods(['POST']); + } + }); + // --- admin (secret token) ----------------------------------------- $builder->scope('/admin/{token}', function (RouteBuilder $admin): void { $token = ['token' => '[A-Za-z0-9_-]{20,64}', 'id' => '\d+']; @@ -47,6 +61,8 @@ return function (RouteBuilder $routes): void { ->setPatterns($token)->setMethods(['POST']); $admin->connect('/rotate-token', 'Admin::rotateToken', ['_name' => 'admin:rotate']) ->setPatterns($token)->setMethods(['POST']); + $admin->connect('/rotate-embed-key', 'Admin::rotateEmbedKey', ['_name' => 'admin:rotate-embed']) + ->setPatterns($token)->setMethods(['POST']); $admin->connect('/delete', 'Admin::delete', ['_name' => 'admin:delete']) ->setPatterns($token)->setMethods(['POST']); $admin->connect('/present', 'Admin::present', ['_name' => 'admin:present'])->setPatterns($token); diff --git a/src/Application.php b/src/Application.php index 98ef0b9..c925801 100644 --- a/src/Application.php +++ b/src/Application.php @@ -29,6 +29,7 @@ use Cake\Http\MiddlewareQueue; use Cake\ORM\Locator\TableLocator; use Cake\Routing\Middleware\AssetMiddleware; use Cake\Routing\Middleware\RoutingMiddleware; +use Psr\Http\Message\ServerRequestInterface; /** * Application setup class. @@ -93,9 +94,15 @@ class Application extends BaseApplication // Cross Site Request Forgery (CSRF) Protection Middleware // https://book.cakephp.org/5/en/security/csrf.html#cross-site-request-forgery-csrf-middleware - ->add(new CsrfProtectionMiddleware([ + ->add((new CsrfProtectionMiddleware([ 'httponly' => true, - ])); + ]))->skipCheckCallback( + // Embedded slides run in third-party iframes (no cookies); the secret key is the authorisation. + fn(ServerRequestInterface $request): bool => (bool)preg_match( + '/^embed(:|$)/', + (string)($request->getAttribute('params')['_name'] ?? ''), + ), + )); return $middlewareQueue; } diff --git a/src/Controller/AdminController.php b/src/Controller/AdminController.php index 0467b5b..625a1c5 100644 --- a/src/Controller/AdminController.php +++ b/src/Controller/AdminController.php @@ -9,6 +9,7 @@ use App\Model\Table\ResponsesTable; use App\Model\Table\SlidesTable; use App\Service\PollStateService; use App\Service\QaService; +use App\Service\SlideControlService; use App\Service\VoteService; use Cake\Core\Configure; use Cake\Http\Exception\BadRequestException; @@ -55,8 +56,10 @@ class AdminController extends AdminAppController $typeLabels = Slide::typeLabels(); $typeDescriptions = Slide::typeDescriptions(); $joinUrl = Router::url(['_name' => 'participate', 'code' => $this->poll->join_code], true); + // Created on first visit, so every slide has its embed URL ready to copy. + $embedKey = $this->Polls->ensureEmbedKey($this->poll); - $this->set(compact('slides', 'responseCounts', 'typeLabels', 'typeDescriptions', 'joinUrl')); + $this->set(compact('slides', 'responseCounts', 'typeLabels', 'typeDescriptions', 'joinUrl', 'embedKey')); } /** @@ -102,6 +105,20 @@ class AdminController extends AdminAppController return $this->redirect($this->adminUrl()); } + /** + * New embed key: all embed URLs (e.g. in Canva) stop working and must be inserted again. + * + * @return \Cake\Http\Response|null + */ + public function rotateEmbedKey(): ?Response + { + $this->request->allowMethod(['post']); + $this->Polls->rotateEmbedKey($this->poll); + $this->Flash->success(__('Neue Einbett-Links erstellt. Die bisherigen Links funktionieren nicht mehr – füge die neuen in deine Präsentation ein.')); + + return $this->redirect($this->adminUrl() + ['#' => 'embed']); + } + /** * Deletes the whole poll incl. slides and responses. * @@ -130,13 +147,13 @@ class AdminController extends AdminAppController */ public function present(): void { - if ($this->poll->current_slide_id === null) { + if ($this->poll->current_slide_id === null && !$this->poll->isPaused()) { $first = $this->Slides->find() ->where(['poll_id' => $this->poll->id]) ->orderBy(['position' => 'ASC', 'id' => 'ASC']) ->first(); if ($first !== null) { - $this->poll->current_slide_id = $first->id; + $this->poll->showSlide($first->id); $this->Polls->saveOrFail($this->poll); } } @@ -159,11 +176,12 @@ class AdminController extends AdminAppController /** * Presenter controls. Field `action`: - * goto (+ slide_id), next, prev, open, close, toggle, stop, - * Q&A: stage (+ stage: collect|vote|discuss), question (+ step: 1|-1) + * goto (+ slide_id), next, prev, stop (pause), and the slide actions of + * 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), toggle switches to the next stage. + * first (like builds in presentation software). While paused, next/prev resume + * the slide that was live before. * * Answers with the new state as JSON for XHR requests, otherwise redirects back. * @@ -177,68 +195,51 @@ class AdminController extends AdminAppController $ids = array_map(fn(Slide $s) => $s->id, $slides); $index = array_search($this->poll->current_slide_id, $ids, true); $current = $index === false ? null : $slides[$index]; - $qa = new QaService(); - if ($current !== null && $current->isQa()) { - if ($action === 'toggle') { - // No-op while discussing (last stage). - $qa->advance($current); - $action = 'none'; - } elseif (in_array($action, ['next', 'prev'], true) && $qa->moveFocus($current, $action === 'next' ? 1 : -1)) { - $action = 'none'; - } + if ( + $current !== null + && $current->isQa() + && in_array($action, ['next', 'prev'], true) + && (new QaService())->moveFocus($current, $action === 'next' ? 1 : -1) + ) { + $action = 'none'; } switch ($action) { case 'none': break; - case 'stage': - case 'question': - if ($current === null || !$current->isQa()) { - throw new BadRequestException('Not a Q&A slide'); - } - if ($action === 'question') { - $qa->moveFocus($current, (int)$this->request->getData('step') < 0 ? -1 : 1); - break; - } - $stage = (string)$this->request->getData('stage'); - if (!in_array($stage, Slide::QA_STAGES, true)) { - throw new BadRequestException('Unknown stage'); - } - $qa->setStage($current, $stage); - break; case 'goto': $target = (int)$this->request->getData('slide_id'); if (!in_array($target, $ids, true)) { throw new BadRequestException('Unknown slide'); } - $this->poll->current_slide_id = $target; + $this->poll->showSlide($target); break; case 'next': case 'prev': - if ($ids !== []) { - $index = $index === false ? 0 : $index + ($action === 'next' ? 1 : -1); - $this->poll->current_slide_id = $ids[max(0, min(count($ids) - 1, $index))]; + if ($ids === []) { + break; } + if ($index === false && in_array($this->poll->paused_slide_id, $ids, true)) { + $this->poll->showSlide((int)$this->poll->paused_slide_id); + break; + } + $index = $index === false ? 0 : $index + ($action === 'next' ? 1 : -1); + $this->poll->showSlide($ids[max(0, min(count($ids) - 1, $index))]); break; case 'stop': - $this->poll->current_slide_id = null; - break; - case 'open': - case 'close': - case 'toggle': - if ($index !== false) { - // Opening a quiz (re)starts its timer, see Slide::setVotingOpen(). - $slide = $slides[$index]; - $slide->setVotingOpen(match ($action) { - 'open' => true, - 'close' => false, - default => !$slide->isVotingOpen(), - }); - $this->Slides->saveOrFail($slide); - } + $this->poll->pause(); break; default: - throw new BadRequestException('Unknown action'); + if (!in_array($action, SlideControlService::ACTIONS, true)) { + throw new BadRequestException('Unknown action'); + } + if ($current === null) { + if (in_array($action, ['stage', 'question'], true)) { + throw new BadRequestException('Not a Q&A slide'); + } + break; + } + (new SlideControlService())->apply($current, $action, (array)$this->request->getData()); } $this->Polls->saveOrFail($this->poll); diff --git a/src/Controller/EmbedController.php b/src/Controller/EmbedController.php new file mode 100644 index 0000000..d979e24 --- /dev/null +++ b/src/Controller/EmbedController.php @@ -0,0 +1,223 @@ +fetchTable('Polls'); + $this->Polls = $polls; + /** @var \App\Model\Table\SlidesTable $slides */ + $slides = $this->fetchTable('Slides'); + $this->Slides = $slides; + } + + /** + * @param \Cake\Event\EventInterface<\Cake\Controller\Controller> $event Event + * @return void + */ + public function beforeFilter(EventInterface $event): void + { + parent::beforeFilter($event); + + /** @var \App\Model\Entity\Poll|null $poll */ + $poll = $this->Polls->find('byEmbedKey', key: (string)$this->request->getParam('key'))->first(); + /** @var \App\Model\Entity\Slide|null $slide */ + $slide = $poll === null ? null : $this->Slides->find() + ->where(['Slides.id' => (int)$this->request->getParam('id'), 'Slides.poll_id' => $poll->id]) + ->contain(['SlideOptions']) + ->first(); + if ($poll === null || $slide === null) { + throw new NotFoundException(__('Diese eingebettete Folie gibt es nicht (mehr).')); + } + $this->poll = $poll; + $this->slide = $slide; + } + + /** + * Like admin pages: never leak the key as referrer, never index or cache. + * Unlike everything else, framing by other sites is allowed. + * + * @param \Cake\Event\EventInterface<\Cake\Controller\Controller> $event Event + * @return void + */ + public function beforeRender(EventInterface $event): void + { + parent::beforeRender($event); + $this->response = $this->protect($this->response) + ->withoutHeader('X-Frame-Options') + ->withHeader('Content-Security-Policy', 'frame-ancestors ' . $this->frameAncestors()); + } + + /** + * @return void + */ + public function view(): void + { + $urls = []; + foreach (['state', 'activate', 'heartbeat', 'pause', 'control'] as $name) { + $urls[$name] = Router::url($this->embedUrl('embed:' . $name)); + } + $this->viewBuilder()->setLayout('present'); + $this->set('poll', $this->poll); + $this->set('slide', $this->slide); + $this->set('urls', $urls); + $this->set('joinBaseUrl', Router::url(['_name' => 'join:short'], true)); + $this->set('pollIntervalMs', (int)Configure::read('Plenario.pollIntervalMs', 2000)); + $this->set('heartbeatMs', max(1, (int)Configure::read('Plenario.embed.heartbeatSeconds', 5)) * 1000); + } + + /** + * @return \Cake\Http\Response + */ + public function state(): Response + { + return $this->stateResponse(); + } + + /** + * The embed became visible: this slide goes live. Idempotent. + * + * @return \Cake\Http\Response + */ + public function activate(): Response + { + $this->request->allowMethod(['post']); + if ($this->poll->is_active) { + $this->poll->showEmbeddedSlide($this->slide->id); + $this->Polls->saveOrFail($this->poll); + } + + return $this->stateResponse(); + } + + /** + * Still visible: keeps the slide live – but never takes it back when the + * presenter has switched to another slide in Plenario in the meantime. + * + * @return \Cake\Http\Response + */ + public function heartbeat(): Response + { + $this->request->allowMethod(['post']); + if ($this->poll->current_slide_id === $this->slide->id && $this->poll->embed_seen_at !== null) { + $this->poll->showEmbeddedSlide($this->slide->id); + $this->Polls->saveOrFail($this->poll); + } + + return $this->stateResponse(); + } + + /** + * The embed disappeared: pause, but only if this slide is still the live one + * (the next embedded slide may already have taken over). Idempotent. + * + * @return \Cake\Http\Response + */ + public function pause(): Response + { + $this->request->allowMethod(['post']); + if ($this->poll->current_slide_id === $this->slide->id) { + $this->poll->pause(); + $this->Polls->saveOrFail($this->poll); + } + + return $this->stateResponse(); + } + + /** + * Voting / quiz / Q&A controls of this slide (see SlideControlService). + * + * @return \Cake\Http\Response + */ + public function control(): Response + { + $this->request->allowMethod(['post']); + $action = (string)$this->request->getData('action'); + if (!in_array($action, SlideControlService::ACTIONS, true)) { + throw new BadRequestException('Unknown action'); + } + (new SlideControlService())->apply($this->slide, $action, (array)$this->request->getData()); + + return $this->stateResponse(); + } + + /** + * @return \Cake\Http\Response + */ + protected function stateResponse(): Response + { + return $this->protect($this->json((new PollStateService())->forEmbed($this->poll, $this->slide))); + } + + /** + * @param \Cake\Http\Response $response Response + * @return \Cake\Http\Response + */ + protected function protect(Response $response): Response + { + return $response + ->withHeader('Referrer-Policy', 'no-referrer') + ->withHeader('X-Robots-Tag', 'noindex, nofollow') + ->withHeader('Cache-Control', 'no-store, private'); + } + + /** + * @param string $name Route name + * @return array + */ + protected function embedUrl(string $name): array + { + return ['_name' => $name, 'key' => (string)$this->poll->embed_key, 'id' => $this->slide->id]; + } + + /** + * @return string CSP source list; falls back to 'self' for anything unexpected + */ + protected function frameAncestors(): string + { + $value = trim((string)Configure::read('Plenario.embed.frameAncestors', '*')); + + return preg_match('#^[A-Za-z0-9*:/.\' -]+$#', $value) ? $value : "'self'"; + } +} diff --git a/src/Model/Entity/Poll.php b/src/Model/Entity/Poll.php index 76e7eb6..e7bfc81 100644 --- a/src/Model/Entity/Poll.php +++ b/src/Model/Entity/Poll.php @@ -3,6 +3,7 @@ declare(strict_types=1); namespace App\Model\Entity; +use Cake\I18n\DateTime; use Cake\ORM\Entity; /** @@ -12,7 +13,10 @@ use Cake\ORM\Entity; * @property string $admin_token_hash * @property string $admin_token_encrypted * @property string $join_code + * @property string|null $embed_key * @property int|null $current_slide_id + * @property \Cake\I18n\DateTime|null $embed_seen_at + * @property int|null $paused_slide_id * @property bool $is_active * @property bool $show_results_to_participants * @property \Cake\I18n\DateTime|null $last_admin_access @@ -44,6 +48,7 @@ class Poll extends Entity 'admin_token_hash', 'admin_token_encrypted', 'email', + 'embed_key', ]; /** @@ -55,4 +60,52 @@ class Poll extends Entity { return trim(chunk_split($this->join_code, 3, ' ')); } + + /** + * Shows a slide to the participants (from Plenario itself: no embed timeout). + * + * @param int $slideId Slide id (must belong to this poll, checked by the caller) + * @return void + */ + public function showSlide(int $slideId): void + { + $this->current_slide_id = $slideId; + $this->paused_slide_id = null; + $this->embed_seen_at = null; + } + + /** + * Shows a slide because its embedded page (e.g. in Canva) became visible. + * It stays live only as long as the page keeps sending heartbeats. + * + * @param int $slideId Slide id + * @return void + */ + public function showEmbeddedSlide(int $slideId): void + { + $this->showSlide($slideId); + $this->embed_seen_at = DateTime::now(); + } + + /** + * No slide live: participants see the pause page. Idempotent. + * + * @return void + */ + public function pause(): void + { + if ($this->current_slide_id !== null) { + $this->paused_slide_id = $this->current_slide_id; + } + $this->current_slide_id = null; + $this->embed_seen_at = null; + } + + /** + * @return bool Paused after a slide had been live (not: not started yet) + */ + public function isPaused(): bool + { + return $this->current_slide_id === null && $this->paused_slide_id !== null; + } } diff --git a/src/Model/Table/PollsTable.php b/src/Model/Table/PollsTable.php index f460308..d51485a 100644 --- a/src/Model/Table/PollsTable.php +++ b/src/Model/Table/PollsTable.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace App\Model\Table; use App\Model\Entity\Poll; +use Cake\Core\Configure; use Cake\ORM\Query\SelectQuery; use Cake\ORM\RulesChecker; use Cake\ORM\Table; @@ -230,4 +231,82 @@ class PollsTable extends Table { return $query->where(['Polls.join_code' => static::normalizeJoinCode($code)]); } + + /** + * @param \Cake\ORM\Query\SelectQuery $query Query + * @param string $key Embed key + * @return \Cake\ORM\Query\SelectQuery + */ + public function findByEmbedKey(SelectQuery $query, string $key): SelectQuery + { + // Never match polls without key (null) and never compare against an empty string. + return $query->where(['Polls.embed_key' => $key === '' ? '-' : $key]); + } + + /** + * Creates the embed key on first use; keeps an existing one (idempotent). + * + * @param \App\Model\Entity\Poll $poll Poll + * @return string + */ + public function ensureEmbedKey(Poll $poll): string + { + if ($poll->embed_key === null || $poll->embed_key === '') { + return $this->rotateEmbedKey($poll); + } + + return $poll->embed_key; + } + + /** + * New embed key, all previous embed URLs stop working. + * + * @param \App\Model\Entity\Poll $poll Poll + * @return string + */ + public function rotateEmbedKey(Poll $poll): string + { + // Only the key column, so the rest of the entity (e.g. live slide) is not overwritten. + $key = static::generateToken(); + $this->updateAll(['embed_key' => $key], ['id' => $poll->id]); + $poll->embed_key = $key; + $poll->setDirty('embed_key', false); + + return $key; + } + + /** + * Pauses the poll when the embedded slide that made itself live has stopped reporting + * (presentation moved on to a non-Plenario slide, or was closed without a pause beacon). + * Called lazily whenever the state is read, like SlidesTable::closeIfExpired(). + * + * @param \App\Model\Entity\Poll $poll Poll + * @return \App\Model\Entity\Poll + */ + public function pauseIfEmbedStale(Poll $poll): Poll + { + $timeout = max(1, (int)Configure::read('Plenario.embed.timeoutSeconds', 20)); + if ( + $poll->embed_seen_at === null + || $poll->current_slide_id === null + || $poll->embed_seen_at->wasWithinLast($timeout . ' seconds') + ) { + return $poll; + } + + // Conditional update: a concurrent heartbeat or slide change wins. + $this->updateAll( + ['current_slide_id' => null, 'paused_slide_id' => $poll->current_slide_id, 'embed_seen_at' => null], + ['id' => $poll->id, 'current_slide_id' => $poll->current_slide_id, 'embed_seen_at' => $poll->embed_seen_at], + ); + + /** @var \App\Model\Entity\Poll $fresh */ + $fresh = $this->get($poll->id); + foreach (['current_slide_id', 'paused_slide_id', 'embed_seen_at'] as $field) { + $poll->set($field, $fresh->get($field)); + $poll->setDirty($field, false); + } + + return $poll; + } } diff --git a/src/Service/PollStateService.php b/src/Service/PollStateService.php index d3a8f3b..3f183f6 100644 --- a/src/Service/PollStateService.php +++ b/src/Service/PollStateService.php @@ -5,6 +5,7 @@ namespace App\Service; use App\Model\Entity\Poll; use App\Model\Entity\Slide; +use App\Model\Table\PollsTable; use App\Model\Table\ResponsesTable; use App\Model\Table\SlidesTable; use Cake\ORM\Locator\LocatorAwareTrait; @@ -33,6 +34,8 @@ class PollStateService protected ResponsesTable $Responses; + protected PollsTable $Polls; + protected ResultsService $results; /** @@ -46,6 +49,9 @@ class PollStateService /** @var \App\Model\Table\ResponsesTable $responses */ $responses = $this->fetchTable('Responses'); $this->Responses = $responses; + /** @var \App\Model\Table\PollsTable $polls */ + $polls = $this->fetchTable('Polls'); + $this->Polls = $polls; $this->results = new ResultsService(); } @@ -55,6 +61,7 @@ class PollStateService */ public function currentSlide(Poll $poll): ?Slide { + $this->Polls->pauseIfEmbedStale($poll); if ($poll->current_slide_id === null) { return null; } @@ -74,6 +81,7 @@ class PollStateService */ public function forPresenter(Poll $poll): array { + $this->Polls->pauseIfEmbedStale($poll); $slides = $this->Slides->listForPoll($poll->id); $current = null; $index = null; @@ -90,6 +98,7 @@ class PollStateService 'joinCode' => $poll->join_code, 'joinCodeFormatted' => $poll->formattedJoinCode(), 'isActive' => $poll->is_active, + 'isPaused' => $poll->isPaused(), ], 'slides' => array_map(fn(Slide $s) => [ 'id' => $s->id, @@ -103,6 +112,35 @@ class PollStateService ]; } + /** + * State of one embedded slide (/e/{key}/{slide}/state). Same shape as forPresenter(), + * but always for this slide, live or not, plus `isLive`. Never contains the slide list. + * + * @param \App\Model\Entity\Poll $poll Poll + * @param \App\Model\Entity\Slide $slide Slide of this poll incl. slide_options + * @return array + */ + public function forEmbed(Poll $poll, Slide $slide): array + { + $this->Polls->pauseIfEmbedStale($poll); + $slide = $this->Slides->closeIfExpired($slide); + + return [ + 'poll' => [ + 'title' => $poll->title, + 'joinCode' => $poll->join_code, + 'joinCodeFormatted' => $poll->formattedJoinCode(), + 'isActive' => $poll->is_active, + 'isPaused' => $poll->isPaused(), + ], + 'isLive' => $poll->current_slide_id === $slide->id, + 'index' => null, + 'count' => null, + 'slide' => $this->slidePayload($slide), + 'results' => $this->results->forSlide($slide), + ]; + } + /** * @param \App\Model\Entity\Poll $poll Poll * @param string $participantHash Participant hash @@ -131,6 +169,7 @@ class PollStateService return [ 'isActive' => $poll->is_active, + 'isPaused' => $slide === null && $poll->isPaused(), 'slideId' => $slide?->id, 'isVotingOpen' => $isVotingOpen, 'hasResponded' => $hasResponded, diff --git a/src/Service/SlideControlService.php b/src/Service/SlideControlService.php new file mode 100644 index 0000000..5123858 --- /dev/null +++ b/src/Service/SlideControlService.php @@ -0,0 +1,90 @@ +fetchTable('Slides'); + $this->Slides = $slides; + } + + /** + * @param \App\Model\Entity\Slide $slide Slide (belongs to the poll, checked by the caller) + * @param string $action One of self::ACTIONS + * @param array $data Request data (stage, step) + * @return void + * @throws \Cake\Http\Exception\BadRequestException + */ + public function apply(Slide $slide, string $action, array $data = []): void + { + $qa = new QaService(); + switch ($action) { + case 'stage': + case 'question': + if (!$slide->isQa()) { + throw new BadRequestException('Not a Q&A slide'); + } + if ($action === 'question') { + $qa->moveFocus($slide, (int)($data['step'] ?? 1) < 0 ? -1 : 1); + break; + } + $stage = (string)($data['stage'] ?? ''); + if (!in_array($stage, Slide::QA_STAGES, true)) { + throw new BadRequestException('Unknown stage'); + } + $qa->setStage($slide, $stage); + break; + case 'toggle': + if ($slide->isQa()) { + $qa->advance($slide); + break; + } + $this->setVotingOpen($slide, !$slide->isVotingOpen()); + break; + case 'open': + case 'close': + $this->setVotingOpen($slide, $action === 'open'); + break; + default: + throw new BadRequestException('Unknown action'); + } + } + + /** + * Opening a quiz (re)starts its timer, see Slide::setVotingOpen(). + * + * @param \App\Model\Entity\Slide $slide Slide + * @param bool $open Open or close + * @return void + */ + protected function setVotingOpen(Slide $slide, bool $open): void + { + $slide->setVotingOpen($open); + $this->Slides->saveOrFail($slide); + } +} diff --git a/templates/Admin/index.php b/templates/Admin/index.php index 9bdbce0..d1672d6 100644 --- a/templates/Admin/index.php +++ b/templates/Admin/index.php @@ -10,6 +10,7 @@ * @var array $typeLabels * @var array $typeDescriptions * @var string $joinUrl + * @var string $embedKey */ $this->assign('title', $poll->title); $this->assign('noindex', '1'); @@ -25,12 +26,22 @@ $url = fn(string $name, array $params = []) => ['_name' => $name, 'token' => $ad + isPaused()) : ?> + +

▶ + current_slide_id !== null) : ?> + Form->postLink('⏸ ' . __('Pause'), $url('admin:control'), [ + 'data' => ['action' => 'stop'], + 'class' => 'button', + 'title' => __('Keine Folie zeigen – Teilnehmende sehen eine Pause-Seite'), + ]) ?> +
@@ -97,6 +108,15 @@ $url = fn(string $name, array $params = []) => ['_name' => $name, 'token' => $ad $slide->slide_options, ))) ?>

+
+ +
+ + +
+
@@ -145,6 +165,17 @@ $url = fn(string $name, array $params = []) => ['_name' => $name, 'token' => $ad
+
+

+

+

+

+ Form->postLink(__('Neue Einbett-Links erzeugen'), $url('admin:rotate-embed'), [ + 'class' => 'button button--small', + 'confirm' => __('Neue Einbett-Links erzeugen? Alle bisher eingebetteten Folien funktionieren danach nicht mehr.'), + ]) ?> +
+

Form->create($poll, ['url' => $url('admin:settings'), 'type' => 'post']) ?> diff --git a/templates/Admin/present.php b/templates/Admin/present.php index 13a6be5..1ad65c2 100644 --- a/templates/Admin/present.php +++ b/templates/Admin/present.php @@ -3,7 +3,7 @@ * Presenter screen. Rendered empty and filled by webroot/js/plenario.js * (Plenario.presenter) from /admin/{token}/state. * - * Keyboard: ←/→ slides, V voting on/off, H hide results, F fullscreen, Q QR code, T light/dark. + * Keyboard: ←/→ slides, P pause (→ resumes), V voting on/off, H hide results, F fullscreen, Q QR code, T light/dark. * Q&A slides: V switches to the next stage; while discussing ←/→ step through the questions first. * * @var \App\View\AppView $this @@ -50,6 +50,10 @@ $host = preg_replace('#^https?://#', '', $joinBaseUrl); + diff --git a/templates/Embed/view.php b/templates/Embed/view.php new file mode 100644 index 0000000..385a430 --- /dev/null +++ b/templates/Embed/view.php @@ -0,0 +1,66 @@ + $urls state, activate, heartbeat, pause, control + * @var string $joinBaseUrl + * @var int $pollIntervalMs + * @var int $heartbeatMs + */ +$this->assign('title', $slide->question); +$host = preg_replace('#^https?://#', '', $joinBaseUrl); +?> +
+ +
+
+ + formattedJoinCode()) ?> +
+ +
+ +
+

+

question) ?>

+

+ +
+
+ +
+ + + + + element('theme_switch', [ + 'key' => 'plenario-theme-present', + 'modes' => 'dark,light', + 'class' => 'ctrl ctrl--wide', + 'shortcut' => 'T', + ]) ?> +
+
diff --git a/templates/Participate/view.php b/templates/Participate/view.php index 5e31cac..4f21cb7 100644 --- a/templates/Participate/view.php +++ b/templates/Participate/view.php @@ -41,6 +41,13 @@ $countdown = function (?int $remaining): string {

+ isPaused()) : ?> +
+ +

+

+
+
diff --git a/tests/TestCase/Controller/EmbedTest.php b/tests/TestCase/Controller/EmbedTest.php new file mode 100644 index 0000000..cebf60c --- /dev/null +++ b/tests/TestCase/Controller/EmbedTest.php @@ -0,0 +1,271 @@ + + */ + protected array $fixtures = ['app.Polls', 'app.Slides', 'app.SlideOptions', 'app.Responses']; + + /** + * @return array{0: \App\Model\Entity\Poll, 1: string, 2: string} poll, admin token, embed key + */ + protected function embeddedPoll(): array + { + [$poll, $token] = $this->createPoll(); + $key = $this->pollsTable()->ensureEmbedKey($poll); + + return [$poll, $token, $key]; + } + + /** + * POST without CSRF token, like the beacon / fetch from a third-party iframe. + * + * @return array + */ + protected function embedPost(string $key, Slide $slide, string $action, array $data = []): array + { + $this->configRequest(['headers' => ['Accept' => 'application/json']]); + $this->post("/e/$key/{$slide->id}/$action", $data); + $this->assertResponseOk(); + + return json_decode((string)$this->_response->getBody(), true); + } + + protected function reload(Poll $poll): Poll + { + return $this->pollsTable()->get($poll->id); + } + + public function testEnsureEmbedKeyIsIdempotent(): void + { + [$poll] = $this->createPoll(); + $key = $this->pollsTable()->ensureEmbedKey($poll); + + $this->assertSame($key, $this->pollsTable()->ensureEmbedKey($this->reload($poll))); + $this->assertNotSame($key, $this->pollsTable()->rotateEmbedKey($poll)); + } + + public function testUnknownKeyOrForeignSlideIs404(): void + { + [$poll, , $key] = $this->embeddedPoll(); + [$other] = $this->createPoll('Andere'); + $foreign = $this->createSlide($other); + $this->createSlide($poll); + + $this->get('/e/' . str_repeat('x', 43) . '/' . $foreign->id); + $this->assertResponseCode(404); + $this->get("/e/$key/{$foreign->id}"); + $this->assertResponseCode(404); + } + + public function testViewMayBeFramedAndHidesAdminToken(): void + { + [$poll, $token, $key] = $this->embeddedPoll(); + $slide = $this->createSlide($poll, Slide::TYPE_CHOICE, ['question' => 'Wie es?']); + + $this->get("/e/$key/{$slide->id}"); + + $this->assertResponseOk(); + $this->assertResponseContains('Wie <geht> es?'); + $this->assertResponseContains('data-embed'); + $this->assertResponseNotContains($token); + $this->assertHeader('Content-Security-Policy', 'frame-ancestors *'); + $this->assertNull($this->_response->getHeaderLine('X-Frame-Options') ?: null); + $this->assertHeader('Referrer-Policy', 'no-referrer'); + $this->assertNull($this->reload($poll)->current_slide_id, 'viewing alone does not go live'); + } + + public function testActivateWorksWithoutCsrfAndIsIdempotent(): void + { + [$poll, , $key] = $this->embeddedPoll(); + $slide = $this->createSlide($poll); + + $state = $this->embedPost($key, $slide, 'activate'); + $this->embedPost($key, $slide, 'activate'); + + $this->assertTrue($state['isLive']); + $this->assertSame($slide->id, $state['slide']['id']); + $this->assertArrayNotHasKey('slides', $state); + $poll = $this->reload($poll); + $this->assertSame($slide->id, $poll->current_slide_id); + $this->assertNotNull($poll->embed_seen_at); + } + + public function testCsrfIsStillCheckedOutsideEmbedRoutes(): void + { + [$poll, $token] = $this->embeddedPoll(); + $slide = $this->createSlide($poll); + + $this->post("/admin/$token/control", ['action' => 'goto', 'slide_id' => $slide->id]); + $this->assertResponseCode(403); + $this->post('/p/' . $poll->join_code . '/vote', ['slide_id' => $slide->id]); + $this->assertResponseCode(403); + } + + public function testActivateDoesNothingWhenPollIsClosed(): void + { + [$poll, , $key] = $this->embeddedPoll(); + $slide = $this->createSlide($poll); + $this->pollsTable()->updateAll(['is_active' => false], ['id' => $poll->id]); + + $state = $this->embedPost($key, $slide, 'activate'); + + $this->assertFalse($state['isLive']); + $this->assertNull($this->reload($poll)->current_slide_id); + } + + public function testPauseOnlyWhenOwnSlideIsLive(): void + { + [$poll, , $key] = $this->embeddedPoll(); + $first = $this->createSlide($poll); + $second = $this->createSlide($poll, Slide::TYPE_OPEN); + + // Canva moves from embed 1 to embed 2: the late pause beacon of 1 must not stop 2. + $this->embedPost($key, $first, 'activate'); + $this->embedPost($key, $second, 'activate'); + $this->embedPost($key, $first, 'pause'); + $this->assertSame($second->id, $this->reload($poll)->current_slide_id); + + $this->embedPost($key, $second, 'pause'); + $this->embedPost($key, $second, 'pause'); + $poll = $this->reload($poll); + $this->assertNull($poll->current_slide_id); + $this->assertSame($second->id, $poll->paused_slide_id); + $this->assertTrue($poll->isPaused()); + + $this->get('/p/' . $poll->join_code); + $this->assertResponseContains('Kurze Pause'); + $this->get('/p/' . $poll->join_code . '/state'); + $this->assertTrue(json_decode((string)$this->_response->getBody(), true)['isPaused']); + } + + public function testHeartbeatDoesNotTakeBackManuallyChosenSlide(): void + { + [$poll, $token, $key] = $this->embeddedPoll(); + $embedded = $this->createSlide($poll); + $other = $this->createSlide($poll, Slide::TYPE_OPEN); + $this->embedPost($key, $embedded, 'activate'); + + $this->enableCsrfToken(); + $this->post("/admin/$token/control", ['action' => 'goto', 'slide_id' => $other->id]); + $this->assertNull($this->reload($poll)->embed_seen_at, 'manual choice has no embed timeout'); + + $state = $this->embedPost($key, $embedded, 'heartbeat'); + $this->assertFalse($state['isLive']); + $this->assertSame($other->id, $this->reload($poll)->current_slide_id); + } + + public function testPollPausesWhenHeartbeatsStop(): void + { + [$poll, , $key] = $this->embeddedPoll(); + $slide = $this->createSlide($poll); + $this->embedPost($key, $slide, 'activate'); + $this->pollsTable()->updateAll(['embed_seen_at' => DateTime::now()->subMinutes(5)], ['id' => $poll->id]); + + $this->get('/p/' . $poll->join_code . '/state'); + $state = json_decode((string)$this->_response->getBody(), true); + + $this->assertNull($state['slideId']); + $this->assertTrue($state['isPaused']); + $poll = $this->reload($poll); + $this->assertNull($poll->current_slide_id); + $this->assertSame($slide->id, $poll->paused_slide_id); + } + + public function testFreshHeartbeatKeepsSlideLive(): void + { + [$poll, , $key] = $this->embeddedPoll(); + $slide = $this->createSlide($poll); + $this->embedPost($key, $slide, 'activate'); + $this->pollsTable()->updateAll(['embed_seen_at' => DateTime::now()->subMinutes(5)], ['id' => $poll->id]); + + $this->post("/e/$key/{$slide->id}/heartbeat"); + $this->get('/p/' . $poll->join_code . '/state'); + + $this->assertSame($slide->id, json_decode((string)$this->_response->getBody(), true)['slideId']); + } + + public function testControlStartsQuizButRejectsNavigation(): void + { + [$poll, , $key] = $this->embeddedPoll(); + $quiz = $this->createSlide($poll, Slide::TYPE_QUIZ, ['is_voting_open' => false], ['Richtig', 'Falsch']); + $this->embedPost($key, $quiz, 'activate'); + + $state = $this->embedPost($key, $quiz, 'control', ['action' => 'toggle']); + $this->assertSame('running', $state['results']['phase']); + $this->assertStringNotContainsString('correct', (string)$this->_response->getBody()); + + foreach (['next', 'goto', 'stop', 'delete'] as $action) { + $this->post("/e/$key/{$quiz->id}/control", ['action' => $action]); + $this->assertResponseCode(400, $action); + } + } + + public function testQaStageCanBeSwitchedFromEmbed(): void + { + [$poll, , $key] = $this->embeddedPoll(); + $qa = $this->createSlide($poll, Slide::TYPE_QA); + + $state = $this->embedPost($key, $qa, 'control', ['action' => 'stage', 'stage' => Slide::QA_VOTE]); + + $this->assertSame(Slide::QA_VOTE, $state['results']['stage']); + } + + public function testAdminPauseAndResume(): void + { + [$poll, $token] = $this->createPoll(); + $first = $this->createSlide($poll); + $second = $this->createSlide($poll, Slide::TYPE_OPEN); + $this->goLive($poll, $second); + $this->enableCsrfToken(); + + $this->post("/admin/$token/control", ['action' => 'stop']); + $this->assertTrue($this->reload($poll)->isPaused()); + + // Opening the presenter while paused keeps the pause. + $this->get("/admin/$token/present"); + $this->assertTrue($this->reload($poll)->isPaused()); + + // → resumes the slide that was live, not the next one / the first one. + $this->post("/admin/$token/control", ['action' => 'next']); + $poll = $this->reload($poll); + $this->assertSame($second->id, $poll->current_slide_id); + $this->assertNull($poll->paused_slide_id); + $this->assertNotSame($first->id, $poll->current_slide_id); + } + + public function testDashboardListsEmbedLinksAndRotationInvalidatesThem(): void + { + [$poll, $token] = $this->createPoll(); + $slide = $this->createSlide($poll); + + $this->get("/admin/$token"); + $key = (string)$this->reload($poll)->embed_key; + $this->assertNotSame('', $key); + $this->assertResponseContains("/e/$key/{$slide->id}"); + + $this->enableCsrfToken(); + $this->post("/admin/$token/rotate-embed-key"); + $this->assertRedirectContains("/admin/$token"); + + $this->get("/e/$key/{$slide->id}"); + $this->assertResponseCode(404); + } +} diff --git a/webroot/css/plenario.css b/webroot/css/plenario.css index 041f8ca..85e6654 100644 --- a/webroot/css/plenario.css +++ b/webroot/css/plenario.css @@ -238,6 +238,11 @@ textarea { resize: vertical; } .slide-item__meta { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; font-size: .85rem; margin-bottom: 4px; } .slide-item__title { font-weight: 600; color: var(--text); text-decoration: none; word-break: break-word; } .slide-item__options { margin: 4px 0 0; font-size: .85rem; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.slide-embed { margin-top: 6px; font-size: .85rem; } +.slide-embed summary { cursor: pointer; color: var(--muted); width: max-content; } +.slide-embed summary:hover { color: var(--text); } +.slide-embed .copy-field { margin-top: 6px; } +.slide-embed input { min-width: 0; flex: 1; } .slide-item__actions { display: flex; gap: 6px; flex-wrap: wrap; justify-content: flex-end; } @media (max-width: 700px) { .slide-item { grid-template-columns: auto minmax(0, 1fr); } @@ -530,6 +535,10 @@ body.present { @media (hover: none) and (pointer: coarse) { .ctrl__key { display: none; } /* touch devices usually have no keyboard */ } +.live-indicator { font-size: .8em; color: var(--muted); white-space: nowrap; } +.live-indicator.is-live { color: var(--c1); font-weight: 700; } +/* Embedded slides are smaller than a beamer: keep the controls visible, they are the only ones. */ +.stage--embed .stage__controls { opacity: .7; } .ctrl-counter { color: var(--muted); min-width: 64px; text-align: center; font-variant-numeric: tabular-nums; } .qr-overlay { position: fixed; inset: 0; background: var(--overlay-bg); display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 16px; cursor: zoom-out; z-index: 10; } diff --git a/webroot/js/plenario.js b/webroot/js/plenario.js index 2541d72..f0b1289 100644 --- a/webroot/js/plenario.js +++ b/webroot/js/plenario.js @@ -5,7 +5,8 @@ * - [data-copy] copy the value of the sibling [data-copy-source] * - [data-share] native share sheet (Web Share API), fallback: copy like [data-copy] * - [data-youtube-form] slide form: "Link prüfen" for YouTube slides (status + preview) - * - [data-presenter] presenter screen, polls /admin/{token}/state + * - [data-presenter] presenter screen, polls /admin/{token}/state; + * with [data-embed]: one embedded slide (/e/{key}/{id}), goes live while visible * - [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 @@ -761,6 +762,13 @@ var controlUrl = root.getAttribute('data-control-url'); var interval = parseInt(root.getAttribute('data-interval'), 10) || 2000; var q = function (selector) { return root.querySelector(selector); }; + var embedded = root.hasAttribute('data-embed'); + var setText = function (selector, text) { + var node = q(selector); + if (node) { + node.textContent = text; + } + }; var last = ''; var hideResults = false; var state = null; @@ -791,23 +799,32 @@ state = newState; var slide = state.slide; - q('[data-counter]').textContent = state.count === 0 + setText('[data-counter]', state.count === 0 ? '0 / 0' - : (state.index === null ? '–' : state.index + 1) + ' / ' + state.count; + : (state.index === null ? (state.poll.isPaused ? '⏸' : '–') : state.index + 1) + ' / ' + state.count); + var pauseButton = q('[data-action="stop"]'); + if (pauseButton) { + pauseButton.hidden = !slide; + } + if (embedded) { + renderLive(); + } if (!slide) { - q('[data-type]').textContent = ''; + q('[data-type]').textContent = state.poll.isPaused ? 'Pause' : ''; q('[data-question]').textContent = state.count === 0 ? 'Noch keine Folien angelegt' : state.poll.title; q('[data-description]').textContent = state.count === 0 ? 'Lege in der Verwaltung Fragen an.' - : 'Drücke → um zu starten.'; + : (state.poll.isPaused + ? 'Teilnehmende sehen gerade eine Pause-Seite. Drücke → zum Fortsetzen.' + : 'Drücke → um zu starten.'); q('[data-results]').innerHTML = ''; renderMedia(null); root.classList.remove('stage--video'); q('[data-voting]').hidden = true; - q('[data-participants]').textContent = ''; + setText('[data-participants]', ''); return; } @@ -834,9 +851,9 @@ : (slide.isVotingOpen ? 'Abstimmung schließen' : 'Abstimmung öffnen')); var count = qaStage ? state.results.questions.length : (slide.isInteractive ? state.results.participants : 0); - q('[data-participants]').textContent = !slide.isInteractive ? '' : (qaStage + setText('[data-participants]', !slide.isInteractive ? '' : (qaStage ? count + (count === 1 ? ' Frage' : ' Fragen') - : count + ' ' + (count === 1 ? 'Antwort' : 'Antworten')); + : count + ' ' + (count === 1 ? 'Antwort' : 'Antworten'))); var container = q('[data-results]'); container.classList.toggle('is-hidden', hideResults); @@ -865,10 +882,70 @@ function toggleHide() { hideResults = !hideResults; q('[data-results]').classList.toggle('is-hidden', hideResults); - q('[data-hide-results] [data-label]').textContent = hideResults ? 'Ergebnisse zeigen' : 'Ergebnisse verbergen'; + setText('[data-hide-results] [data-label]', hideResults ? 'Ergebnisse zeigen' : 'Ergebnisse verbergen'); } q('[data-hide-results]').addEventListener('click', toggleHide); + /* + * Embed mode: the slide goes live while the embed is really on screen (tab visible and + * at least half of it in the viewport - IntersectionObserver also sees through the + * iframes of the surrounding presentation), stays live with heartbeats, pauses when gone. + */ + var live = false; + function renderLive() { + var isLive = !!state.isLive; + var indicator = q('[data-live]'); + indicator.textContent = !state.poll.isActive + ? 'Umfrage geschlossen' + : (isLive ? '● live' : 'nicht live'); + indicator.classList.toggle('is-live', isLive); + q('[data-go-live]').hidden = isLive || !state.poll.isActive; + } + function goLive() { + live = true; + postJson(root.getAttribute('data-activate-url'), {}).then(render).catch(function () {}); + } + function leave() { + if (!live) { + return; + } + live = false; + var url = root.getAttribute('data-pause-url'); + // sendBeacon survives page unload; embed routes need no CSRF token. + if (!(navigator.sendBeacon && navigator.sendBeacon(url, new FormData()))) { + postJson(url, {}).catch(function () {}); + } + } + if (embedded) { + var inView = false; + var check = function () { + if (inView && document.visibilityState === 'visible') { + if (!live) { + goLive(); + } + } else { + leave(); + } + }; + if ('IntersectionObserver' in window) { + new IntersectionObserver(function (entries) { + inView = entries[entries.length - 1].intersectionRatio >= 0.5; + check(); + }, { threshold: [0, 0.5, 1] }).observe(root); + } else { + inView = true; + check(); + } + document.addEventListener('visibilitychange', check); + window.addEventListener('pagehide', leave); + q('[data-go-live]').addEventListener('click', goLive); + setInterval(function () { + if (live) { + postJson(root.getAttribute('data-heartbeat-url'), {}).then(render).catch(function () {}); + } + }, parseInt(root.getAttribute('data-heartbeat'), 10) || 5000); + } + function toggleFullscreen() { if (!document.fullscreenElement) { (document.documentElement.requestFullscreen || function () {}).call(document.documentElement); @@ -876,20 +953,33 @@ document.exitFullscreen(); } } - q('[data-fullscreen]').addEventListener('click', toggleFullscreen); + if (q('[data-fullscreen]')) { + q('[data-fullscreen]').addEventListener('click', toggleFullscreen); + } var overlay = q('[data-qr-overlay]'); function toggleQr() { - overlay.hidden = !overlay.hidden; + if (overlay) { + overlay.hidden = !overlay.hidden; + } + } + if (overlay) { + q('[data-qr-toggle]').addEventListener('click', toggleQr); + overlay.addEventListener('click', toggleQr); } - q('[data-qr-toggle]').addEventListener('click', toggleQr); - overlay.addEventListener('click', toggleQr); document.addEventListener('keydown', function (event) { if (event.target.closest('input, textarea, select')) { return; } + if (embedded && ['ArrowRight', 'ArrowLeft', 'PageUp', 'PageDown', ' ', 'p', 'P', 'f', 'F', 'q', 'Q'].indexOf(event.key) >= 0) { + return; // slide navigation belongs to the surrounding presentation + } switch (event.key) { + case 'p': + case 'P': + control('stop'); + break; case 'ArrowRight': case 'PageDown': case ' ': @@ -926,7 +1016,9 @@ } break; case 'Escape': - overlay.hidden = true; + if (overlay) { + overlay.hidden = true; + } break; } });