diff --git a/AGENTS.md b/AGENTS.md index 293c080..17f491b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -71,7 +71,8 @@ src/ 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) +webroot/js/plenario.js Vanilla JS: Polling, Ergebnis-Rendering, Presenter-Steuerung, Sortieren (`makeSortable`: Pointer Events + Pfeiltasten, + genutzt für Folienliste, Reihenfolge-Editor und Teilnehmer-Antwort) tests/ PHPUnit; PlenarioTestTrait erzeugt Testdaten, Fixtures sind leer ``` @@ -81,14 +82,16 @@ tests/ PHPUnit; PlenarioTestTrait erzeugt Testdaten, Fixtures `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`, +- `slides`: `type` (`choice|wordcloud|open|scale|content|quiz|youtube|qa|order`), `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), `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 +- `slide_options`: Antwortoptionen für `choice`, `quiz` und `order`; `is_correct` markiert richtige Quiz-Antworten, + bei `order` ist `position` die richtige Reihenfolge - `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). + Reihenfolge: eine Zeile pro Person, `text_value` = Options-ids kommagetrennt (`VoteService::parseOrder()`). ### Zentrale Regeln (nicht versehentlich brechen) @@ -140,6 +143,14 @@ 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`). +- Reihenfolge-Folie (`order`): Admin legt die Einträge in der richtigen Reihenfolge an (Formular `order_options[]`, Zeilen + per Drag & Drop/Pfeiltasten sortierbar, ids bleiben beim Umsortieren erhalten). Teilnehmende bekommen sie per + `Slide::shuffledOptions(participantHash)` gemischt (stabil, nie schon richtig), sortieren und senden `order[]` (alle ids genau einmal), + einmal pro Person. Startet offen wie normale Folien; **aufgelöst wird beim Schließen der Abstimmung** (`Slide::isOrderRevealed()`). + Vorher landen weder richtige Reihenfolge noch Zählungen im JSON (Presenter sieht die Einträge gemischt mit Seed `slide:{id}`); + danach sehen alle die Lösung inkl. „X von N komplett richtig“ und je Eintrag, wie oft er an der richtigen Stelle lag, Teilnehmende + zusätzlich `order.isCorrect` – unabhängig von `show_results_to_participants`. Tests: `OrderTest.php`, `OrderSlideTest.php`. + - **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. diff --git a/src/Controller/AdminController.php b/src/Controller/AdminController.php index 625a1c5..85ede6e 100644 --- a/src/Controller/AdminController.php +++ b/src/Controller/AdminController.php @@ -305,6 +305,7 @@ class AdminController extends AdminAppController foreach ($responses as $response) { $texts[$response->id] = (string)$response->text_value; $answer = match (true) { + $slide->isOrder() => $this->orderAnswer($slide, $labels, (string)$response->text_value), $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 @@ -335,6 +336,26 @@ class AdminController extends AdminAppController ->withStringBody($csv); } + /** + * Ordering answer for the CSV export, e.g. "A → C → B (falsch)". + * + * @param \App\Model\Entity\Slide $slide Ordering slide incl. slide_options + * @param array $labels Option labels by id + * @param string $text Stored answer (option ids) + * @return string + */ + protected function orderAnswer(Slide $slide, array $labels, string $text): string + { + $given = VoteService::parseOrder($text); + $correct = array_map(fn($option) => $option->id, array_values($slide->slide_options ?? [])); + + return __( + '{0} ({1})', + implode(' → ', array_map(fn(int $id) => $labels[$id] ?? '?', $given)), + $given === $correct ? __('richtig') : __('falsch'), + ); + } + /** * Prevents CSV/formula injection in spreadsheet programs. * diff --git a/src/Controller/ParticipateController.php b/src/Controller/ParticipateController.php index e6ed9d5..b0408c4 100644 --- a/src/Controller/ParticipateController.php +++ b/src/Controller/ParticipateController.php @@ -85,9 +85,10 @@ class ParticipateController extends AppController $poll = $this->loadPoll($code); $stateService = new PollStateService(); $slide = $poll->is_active ? $stateService->currentSlide($poll) : null; - $state = $stateService->forParticipant($poll, $this->participantHash($poll)); + $participantHash = $this->participantHash($poll); + $state = $stateService->forParticipant($poll, $participantHash); - $this->set(compact('poll', 'slide', 'state')); + $this->set(compact('poll', 'slide', 'state', 'participantHash')); $this->set('pollIntervalMs', (int)Configure::read('Plenario.pollIntervalMs', 2000)); } diff --git a/src/Controller/SlidesController.php b/src/Controller/SlidesController.php index dfe32de..7719ed0 100644 --- a/src/Controller/SlidesController.php +++ b/src/Controller/SlidesController.php @@ -49,10 +49,12 @@ class SlidesController extends AdminAppController $slide->stage = $type === Slide::TYPE_QA ? Slide::QA_COLLECT : null; $optionsText = $type === Slide::TYPE_CHOICE ? "\n" : ''; $quizOptions = []; + $orderOptions = []; if ($this->request->is('post')) { $optionsText = (string)$this->request->getData('options_text', ''); $quizOptions = $this->postedQuizOptions(); + $orderOptions = $this->postedOrderOptions(); if ($this->saveSlide($slide, $optionsText)) { $this->Flash->success(__('Folie angelegt.')); @@ -60,7 +62,7 @@ class SlidesController extends AdminAppController } } - $this->set(compact('slide', 'optionsText', 'quizOptions')); + $this->set(compact('slide', 'optionsText', 'quizOptions', 'orderOptions')); $this->render('form'); return null; @@ -75,10 +77,12 @@ class SlidesController extends AdminAppController $slide = $this->loadSlide($id); $optionsText = implode("\n", array_map(fn($o) => $o->label, $slide->slide_options ?? [])); $quizOptions = array_map(fn($o) => ['label' => $o->label, 'correct' => $o->is_correct], $slide->slide_options ?? []); + $orderOptions = array_map(fn($o) => $o->label, $slide->slide_options ?? []); if ($this->request->is(['post', 'put', 'patch'])) { $optionsText = (string)$this->request->getData('options_text', ''); $quizOptions = $this->postedQuizOptions(); + $orderOptions = $this->postedOrderOptions(); if ($this->saveSlide($slide, $optionsText)) { $this->Flash->success(__('Folie gespeichert.')); @@ -87,7 +91,7 @@ class SlidesController extends AdminAppController } $hasResponses = $this->Slides->Responses->exists(['slide_id' => $slide->id]); - $this->set(compact('slide', 'optionsText', 'quizOptions', 'hasResponses')); + $this->set(compact('slide', 'optionsText', 'quizOptions', 'orderOptions', 'hasResponses')); $this->render('form'); return null; @@ -215,6 +219,23 @@ class SlidesController extends AdminAppController return $rows; } + /** + * Item rows of an ordering slide as posted by the form (for re-rendering after errors). + * + * @return list + */ + protected function postedOrderOptions(): array + { + $rows = []; + foreach ((array)$this->request->getData('order_options', []) as $label) { + if (is_scalar($label)) { + $rows[] = (string)$label; + } + } + + return $rows; + } + /** * Patches and saves a slide incl. its options. * @@ -253,6 +274,16 @@ class SlidesController extends AdminAppController $slide->setError('quiz_options', __('Bitte markiere mindestens eine Antwort als richtig.')); } } + if ($slide->isOrder()) { + ['labels' => $labels, 'duplicate' => $duplicate] = SlidesTable::parseOrderOptions( + (array)$this->request->getData('order_options', []), + ); + if ($duplicate) { + $slide->setError('order_options', __('Jeder Eintrag darf nur einmal vorkommen, sonst ist die Reihenfolge nicht eindeutig.')); + } elseif (count($labels) < 2) { + $slide->setError('order_options', __('Bitte gib mindestens zwei Einträge an.')); + } + } if ($slide->hasErrors()) { $this->Flash->error(__('Bitte prüfe deine Eingaben.')); @@ -263,7 +294,7 @@ class SlidesController extends AdminAppController if (!$this->Slides->save($slide)) { return false; } - if ($slide->type === Slide::TYPE_CHOICE || $slide->isQuiz()) { + if ($slide->type === Slide::TYPE_CHOICE || $slide->isQuiz() || $slide->isOrder()) { $this->Slides->syncOptions($slide, $labels, $correct); } if ($youtube['warning'] !== null) { diff --git a/src/Model/Entity/Slide.php b/src/Model/Entity/Slide.php index 9c8cd1d..34df351 100644 --- a/src/Model/Entity/Slide.php +++ b/src/Model/Entity/Slide.php @@ -39,6 +39,7 @@ class Slide extends Entity public const TYPE_QUIZ = 'quiz'; public const TYPE_YOUTUBE = 'youtube'; public const TYPE_QA = 'qa'; + public const TYPE_ORDER = 'order'; /** * Quiz phases, see quizPhase(). @@ -91,6 +92,8 @@ class Slide extends Entity 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], + // The correct order is the order of the slide_options (position), revealed when voting closes. + self::TYPE_ORDER => [], ]; /** @@ -115,6 +118,7 @@ class Slide extends Entity self::TYPE_OPEN => __('Offene Frage'), self::TYPE_SCALE => __('Skala'), self::TYPE_QUIZ => __('Quiz'), + self::TYPE_ORDER => __('Reihenfolge'), self::TYPE_QA => __('Fragen & Antworten'), self::TYPE_CONTENT => __('Inhaltsfolie'), self::TYPE_YOUTUBE => __('YouTube-Video'), @@ -132,6 +136,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_ORDER => __('Einträge in die richtige Reihenfolge bringen, aufgelöst wird beim Schließen der Abstimmung.'), 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.'), @@ -233,6 +238,48 @@ class Slide extends Entity return $this->type === self::TYPE_QA; } + /** + * @return bool + */ + public function isOrder(): bool + { + return $this->type === self::TYPE_ORDER; + } + + /** + * Ordering slide whose solution may be shown: voting is closed. While voting + * is open, neither the correct order nor any counts may leave the server. + * + * @return bool + */ + public function isOrderRevealed(): bool + { + return $this->isOrder() && !$this->isVotingOpen(); + } + + /** + * Options of an ordering slide in a stable pseudo-random order (same seed = + * same order, e.g. per participant across reloads). With two or more options + * the result never equals the correct order. + * + * @param string $seed Seed, e.g. participant hash or "slide:{id}" + * @return list<\App\Model\Entity\SlideOption> + */ + public function shuffledOptions(string $seed): array + { + $options = array_values($this->slide_options ?? []); + $correct = array_map(fn($option) => $option->id, $options); + usort($options, fn($a, $b) => strcmp( + hash('sha256', $seed . '|' . $a->id), + hash('sha256', $seed . '|' . $b->id), + )); + if (count($options) > 1 && array_map(fn($option) => $option->id, $options) === $correct) { + $options[] = array_shift($options); + } + + return $options; + } + /** * Stage of a Q&A slide (one of the QA_* constants), see QaService. * diff --git a/src/Model/Table/SlidesTable.php b/src/Model/Table/SlidesTable.php index 464e1d6..436a7f7 100644 --- a/src/Model/Table/SlidesTable.php +++ b/src/Model/Table/SlidesTable.php @@ -23,6 +23,7 @@ class SlidesTable extends Table { public const MAX_OPTIONS = 20; public const MAX_QUIZ_OPTIONS = 10; + public const MAX_ORDER_OPTIONS = 10; /** * @param array $config The configuration for the Table. @@ -233,6 +234,32 @@ class SlidesTable extends Table return ['labels' => $labels, 'correct' => $correct]; } + /** + * Parses the item rows of an ordering slide (`order_options[]`, in the correct order). + * Empty rows are skipped; a repeated label is reported, because it would make the order ambiguous. + * + * @param array $rows Raw form rows (labels) + * @return array{labels: list, duplicate: bool} + */ + public static function parseOrderOptions(array $rows): array + { + $labels = []; + $duplicate = false; + foreach ($rows as $row) { + $label = is_scalar($row) ? mb_substr(trim((string)$row), 0, 255) : ''; + if ($label === '' || count($labels) >= self::MAX_ORDER_OPTIONS) { + continue; + } + if (in_array($label, $labels, true)) { + $duplicate = true; + continue; + } + $labels[] = $label; + } + + return ['labels' => $labels, 'duplicate' => $duplicate]; + } + /** * Persists the end of a timed quiz once its deadline has passed. Safe to * call repeatedly (no-op unless the slide is still flagged open). diff --git a/src/Service/PollStateService.php b/src/Service/PollStateService.php index 898f309..262b776 100644 --- a/src/Service/PollStateService.php +++ b/src/Service/PollStateService.php @@ -22,7 +22,8 @@ use Cake\ORM\Locator\LocatorAwareTrait; * Quiz slides reveal results (and the participant's own correctness) only * once the quiz is finished – then always, independent of * `show_results_to_participants`. Timed quizzes are closed lazily here - * when their deadline has passed. + * when their deadline has passed. Ordering slides work the same way: solution, + * counts and the participant's correctness (`order`) only once voting is closed. * * Q&A slides have their own participant view (`qa`, see qaState()), never `results`. * Private open questions (anonymous feedback) never show results to participants. @@ -153,6 +154,7 @@ class PollStateService $words = $slide?->type === Slide::TYPE_WORDCLOUD ? $this->wordState($slide, $participantHash) : null; $quiz = $slide?->isQuiz() ? $this->quizState($slide, $participantHash) : null; $qa = $slide?->isQa() ? $this->qaState($slide, $participantHash) : null; + $order = $slide?->isOrder() ? $this->orderState($slide, $participantHash) : null; $hasResponded = match (true) { $words !== null => $words['mine'] !== [] || $words['down'] !== [], $qa !== null => $qa['mine'] !== [] || $qa['upvoted'] !== [], @@ -164,8 +166,8 @@ class PollStateService && $slide->isInteractive() && $qa === null && !$slide->isPrivate() - && ($quiz !== null - ? $quiz['phase'] === Slide::QUIZ_FINISHED + && ($quiz !== null || $order !== null + ? ($quiz['phase'] ?? null) === Slide::QUIZ_FINISHED || ($order['revealed'] ?? false) : ($poll->show_results_to_participants && ($hasResponded || !$isVotingOpen)) || ($words !== null && $words['allowUpvotes'] && $isVotingOpen)); @@ -189,6 +191,35 @@ class PollStateService 'words' => $words, 'quiz' => $quiz, 'qa' => $qa, + 'order' => $order, + ]; + } + + /** + * Ordering progress of one participant. Own answer and correctness only once + * revealed (voting closed); before that the state must not hint at the solution. + * + * @param \App\Model\Entity\Slide $slide Ordering slide incl. slide_options + * @param string $participantHash Participant hash + * @return array{revealed: bool, answer: list|null, isCorrect: bool|null} + */ + public function orderState(Slide $slide, string $participantHash): array + { + $revealed = $slide->isOrderRevealed(); + $answer = null; + if ($revealed) { + $response = $this->Responses->find() + ->select(['text_value']) + ->where(['slide_id' => $slide->id, 'participant_hash' => $participantHash]) + ->first(); + $answer = $response === null ? null : VoteService::parseOrder($response->text_value); + } + $correct = array_map(fn($option) => $option->id, array_values($slide->slide_options ?? [])); + + return [ + 'revealed' => $revealed, + 'answer' => $answer, + 'isCorrect' => $answer === null ? null : $answer === $correct, ]; } diff --git a/src/Service/ResultsService.php b/src/Service/ResultsService.php index 52e53a3..6a2bbba 100644 --- a/src/Service/ResultsService.php +++ b/src/Service/ResultsService.php @@ -25,6 +25,11 @@ 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. + * - order: 'revealed' (bool, = voting closed); while not revealed 'items' => [['id', 'label']] + * in a fixed shuffled order (never the solution); once revealed 'items' in the correct + * order with 'position' (1-based), 'placed' (participants who put the item at its position), + * 'percent', plus 'correctCount' (participants with the completely correct order). + * Neither the correct order nor counts are part of the result before it is revealed. * - 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). @@ -66,10 +71,61 @@ class ResultsService Slide::TYPE_SCALE => $this->scale($slide), Slide::TYPE_QUIZ => $this->quiz($slide), Slide::TYPE_QA => $this->qa($slide), + Slide::TYPE_ORDER => $this->order($slide), default => [], }; } + /** + * @param \App\Model\Entity\Slide $slide Slide + * @return array + */ + protected function order(Slide $slide): array + { + if (!$slide->isOrderRevealed()) { + return [ + 'revealed' => false, + 'items' => array_map(fn($option) => [ + 'id' => $option->id, + 'label' => $option->label, + ], $slide->shuffledOptions('slide:' . $slide->id)), + ]; + } + + $correct = array_map(fn($option) => $option->id, array_values($slide->slide_options ?? [])); + $placed = array_fill_keys($correct, 0); + $correctCount = 0; + $answers = $this->Responses->find() + ->select(['text_value']) + ->where(['slide_id' => $slide->id, 'text_value IS NOT' => null]) + ->disableHydration() + ->all(); + foreach ($answers as $row) { + $given = VoteService::parseOrder($row['text_value']); + if ($given === $correct) { + $correctCount++; + } + foreach ($correct as $index => $id) { + if (($given[$index] ?? null) === $id) { + $placed[$id]++; + } + } + } + $total = count($answers); + $items = []; + foreach (array_values($slide->slide_options ?? []) as $index => $option) { + $items[] = [ + 'id' => $option->id, + 'label' => $option->label, + 'position' => $index + 1, + 'placed' => $placed[$option->id], + 'percent' => $total > 0 ? round($placed[$option->id] / $total * 100, 1) : 0, + ]; + } + + return ['revealed' => true, 'items' => $items, 'correctCount' => $correctCount]; + } + /** * @param \App\Model\Entity\Slide $slide Slide * @return array diff --git a/src/Service/VoteService.php b/src/Service/VoteService.php index deec40e..8ce070a 100644 --- a/src/Service/VoteService.php +++ b/src/Service/VoteService.php @@ -28,6 +28,8 @@ use Cake\Utility\Security; * 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. + * - ordering: `order` = all option ids, each exactly once, in the participant's order. + * Stored as one row with the ids comma separated in `text_value` (see parseOrder()). */ class VoteService { @@ -105,6 +107,7 @@ class VoteService Slide::TYPE_SCALE => $this->scaleRows($slide, $data), Slide::TYPE_QUIZ => $this->quizRows($slide, $data), Slide::TYPE_QA => $this->qaRows($slide, $participantHash, $data), + Slide::TYPE_ORDER => $this->orderRows($slide, $data), default => throw new VoteException(__('Unbekannter Folientyp.')), }; @@ -159,6 +162,51 @@ class VoteService return [['slide_option_id' => $id]]; } + /** + * @param \App\Model\Entity\Slide $slide Slide + * @param array $data Request data + * @return list> + */ + protected function orderRows(Slide $slide, array $data): array + { + $given = []; + foreach ((array)($data['order'] ?? []) as $id) { + $id = is_scalar($id) ? filter_var($id, FILTER_VALIDATE_INT) : false; + if ($id === false) { + $given = []; + break; + } + $given[] = $id; + } + $validIds = array_map(fn($option) => $option->id, $slide->slide_options ?? []); + $sortedGiven = $given; + sort($sortedGiven); + sort($validIds); + if ($validIds === [] || $sortedGiven !== $validIds) { + throw new VoteException(__('Bitte bring alle Einträge in eine Reihenfolge und sende sie erneut.')); + } + + return [['text_value' => implode(',', $given)]]; + } + + /** + * Option ids of a stored ordering answer (`responses.text_value`), in the participant's order. + * + * @param string|null $text Stored answer + * @return list + */ + public static function parseOrder(?string $text): array + { + $ids = []; + foreach (explode(',', (string)$text) as $id) { + if (ctype_digit(trim($id))) { + $ids[] = (int)$id; + } + } + + return $ids; + } + /** * Q&A: a new question while collecting, an upvote (or its withdrawal) while voting. * Withdrawing deletes one upvote row and returns no new rows. diff --git a/templates/Admin/index.php b/templates/Admin/index.php index b4c04f4..931aa36 100644 --- a/templates/Admin/index.php +++ b/templates/Admin/index.php @@ -96,6 +96,8 @@ $url = fn(string $name, array $params = []) => ['_name' => $name, 'token' => $ad 'vote' => __('Abstimmung läuft'), 'discuss' => __('Fragen werden besprochen'), ][$slide->qaStage()]) ?> · setting('max_upvotes'), (int)$slide->setting('max_upvotes')) ?> + isOrder() && !$slide->is_voting_open) : ?> + · is_voting_open) : ?>· isPrivate()) : ?>🔒 @@ -108,6 +110,11 @@ $url = fn(string $name, array $params = []) => ['_name' => $name, 'token' => $ad fn($o) => $o->is_correct ? '✓ ' . $o->label : $o->label, $slide->slide_options, ))) ?>

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

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

