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