diff --git a/templates/Participate/view.php b/templates/Participate/view.php index f04cc1c..9dc101a 100644 --- a/templates/Participate/view.php +++ b/templates/Participate/view.php @@ -7,6 +7,7 @@ * @var \App\Model\Entity\Poll $poll * @var \App\Model\Entity\Slide|null $slide * @var array $state + * @var string $participantHash Seed for the shuffled items of ordering slides * @var int $pollIntervalMs */ $this->assign('title', $poll->title); @@ -15,6 +16,7 @@ $voteUrl = ['_name' => 'participate:vote', 'code' => $poll->join_code]; $words = $state['words'] ?? null; $quiz = $state['quiz'] ?? null; $qa = $state['qa'] ?? null; +$order = $state['order'] ?? null; $countdown = function (?int $remaining): string { if ($remaining === null) { return ''; @@ -125,6 +127,44 @@ $countdown = function (?int $remaining): string {

+ + +

✓

+ +

✗

+

+ +

+ +

✓

+

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

+ +
    + $option) : ?> +
  1. + + + + label) ?> + + + + +
  2. + +
+

+ Form->button(__('Reihenfolge einreichen'), ['class' => 'button button--primary button--block']) ?> + Form->end() ?> +
@@ -222,6 +262,7 @@ $countdown = function (?int $remaining): string {

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

is_voting_open) : ?> diff --git a/templates/Slides/form.php b/templates/Slides/form.php index b77559a..2aa1665 100644 --- a/templates/Slides/form.php +++ b/templates/Slides/form.php @@ -9,6 +9,7 @@ * @var \App\Model\Entity\Slide $slide * @var string $optionsText * @var list $quizOptions + * @var list $orderOptions Ordering slide: labels in the correct order * @var bool|null $hasResponses */ @@ -217,6 +218,39 @@ $optionsError = $slide->getError('options_text'); 'value' => $settings['time_limit'], ]) ?>

+ isOrder()) : + $orderError = $slide->getError('order_options'); + $max = \App\Model\Table\SlidesTable::MAX_ORDER_OPTIONS; + $rows = array_pad($orderOptions, min($max, max(4, count($orderOptions) + 1)), ''); + ?> +
+ +

+ +
    + $label) : ?> +
  1. + + + + + placeholder=""> +
  2. + +
+

+ + +
+ + +

+ +
+

type === 'qa') : $upvoteOptions = []; foreach (range(1, \App\Model\Entity\Slide::QA_MAX_UPVOTES) as $n) { diff --git a/tests/TestCase/Controller/OrderSlideTest.php b/tests/TestCase/Controller/OrderSlideTest.php new file mode 100644 index 0000000..8dd37ad --- /dev/null +++ b/tests/TestCase/Controller/OrderSlideTest.php @@ -0,0 +1,93 @@ + + */ + protected array $fixtures = ['app.Polls', 'app.Slides', 'app.SlideOptions', 'app.Responses']; + + protected function setUp(): void + { + parent::setUp(); + $this->enableCsrfToken(); + } + + public function testAddAndEditKeepTheEnteredOrder(): void + { + [$poll, $token] = $this->createPoll(); + $this->get("/admin/$token/slides/add?type=order"); + $this->assertResponseOk(); + $this->assertResponseContains('name="order_options[]"'); + $this->assertResponseContains('data-order-options'); + + $data = ['type' => 'order', 'question' => 'Sortiere nach Größe', 'is_voting_open' => '1']; + $this->post("/admin/$token/slides/add?type=order", $data + ['order_options' => ['Maus', '', '']]); + $this->assertResponseOk(); + $this->assertResponseContains('Bitte gib mindestens zwei Einträge an.'); + + $this->post("/admin/$token/slides/add?type=order", $data + ['order_options' => ['Maus', 'Maus', 'Hund']]); + $this->assertResponseContains('Jeder Eintrag darf nur einmal vorkommen'); + + $this->post("/admin/$token/slides/add?type=order", $data + ['order_options' => ['Maus', 'Katze', '', 'Elefant']]); + $this->assertRedirect(['_name' => 'admin', 'token' => $token]); + $slide = $this->slidesTable()->find()->where(['poll_id' => $poll->id])->contain(['SlideOptions'])->firstOrFail(); + $this->assertSame(['Maus', 'Katze', 'Elefant'], array_map(fn($o) => $o->label, $slide->slide_options)); + $this->assertTrue($slide->is_voting_open); + $ids = array_map(fn($o) => $o->id, $slide->slide_options); + + // Reordering in the editor keeps the options (ids), only the positions change. + $this->post("/admin/$token/slides/{$slide->id}/edit", $data + ['order_options' => ['Elefant', 'Katze', 'Maus']]); + $slide = $this->slidesTable()->get($slide->id, contain: ['SlideOptions']); + $this->assertSame(['Elefant', 'Katze', 'Maus'], array_map(fn($o) => $o->label, $slide->slide_options)); + $this->assertSame(array_reverse($ids), array_map(fn($o) => $o->id, $slide->slide_options)); + + $this->get("/admin/$token"); + $this->assertResponseContains('Elefant → Katze → Maus'); + } + + public function testParticipantSortsSubmitsAndSeesVerdict(): void + { + [$poll, $token] = $this->createPoll(); + $slide = $this->createSlide($poll, Slide::TYPE_ORDER, [], ['Eins', 'Zwei', 'Drei']); + $this->goLive($poll, $slide); + $ids = array_map(fn($o) => $o->id, $slide->slide_options); + $this->cookie('plenario_pid', str_repeat('b', 32)); + + $this->get('/p/' . $poll->join_code); + $this->assertResponseOk(); + $this->assertResponseContains('data-order-form'); + $this->assertResponseContains('Reihenfolge einreichen'); + preg_match_all('/name="order\[\]" value="(\d+)"/', (string)$this->_response->getBody(), $matches); + $shown = array_map('intval', $matches[1]); + $this->assertNotSame($ids, $shown, 'items are shuffled'); + $this->assertEqualsCanonicalizing($ids, $shown); + + $this->post('/p/' . $poll->join_code . '/vote', ['slide_id' => $slide->id, 'order' => $ids]); + $this->assertRedirect(['_name' => 'participate', 'code' => $poll->join_code]); + $this->get('/p/' . $poll->join_code); + $this->assertResponseContains('Deine Reihenfolge ist angekommen.'); + + $this->post("/admin/$token/control", ['action' => 'toggle']); + $this->get('/p/' . $poll->join_code); + $this->assertResponseContains('Richtig – deine Reihenfolge stimmt!'); + + $this->get("/admin/$token/export.csv"); + $this->assertResponseOk(); + $this->assertResponseContains('Eins → Zwei → Drei (richtig)'); + } +} diff --git a/tests/TestCase/PlenarioTestTrait.php b/tests/TestCase/PlenarioTestTrait.php index 49c48d4..3ef30f0 100644 --- a/tests/TestCase/PlenarioTestTrait.php +++ b/tests/TestCase/PlenarioTestTrait.php @@ -46,7 +46,8 @@ trait PlenarioTestTrait ]); $slide->poll_id = $poll->id; $slides->saveOrFail($slide); - if ($type === Slide::TYPE_CHOICE) { + if ($type === Slide::TYPE_CHOICE || $type === Slide::TYPE_ORDER) { + // Ordering: the given order is the correct one. $slides->syncOptions($slide, $options); } if ($type === Slide::TYPE_QUIZ) { diff --git a/tests/TestCase/Service/OrderTest.php b/tests/TestCase/Service/OrderTest.php new file mode 100644 index 0000000..6ce0555 --- /dev/null +++ b/tests/TestCase/Service/OrderTest.php @@ -0,0 +1,180 @@ + + */ + 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 createOrder(array $items = ['Steinzeit', 'Antike', 'Mittelalter', 'Neuzeit']): array + { + [$poll] = $this->createPoll(); + $slide = $this->createSlide($poll, Slide::TYPE_ORDER, [], $items); + + return [$this->goLive($poll, $slide), $slide]; + } + + /** + * @return list + */ + protected function ids(Slide $slide, array $labels): array + { + $byLabel = []; + foreach ($slide->slide_options as $option) { + $byLabel[$option->label] = $option->id; + } + + return array_map(fn($label) => $byLabel[$label], $labels); + } + + protected function close(Slide $slide): Slide + { + $slide->setVotingOpen(false); + $this->slidesTable()->saveOrFail($slide); + + return $this->slidesTable()->get($slide->id, contain: ['SlideOptions']); + } + + protected function participantState(Poll $poll, string $participant): array + { + return (new PollStateService())->forParticipant($this->pollsTable()->get($poll->id), $participant); + } + + public function testShuffledOptionsAreStableAndNeverTheSolution(): void + { + [, $slide] = $this->createOrder(['A', 'B']); + $correct = $this->ids($slide, ['A', 'B']); + + foreach (['p1', 'p2', 'p3', 'p4', 'p5', 'slide:1'] as $seed) { + $shuffled = array_map(fn($o) => $o->id, $slide->shuffledOptions($seed)); + $this->assertNotSame($correct, $shuffled); + $this->assertSame($shuffled, array_map(fn($o) => $o->id, $slide->shuffledOptions($seed))); + } + } + + public function testParseOrderOptions(): void + { + $this->assertSame( + ['labels' => ['Eins', 'Zwei'], 'duplicate' => false], + SlidesTable::parseOrderOptions([' Eins ', '', 'Zwei', ['x']]), + ); + $this->assertTrue(SlidesTable::parseOrderOptions(['Eins', 'Eins', 'Zwei'])['duplicate']); + } + + public function testRejectsIncompleteOrForeignOrders(): void + { + [$poll, $slide] = $this->createOrder(); + $ids = $this->ids($slide, ['Steinzeit', 'Antike', 'Mittelalter', 'Neuzeit']); + $service = new VoteService(); + + $invalid = [ + [], + ['order' => array_slice($ids, 0, 3)], + ['order' => [$ids[0], $ids[0], $ids[1], $ids[2]]], + ['order' => array_merge($ids, [999999])], + ['order' => [...array_slice($ids, 0, 3), 'x']], + ]; + foreach ($invalid as $data) { + try { + $service->submit($poll, $slide, 'p1', $data); + $this->fail('VoteException expected for ' . json_encode($data)); + } catch (VoteException $e) { + $this->assertStringContainsString('Reihenfolge', $e->getMessage()); + } + } + + $service->submit($poll, $slide, 'p1', ['order' => array_reverse($ids)]); + $this->expectExceptionMessage('Du hast bereits abgestimmt.'); + $service->submit($poll, $slide, 'p1', ['order' => $ids]); + } + + public function testOpenSlideHidesSolutionAndCounts(): void + { + [$poll, $slide] = $this->createOrder(); + (new VoteService())->submit($poll, $slide, 'p1', [ + 'order' => $this->ids($slide, ['Steinzeit', 'Antike', 'Mittelalter', 'Neuzeit']), + ]); + + $results = (new ResultsService())->forSlide($slide); + $this->assertFalse($results['revealed']); + $this->assertSame(1, $results['participants']); + $this->assertArrayNotHasKey('correctCount', $results); + $this->assertNotSame($slide->slide_options[0]->id, $results['items'][0]['id'] ?? null, 'not in the correct order'); + foreach ($results['items'] as $item) { + $this->assertSame(['id', 'label'], array_keys($item)); + } + + $state = $this->participantState($poll, 'p1'); + $this->assertTrue($state['hasResponded']); + $this->assertNull($state['results']); + $this->assertSame(['revealed' => false, 'answer' => null, 'isCorrect' => null], $state['order']); + } + + public function testClosingRevealsResultsToEveryone(): void + { + [$poll, $slide] = $this->createOrder(); + $service = new VoteService(); + $service->submit($poll, $slide, 'p1', ['order' => $this->ids($slide, ['Steinzeit', 'Antike', 'Mittelalter', 'Neuzeit'])]); + $service->submit($poll, $slide, 'p2', ['order' => $this->ids($slide, ['Antike', 'Steinzeit', 'Mittelalter', 'Neuzeit'])]); + $service->submit($poll, $slide, 'p3', ['order' => $this->ids($slide, ['Steinzeit', 'Antike', 'Mittelalter', 'Neuzeit'])]); + $slide = $this->close($slide); + + $results = (new ResultsService())->forSlide($slide); + $this->assertTrue($results['revealed']); + $this->assertSame(3, $results['participants']); + $this->assertSame(2, $results['correctCount']); + $this->assertSame(['Steinzeit', 'Antike', 'Mittelalter', 'Neuzeit'], array_column($results['items'], 'label')); + $this->assertSame([1, 2, 3, 4], array_column($results['items'], 'position')); + $this->assertSame([2, 2, 3, 3], array_column($results['items'], 'placed')); + + // Revealed even without show_results_to_participants. + $poll->show_results_to_participants = false; + $this->pollsTable()->saveOrFail($poll); + $wrong = $this->participantState($poll, 'p2'); + $this->assertTrue($wrong['order']['revealed']); + $this->assertFalse($wrong['order']['isCorrect']); + $this->assertSame($this->ids($slide, ['Antike', 'Steinzeit', 'Mittelalter', 'Neuzeit']), $wrong['order']['answer']); + $this->assertNotNull($wrong['results']); + $this->assertTrue($this->participantState($poll, 'p1')['order']['isCorrect']); + $this->assertNull($this->participantState($poll, 'nobody')['order']['isCorrect']); + + $this->expectExceptionMessage('Die Abstimmung zu dieser Frage ist geschlossen.'); + $service->submit($this->pollsTable()->get($poll->id), $slide, 'p4', [ + 'order' => $this->ids($slide, ['Steinzeit', 'Antike', 'Mittelalter', 'Neuzeit']), + ]); + } + + public function testReorderingOptionsChangesTheSolution(): void + { + [$poll, $slide] = $this->createOrder(['A', 'B', 'C']); + (new VoteService())->submit($poll, $slide, 'p1', ['order' => $this->ids($slide, ['B', 'A', 'C'])]); + $this->slidesTable()->syncOptions($slide, ['B', 'A', 'C']); + $slide = $this->close($slide); + + $results = (new ResultsService())->forSlide($slide); + $this->assertSame(1, $results['correctCount'], 'option ids are kept, only positions change'); + $this->assertSame(['B', 'A', 'C'], array_column($results['items'], 'label')); + } +} diff --git a/webroot/css/plenario.css b/webroot/css/plenario.css index c089640..3162b1a 100644 --- a/webroot/css/plenario.css +++ b/webroot/css/plenario.css @@ -179,6 +179,7 @@ h3 { font-size: 1.05rem; margin-top: 1.6em; } .badge--type-quiz { background: #f1e3fb; color: #7a2fb0; } .badge--type-youtube { background: #fde4e1; color: #b3261e; } .badge--type-qa { background: #dff1fb; color: #0b5f8a; } +.badge--type-order { background: #e6f4dc; color: #3d6b12; } .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); } @@ -287,6 +288,19 @@ textarea { resize: vertical; } .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); } +/* ordering slide editor (rows in the correct order, sortable) */ +.order-options { border: 0; padding: 0; margin: 0 0 16px; } +.order-options legend { font-weight: 600; margin-bottom: 4px; } +.order-options__list { list-style: none; padding: 0; margin: 0 0 10px; display: grid; gap: 8px; } +.order-option { display: flex; gap: 6px; align-items: center; background: var(--surface); border-radius: 8px; } +.order-option input[type=text] { flex: 1; margin: 0; } +.order-option__pos { min-width: 2em; text-align: right; font-weight: 700; color: var(--muted); font-variant-numeric: tabular-nums; } +.order-options.error .order-options__list input[type=text] { border-color: var(--danger); } + +/* shared by sortable form lists */ +.is-sorting, .is-sorting * { cursor: grabbing !important; user-select: none; } +.is-dragging { position: relative; z-index: 2; box-shadow: 0 10px 30px rgba(0, 0, 0, .18); } + .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; } .copy-field { display: flex; gap: 8px; } @@ -341,6 +355,30 @@ textarea { resize: vertical; } .verdict--correct { color: var(--ok); } .verdict--wrong { color: var(--danger); } +/* ordering slide (participant) */ +.order-list { list-style: none; padding: 0; margin: 16px 0 8px; display: grid; gap: 8px; } +.order-item { + display: flex; gap: 8px; align-items: center; padding: 6px 6px 6px 4px; + background: var(--surface); border: 2px solid var(--border); border-left: 8px solid var(--c0); border-radius: 10px; +} +.order-item.choice--c1 { border-left-color: var(--c1); } +.order-item.choice--c2 { border-left-color: var(--c2); } +.order-item.choice--c3 { border-left-color: var(--c3); } +.order-item.choice--c4 { border-left-color: var(--c4); } +.order-item.choice--c5 { border-left-color: var(--c5); } +.order-item.is-dragging { border-color: var(--primary); } +.order-item__pos { width: 28px; height: 28px; flex: none; border-radius: 50%; display: grid; place-items: center; background: var(--surface-2); font-weight: 700; font-size: .9rem; } +.order-item__label { flex: 1; min-width: 0; font-weight: 600; word-break: break-word; } +.order-item__moves { display: flex; gap: 4px; flex: none; } +.order-move { + width: 44px; height: 44px; padding: 0; border: 1px solid var(--border); border-radius: 8px; + background: var(--surface-2); color: var(--text); font-size: 1rem; cursor: pointer; +} +.order-move:hover { border-color: var(--primary); } +.order-move:focus-visible { outline: 3px solid var(--primary); outline-offset: 1px; } +.order-item:first-child .order-move[data-move=up], .order-item:last-child .order-move[data-move=down] { opacity: .35; } +.order-item .drag-handle { height: 44px; } + /* ---------------------------------------------------------------- results (shared) */ .results-empty { color: var(--muted); font-style: italic; } .is-hidden { visibility: hidden; } @@ -417,6 +455,11 @@ textarea { resize: vertical; } .bar--wrong .bar__fill { background: var(--muted); opacity: .6; } .bar.is-mine .bar__label { text-decoration: underline; text-underline-offset: 3px; } +/* ordering results */ +.order-solution { list-style: none; padding: 0; margin: 0; display: grid; gap: 14px; } +.order-solution__pos { display: inline-block; min-width: 1.6em; color: var(--muted); font-variant-numeric: tabular-nums; } +.order-solution .bar__fill { background: var(--ok); } + .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; } @@ -523,6 +566,7 @@ body.present { .stage .quiz-tile { font-size: clamp(1.2rem, 2.2vw, 2rem); } .stage .quiz-summary strong, .stage .bar--correct .bar__label { color: var(--stage-ok); } .stage .bar--correct .bar__fill { background: var(--stage-ok); } +.stage .order-solution .bar__fill { background: var(--stage-ok); } .stage .qa-steps { font-size: .7em; } .stage .qa-steps__step { border-color: rgba(var(--tint), .25); } .stage .qa-item { background: rgba(var(--tint), .06); } diff --git a/webroot/js/plenario.js b/webroot/js/plenario.js index d1ce843..15c0dfb 100644 --- a/webroot/js/plenario.js +++ b/webroot/js/plenario.js @@ -11,6 +11,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-order-options] slide form of ordering slides: sortable rows (correct order), "add entry" + * - [data-order-form] participant answer of ordering slides: sortable items posting order[] * - [data-theme-switch] cycles the colour scheme (data-theme on , stored in localStorage), * see templates/element/theme_init.php for the pre-paint part * @@ -304,7 +306,9 @@ } // A quiz shows its answer options even before anyone has answered. // A Q&A slide always shows its stages. - if (results.participants === 0 && results.type !== 'qa' && !(results.type === 'quiz' && !results.revealed)) { + // An ordering slide shows its items before and the solution after the reveal. + if (results.participants === 0 && results.type !== 'qa' && results.type !== 'order' + && !(results.type === 'quiz' && !results.revealed)) { container.appendChild(el('p', { class: 'results-empty', text: 'Noch keine Antworten' })); return; } @@ -498,6 +502,56 @@ return el('div', { class: 'quiz-results quiz-results--finished' }, [summary, bars]); }, + /** + * Ordering slide. Before the reveal only the items in a shuffled order; + * afterwards the correct order with how often each item was placed right. + * options: {order: participant state {answer: [ids]|null}} marks own placements. + */ + order: function (results, options) { + var answer = options && options.order ? options.order.answer : null; + if (!results.revealed) { + return el('div', { class: 'order-results' }, [ + el('p', { class: 'quiz-status', text: 'Die Teilnehmenden sortieren – aufgelöst wird beim Schließen der Abstimmung' }), + el('ul', { class: 'quiz-grid' }, results.items.map(function (item, index) { + return el('li', { class: 'quiz-tile quiz-tile--c' + (index % 6), text: item.label }); + })) + ]); + } + + var children = []; + if (results.participants > 0) { + var percent = Math.round(results.correctCount / results.participants * 100); + children.push(el('p', { class: 'quiz-summary' }, [ + el('strong', { text: results.correctCount + ' von ' + results.participants }), + el('span', { text: ' komplett richtig (' + percent + ' %)' }) + ])); + } else { + children.push(el('p', { class: 'results-empty', text: 'Keine Antworten – so wäre es richtig gewesen:' })); + } + children.push(el('ol', { class: 'order-solution' }, results.items.map(function (item, index) { + var mine = answer ? answer[index] === item.id : null; + var label = item.label + (mine === true ? ' ✓' : (mine === false ? ' ✗' : '')); + return el('li', { class: 'bar order-solution__item' + (mine === true ? ' is-mine' : '') }, [ + el('div', { class: 'bar__label' }, [ + el('span', { class: 'order-solution__pos', text: item.position + '.' }), + document.createTextNode(' ' + label), + mine === null ? null : el('span', { + class: 'sr-only', + text: mine ? ' – von dir richtig platziert' : ' – von dir an anderer Stelle' + }) + ]), + results.participants > 0 ? el('div', { class: 'bar__track' }, [ + el('div', { class: 'bar__fill', style: 'width:' + item.percent + '%' }) + ]) : null, + results.participants > 0 ? el('div', { + class: 'bar__value', + text: formatNumber(item.percent) + ' % an dieser Stelle (' + item.placed + ')' + }) : null + ]); + }))); + return el('div', { class: 'order-results order-results--revealed' }, children); + }, + open: function (results) { if (results.private) { // Anonymous feedback: the texts never reach the stage, only the count. @@ -839,15 +893,17 @@ var quizPhase = slide.type === 'quiz' && state.results ? state.results.phase : null; var qaStage = slide.type === 'qa' && state.results ? state.results.stage : null; + var orderRevealed = slide.type === 'order' && state.results ? state.results.revealed : null; q('[data-type]').textContent = quizPhase ? slide.typeLabel + ' · ' + { ready: 'bereit', running: 'läuft', finished: 'Auflösung' }[quizPhase] - : (qaStage ? slide.typeLabel + ' · ' + Qa.labels[qaStage] : slide.typeLabel); + : (qaStage ? slide.typeLabel + ' · ' + Qa.labels[qaStage] + : (orderRevealed ? slide.typeLabel + ' · Auflösung' : 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 && !qaStage); + root.classList.toggle('stage--closed', slide.isInteractive && !slide.isVotingOpen && !quizPhase && !qaStage && !orderRevealed); root.classList.toggle('stage--qa', !!qaStage); var voting = q('[data-voting]'); @@ -857,7 +913,9 @@ ? { ready: 'Quiz starten', running: 'Quiz beenden', finished: 'Quiz erneut öffnen' }[quizPhase] : (qaStage ? { collect: 'Einreichen beenden', vote: 'Abstimmung beenden', discuss: '' }[qaStage] - : (slide.isVotingOpen ? 'Abstimmung schließen' : 'Abstimmung öffnen')); + : (slide.type === 'order' + ? (slide.isVotingOpen ? 'Schließen & auflösen' : 'Abstimmung wieder öffnen') + : (slide.isVotingOpen ? 'Abstimmung schließen' : 'Abstimmung öffnen'))); var count = qaStage ? state.results.questions.length : (slide.isInteractive ? state.results.participants : 0); setText('[data-participants]', !slide.isInteractive ? '' : (qaStage @@ -1248,6 +1306,7 @@ mine: state.words ? state.words.mine : [], down: state.words ? state.words.down : [], answerId: state.quiz ? state.quiz.answerId : null, + order: state.order, onUpvote: upvote ? function (word) { sendWord(word.text); } : null, onDownvote: upvote && state.words.allowDownvotes ? function (word) { sendWord(word.text, 'down'); } : null }); @@ -1467,96 +1526,60 @@ update(); } - // ------------------------------------------------------------------ sortable slide list - function initSortable(list) { - var url = list.getAttribute('data-sortable'); - var section = list.parentNode; - var status = section.querySelector('[data-sortable-status]'); - var hint = section.querySelector('[data-sortable-hint]'); - var error = null; - var saving = Promise.resolve(); + // ------------------------------------------------------------------ sortable lists + + /** + * Reorderable list: drag by [data-drag-handle] (pointer events: mouse, touch, pen), + * arrow keys on a focused handle, and optional [data-move="up|down"] buttons. + * Only moves DOM nodes; options.onChange(item) runs after every completed move. + * + * @param {Element} list + * @param {{item: string, onChange: function(Element), draggingClass: string, sortingClass: string}} options + */ + function makeSortable(list, options) { var drag = null; function items() { - return Array.prototype.slice.call(list.children).filter(function (node) { - return node.hasAttribute('data-slide-id'); + return Array.prototype.filter.call(list.children, function (node) { + return node.matches(options.item); }); } - function order() { - return items().map(function (item) { return item.getAttribute('data-slide-id'); }); - } - - function renumber() { - items().forEach(function (item, index) { - var pos = item.querySelector('[data-position]'); - if (pos) { - pos.textContent = String(index + 1); - } - }); - } - - function label(item) { - var title = item.querySelector('.slide-item__title'); - return title ? title.textContent : ''; - } - - function announce(text) { - if (status) { - status.textContent = text; + function move(item, up) { + var sibling = up ? item.previousElementSibling : item.nextElementSibling; + if (!sibling || !sibling.matches(options.item)) { + return false; } + list.insertBefore(item, up ? sibling : sibling.nextElementSibling); + return true; } - function announceMove(item) { - var all = items(); - announce('„' + label(item) + '“ ist jetzt an Position ' + (all.indexOf(item) + 1) + ' von ' + all.length + '.'); - } - - function showError(message) { - if (!error) { - var reload = el('button', { type: 'button', class: 'button button--small', text: 'Seite neu laden' }); - reload.addEventListener('click', function () { window.location.reload(); }); - error = el('div', { class: 'notice', role: 'alert' }, [el('span'), document.createTextNode(' '), reload]); - section.insertBefore(error, list); - } - error.firstChild.textContent = message; - } - - function save(item) { - var ids = order(); - renumber(); - announceMove(item); - item.classList.add('slide-item--saving'); - // Sequential, so an older order can never overwrite a newer one. - saving = saving.then(function () { - return postJson(url, { ids: ids }); - }).catch(function () { - showError('Die Reihenfolge konnte nicht gespeichert werden. Bitte lade die Seite neu.'); - }).then(function () { - item.classList.remove('slide-item--saving'); - }); - } - - // Keyboard: arrow keys on the handle move the slide by one. list.addEventListener('keydown', function (event) { var handle = event.target.closest('[data-drag-handle]'); if (!handle || (event.key !== 'ArrowUp' && event.key !== 'ArrowDown')) { return; } event.preventDefault(); - var item = handle.closest('[data-slide-id]'); - var up = event.key === 'ArrowUp'; - var sibling = up ? item.previousElementSibling : item.nextElementSibling; - if (!sibling || !sibling.hasAttribute('data-slide-id')) { + var item = handle.closest(options.item); + if (move(item, event.key === 'ArrowUp')) { + handle.focus(); + options.onChange(item); + } + }); + + list.addEventListener('click', function (event) { + var button = event.target.closest('[data-move]'); + if (!button) { return; + } + var item = button.closest(options.item); + if (move(item, button.getAttribute('data-move') === 'up')) { + button.focus(); + options.onChange(item); } - list.insertBefore(item, up ? sibling : sibling.nextElementSibling); - handle.focus(); - save(item); }); - // Pointer (mouse, touch, pen): drag by the handle. function pageTop(node) { return node.getBoundingClientRect().top + window.scrollY; } @@ -1594,13 +1617,13 @@ return; } var item = drag.item; - var changed = order().join(',') !== drag.before; + var changed = items().indexOf(item) !== drag.index; item.style.transform = ''; - item.classList.remove('slide-item--dragging'); - list.classList.remove('slide-list--sorting'); + item.classList.remove(options.draggingClass); + list.classList.remove(options.sortingClass); drag = null; if (changed) { - save(item); + options.onChange(item); } } @@ -1610,22 +1633,83 @@ return; } event.preventDefault(); - var item = handle.closest('[data-slide-id]'); + var item = handle.closest(options.item); handle.setPointerCapture(event.pointerId); drag = { item: item, pointerId: event.pointerId, grabOffset: event.clientY - item.getBoundingClientRect().top, - before: order().join(',') + index: items().indexOf(item) }; - item.classList.add('slide-item--dragging'); - list.classList.add('slide-list--sorting'); + item.classList.add(options.draggingClass); + list.classList.add(options.sortingClass); }); list.addEventListener('pointermove', onMove); list.addEventListener('pointerup', onEnd); list.addEventListener('pointercancel', onEnd); - if (items().length > 1) { + return { items: items }; + } + + /** Updates the visible [data-position] numbers of sortable items. */ + function renumber(items, suffix) { + items.forEach(function (item, index) { + var pos = item.querySelector('[data-position]'); + if (pos) { + pos.textContent = String(index + 1) + (suffix || ''); + } + var label = item.querySelector('[data-row-label]'); + if (label) { + label.textContent = 'Platz ' + (index + 1); + } + }); + } + + /** Admin slide list: saves the new order right away (POST ids[] to [data-sortable]). */ + function initSortable(list) { + var url = list.getAttribute('data-sortable'); + var section = list.parentNode; + var status = section.querySelector('[data-sortable-status]'); + var hint = section.querySelector('[data-sortable-hint]'); + var error = null; + var saving = Promise.resolve(); + + function showError(message) { + if (!error) { + var reload = el('button', { type: 'button', class: 'button button--small', text: 'Seite neu laden' }); + reload.addEventListener('click', function () { window.location.reload(); }); + error = el('div', { class: 'notice', role: 'alert' }, [el('span'), document.createTextNode(' '), reload]); + section.insertBefore(error, list); + } + error.firstChild.textContent = message; + } + + var sortable = makeSortable(list, { + item: '[data-slide-id]', + draggingClass: 'slide-item--dragging', + sortingClass: 'slide-list--sorting', + onChange: function (item) { + var all = sortable.items(); + var ids = all.map(function (node) { return node.getAttribute('data-slide-id'); }); + var title = item.querySelector('.slide-item__title'); + renumber(all); + if (status) { + status.textContent = '„' + (title ? title.textContent : '') + '“ ist jetzt an Position ' + + (all.indexOf(item) + 1) + ' von ' + all.length + '.'; + } + item.classList.add('slide-item--saving'); + // Sequential, so an older order can never overwrite a newer one. + saving = saving.then(function () { + return postJson(url, { ids: ids }); + }).catch(function () { + showError('Die Reihenfolge konnte nicht gespeichert werden. Bitte lade die Seite neu.'); + }).then(function () { + item.classList.remove('slide-item--saving'); + }); + } + }); + + if (sortable.items().length > 1) { list.querySelectorAll('[data-drag-handle]').forEach(function (handle) { handle.hidden = false; }); if (hint) { hint.hidden = false; @@ -1633,6 +1717,74 @@ } } + /** + * Local reordering inside a form (ordering slide editor and participant answer): + * only the DOM order changes, the form posts its fields in that order. + */ + function initOrderList(container, itemSelector, describe) { + var list = container.querySelector('[data-order-list]'); + var status = container.querySelector('[data-order-status]'); + var sortable = makeSortable(list, { + item: itemSelector, + draggingClass: 'is-dragging', + sortingClass: 'is-sorting', + onChange: function (item) { + var all = sortable.items(); + renumber(all, list.hasAttribute('data-position-suffix') ? '.' : ''); + if (status) { + status.textContent = describe(item) + ' ist jetzt an Position ' + (all.indexOf(item) + 1) + ' von ' + all.length + '.'; + } + } + }); + list.querySelectorAll('[data-drag-handle]').forEach(function (handle) { handle.hidden = false; }); + return sortable; + } + + /** Ordering slide editor: sortable rows plus "add entry". */ + function initOrderOptions(fieldset) { + var list = fieldset.querySelector('[data-order-list]'); + var button = fieldset.querySelector('[data-order-add]'); + var hint = fieldset.querySelector('[data-order-hint]'); + var max = parseInt(fieldset.getAttribute('data-max'), 10) || 10; + list.setAttribute('data-position-suffix', ''); + var sortable = initOrderList(fieldset, '[data-order-row]', function (item) { + var value = item.querySelector('input[type=text]').value.trim(); + return value ? '„' + value + '“' : 'Die leere Zeile'; + }); + if (hint) { + hint.hidden = false; + } + function update() { + button.hidden = sortable.items().length >= max; + } + button.addEventListener('click', function () { + var all = sortable.items(); + if (all.length >= max) { + return; + } + var row = all[all.length - 1].cloneNode(true); + var text = row.querySelector('input[type=text]'); + var id = 'order-option-' + all.length + '-' + Date.now(); + row.querySelector('[data-row-label]').setAttribute('for', id); + text.id = id; + text.value = ''; + text.required = false; + text.placeholder = 'Eintrag ' + (all.length + 1); + list.appendChild(row); + renumber(sortable.items(), '.'); + text.focus(); + update(); + }); + update(); + } + + /** Participant answer of an ordering slide. */ + function initOrderForm(form) { + initOrderList(form, '[data-order-item]', function (item) { + return '„' + item.querySelector('[data-label]').textContent + '“'; + }); + } + // ------------------------------------------------------------------ theme switch var THEME_ICONS = { auto: '◐', light: '☀', dark: '☾' }; @@ -1692,6 +1844,8 @@ document.querySelectorAll('[data-participant]').forEach(initParticipant); document.querySelectorAll('[data-quiz-options]').forEach(initQuizOptions); document.querySelectorAll('[data-sortable]').forEach(initSortable); + document.querySelectorAll('[data-order-options]').forEach(initOrderOptions); + document.querySelectorAll('[data-order-form]').forEach(initOrderForm); // Prevent double submits of vote forms. document.querySelectorAll('.vote-form').forEach(function (form) {