diff --git a/AGENTS.md b/AGENTS.md index 1c963ca..89d3bb5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -60,7 +60,7 @@ src/ AdminController Dashboard, Settings, Present, State-JSON, Control, QR, PDF-Export, Token rotieren, Zurücksetzen, Löschen SlidesController Folien-CRUD, Antworten offener Fragen bzw. Skala-Auswertung (`answers`), 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 + ParticipateController /p/{code}: Ansicht, State-JSON, Abstimmen, eigene Antwort/Kommentar bearbeiten; anonymes Cookie plenario_pid EmbedController /e/{key}/{id}: eine Folie zum Einbetten (z. B. Canva), activate/heartbeat/pause/control ErrorController Fehlerseiten (Templates unter templates/Error, Layout `error`) Mailer/ PollMailer (adminLink, recovery; `sendSafely()` loggt Transportfehler statt zu werfen), Transport/FileTransport (lokal) @@ -134,6 +134,9 @@ tests/ PHPUnit; PlenarioTestTrait erzeugt Testdaten, Fixtures Downvotes (`vote=down`, Setting `allow_downvotes`, nur zusammen mit Upvotes): Zeile mit `numeric_value = VoteService::DOWNVOTE` (-1), nur auf fremde, vorhandene Begriffe, ein Rating pro Begriff und Person. Wortgröße richtet sich nur nach den Upvotes (`count`), Downvotes stehen separat in `down`. + `vote=remove` nimmt den eigenen Eintrag zu einem Begriff zurück (genannt/Upvote oder Downvote, `VoteService::removeWord()`, + löscht nur Zeilen mit dem eigenen `participant_hash`); Tippfehler = entfernen und neu eingeben, kein Bearbeiten (die Zeile + ist zugleich die Stimme). Teilnehmende bekommen dafür `words.own` (eigene Begriffe wie eingegeben) und sehen sie als Chips mit „ד. - Quiz: Phasen `ready` → `running` → `finished` (`Slide::quizPhase()`). Neue Quiz-Folien starten geschlossen; erst der Presenter startet (`control` open/toggle → `Slide::setVotingOpen()` setzt Start + Deadline aus `time_limit`, erneutes Öffnen eines laufenden Quiz startet den Timer nicht neu). „Offen“ heißt immer @@ -167,6 +170,10 @@ tests/ PHPUnit; PlenarioTestTrait erzeugt Testdaten, Fixtures (→/←, 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`. + Eigene Fragen bearbeiten/löschen (`vote=edit|delete` + `question_id`, `VoteService::editQuestion()`) nur in `collect`: + danach könnten Upvotes bzw. die Besprechung an einem anderen Text hängen. Bearbeiten prüft Dubletten ohne die eigene Frage, + Löschen entfernt auch übrig gebliebene Upvotes (Presenter von `vote` zurück nach `collect`). Im JS hält `qaEditing` das + Neu-Rendern beim Polling an, solange eine Frage bearbeitet wird. - 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). @@ -216,8 +223,13 @@ tests/ PHPUnit; PlenarioTestTrait erzeugt Testdaten, Fixtures `results.comments` (Teilnehmende bekommen sie nie: Skalen liefern ihnen grundsätzlich keine `results`, siehe `PollStateService::forParticipant()`) (älteste zuerst, je `id`, `text`, `value` – `value` nur mit Setting `comment_ratings`, sonst `null`); `Comments` in `plenario.js` blättert sie automatisch durch (Anzeigedauer nur nach Textlänge, bewusst ohne Setting: `Comments.delay()` = 2,5 s + 15 Zeichen/s, 5–30 s; Vor/Zurück/Fortsetzen geben dem Kommentar wieder die volle Zeit; „Kommentar X von N“, - vor/zurück/Pause, Zustand übersteht das Neu-Rendern beim Polling). Bei internem Feedback erscheinen sie erst, + vor/zurück/Pause, Laufbalken bis zum Wechsel (`Comments.progress()`, setzt nach dem Neu-Rendern per negativem + `animation-delay` fort, bei Pause unsichtbar), Zustand übersteht das Neu-Rendern beim Polling). Bei internem Feedback erscheinen sie erst, wenn der Presenter die Ergebnisse einblendet. +- **Antwort nachträglich bearbeiten** (gegen Tippfehler, `VoteService::hasEditableText()`): Antwort einer offenen Frage + (darf nicht leer werden) bzw. Kommentar einer Skala (ändern, ergänzen, leeren; die Bewertung bleibt unveränderlich), + nur solange die Abstimmung offen ist. `participate:edit` → `VoteService::editText()`, gleiche Vorbedingungen wie + `submit()`, in der Folien-Sperre, legt nie eine neue Antwort an. - **PDF-Export** (`/admin/{token}/export.pdf`, `admin:export`, `ReportService` + `PdfView`, Dompdf): Ergebnisse aller interaktiven Folien (Inhaltsfolien/YouTube fehlen). Standard ist die Fassung **ohne interne Inhalte**: private Folien diff --git a/config/app.php b/config/app.php index 45f4bf9..1ba847d 100644 --- a/config/app.php +++ b/config/app.php @@ -136,7 +136,8 @@ return [ * enable timestamping regardless of debug value. */ 'Asset' => [ - //'timestamp' => true, + // Always (also in production): browsers must not keep an outdated plenario.js/css after a deploy. + 'timestamp' => 'force', // 'cacheTime' => '+1 year' ], diff --git a/config/routes.php b/config/routes.php index 2452d9b..54b189e 100644 --- a/config/routes.php +++ b/config/routes.php @@ -37,6 +37,10 @@ return function (RouteBuilder $routes): void { ->setPatterns(['code' => '[A-Za-z0-9-]{4,16}']) ->setPass(['code']) ->setMethods(['POST']); + $builder->connect('/p/{code}/edit', 'Participate::edit', ['_name' => 'participate:edit']) + ->setPatterns(['code' => '[A-Za-z0-9-]{4,16}']) + ->setPass(['code']) + ->setMethods(['POST']); // --- embedded slides (secret embed key, e.g. Canva) ----------------- // No CSRF check here (see Application::middleware()): runs in third-party iframes diff --git a/src/Controller/ParticipateController.php b/src/Controller/ParticipateController.php index 2914fc1..8da85f2 100644 --- a/src/Controller/ParticipateController.php +++ b/src/Controller/ParticipateController.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace App\Controller; use App\Model\Entity\Poll; +use App\Model\Entity\Slide; use App\Model\Table\PollsTable; use App\Service\PollStateService; use App\Service\VoteException; @@ -86,8 +87,11 @@ class ParticipateController extends AppController $slide = $poll->is_active ? $stateService->currentSlide($poll) : null; $participantHash = $this->participantHash($poll); $state = $stateService->forParticipant($poll, $participantHash, $slide); + $ownText = $slide !== null && VoteService::hasEditableText($slide) && $state['hasResponded'] + ? (new VoteService())->ownText($slide, $participantHash) + : null; - $this->set(compact('poll', 'slide', 'state', 'participantHash')); + $this->set(compact('poll', 'slide', 'state', 'participantHash', 'ownText')); $this->setPollInterval(); } @@ -134,6 +138,8 @@ class ParticipateController extends AppController !$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.'), + $this->request->getData('vote') === 'edit' => __('Deine Frage wurde geändert.'), + $this->request->getData('vote') === 'delete' => __('Deine Frage wurde gelöscht.'), default => __('Danke, deine Frage ist angekommen!'), }; } catch (VoteException $e) { @@ -153,6 +159,41 @@ class ParticipateController extends AppController return $this->redirect(['_name' => 'participate', 'code' => $poll->join_code]); } + /** + * Replaces the own answer text (open question) or comment (scale) while voting is open, + * e.g. to fix a typo. See VoteService::editText(). + * + * @param string $code Join code + * @return \Cake\Http\Response|null + */ + public function edit(string $code): ?Response + { + $this->request->allowMethod(['post']); + $poll = $this->loadPoll($code); + $slide = (new PollStateService())->currentSlide($poll); + + try { + if (!$this->throttle('vote', 'Plenario.throttle.votesPerMinute', 60)) { + throw new VoteException(__('Zu viele Antworten in kurzer Zeit. Bitte warte einen Moment und versuche es dann noch einmal.')); + } + if ($slide === null || $slide->id !== (int)$this->request->getData('slide_id')) { + throw new VoteException(__('Diese Frage ist nicht mehr aktiv.')); + } + $data = (array)$this->request->getData(); + (new VoteService())->editText($poll, $slide, $this->participantHash($poll), $data); + $comment = $data['comment'] ?? ''; + $this->Flash->success(match (true) { + $slide->type === Slide::TYPE_OPEN => __('Deine Antwort wurde geändert.'), + !is_scalar($comment) || trim((string)$comment) === '' => __('Dein Kommentar wurde entfernt.'), + default => __('Dein Kommentar wurde gespeichert.'), + }); + } catch (VoteException $e) { + $this->Flash->error($e->getMessage()); + } + + return $this->redirect(['_name' => 'participate', 'code' => $poll->join_code]); + } + /** * @param string $code Join code * @return \App\Model\Entity\Poll diff --git a/src/Service/PollStateService.php b/src/Service/PollStateService.php index bc0d877..f4b87a9 100644 --- a/src/Service/PollStateService.php +++ b/src/Service/PollStateService.php @@ -321,8 +321,8 @@ class PollStateService * * @param \App\Model\Entity\Slide $slide Word cloud slide * @param string $participantHash Participant hash - * @return array{mine: list, down: list, allowUpvotes: bool, allowDownvotes: bool} - * `mine` (named/upvoted) and `down` are lower case word keys + * @return array{mine: list, down: list, own: list, allowUpvotes: bool, allowDownvotes: bool} + * `mine` (named/upvoted) and `down` are lower case word keys, `own` the same entries as typed */ public function wordState(Slide $slide, string $participantHash): array { @@ -330,10 +330,18 @@ class PollStateService $mine = array_values(array_unique(array_map(VoteService::wordKey(...), $votes['up']))); $down = array_values(array_unique(array_map(VoteService::wordKey(...), $votes['down']))); $allowUpvotes = (bool)$slide->setting('allow_upvotes'); + // Own entries as typed (first spelling per key), oldest first, so they can be withdrawn. + $own = []; + foreach (['up' => false, 'down' => true] as $kind => $isDown) { + foreach ($votes[$kind] as $text) { + $own[VoteService::wordKey($text)] ??= ['text' => $text, 'down' => $isDown]; + } + } return [ 'mine' => $mine, 'down' => $down, + 'own' => array_values($own), 'allowUpvotes' => $allowUpvotes, 'allowDownvotes' => $allowUpvotes && (bool)$slide->setting('allow_downvotes'), ]; diff --git a/src/Service/VoteService.php b/src/Service/VoteService.php index 0e56276..3fbf8b9 100644 --- a/src/Service/VoteService.php +++ b/src/Service/VoteService.php @@ -22,6 +22,7 @@ use Cake\Utility\Security; * exists in the cloud is an upvote – both are stored as the same row. * `vote=down` stores a downvote (numeric_value = DOWNVOTE) for an existing * word of someone else. Each participant rates a word only once (up or down). + * `vote=remove` withdraws the participant's own entry for a word (see removeWord()). * At most MAX_WORDS_PER_REQUEST terms per request and MAX_WORDS per participant and slide. * - checks and insert run in one transaction with the slide row locked (see lockSlide()), * so concurrent or repeated requests cannot store an answer twice. @@ -33,9 +34,12 @@ use Cake\Utility\Security; * questions of others (own ones too with setting `allow_self_upvote`), at most * `max_upvotes` in total, freely distributed (several on one question are allowed, * at most `max_upvotes_per_question` if set; `max_upvotes` = 0 means no voting stage); - * `remove` withdraws one own upvote of the question. + * `remove` withdraws one own upvote of the question. `vote=edit|delete` + `question_id` + * changes or deletes an own question, only while collecting (see editQuestion()). * - 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()). + * - open question and scale with comment field: the own answer text or comment can be changed + * while voting is open (editText()), a scale rating cannot. */ class VoteService { @@ -91,23 +95,7 @@ class VoteService */ public function submit(Poll $poll, Slide $slide, string $participantHash, array $data): void { - if (!$poll->is_active) { - throw new VoteException(__('Diese Umfrage ist derzeit geschlossen.')); - } - if ($slide->poll_id !== $poll->id || $poll->current_slide_id !== $slide->id) { - throw new VoteException(__('Diese Frage ist nicht mehr aktiv.')); - } - if (!$slide->isInteractive()) { - throw new VoteException(__('Auf dieser Folie kann nicht abgestimmt werden.')); - } - if (!$slide->isVotingOpen()) { - throw new VoteException(match (true) { - $slide->isQuiz() && $slide->voting_started_at === null => __('Das Quiz hat noch nicht begonnen.'), - $slide->isQuiz() => __('Die Zeit für dieses Quiz ist abgelaufen.'), - $slide->isQa() => __('Die Fragerunde läuft – Fragen und Stimmen sind nicht mehr möglich.'), - default => __('Die Abstimmung zu dieser Frage ist geschlossen.'), - }); - } + $this->assertOpen($poll, $slide); // Checks (answered already, upvote budget, duplicates) and the insert run as one unit, // so a double click or a retried request cannot store an answer twice. $this->Responses->getConnection()->transactional(function () use ($slide, $participantHash, $data): void { @@ -140,6 +128,99 @@ class VoteService }); } + /** + * Whether the participant may change the text of their answer afterwards (e.g. to fix a typo): + * the answer of an open question and the comment of a scale with comment field. + * + * @param \App\Model\Entity\Slide $slide Slide + * @return bool + */ + public static function hasEditableText(Slide $slide): bool + { + return $slide->type === Slide::TYPE_OPEN || ($slide->type === Slide::TYPE_SCALE && $slide->hasComments()); + } + + /** + * Replaces the text of the participant's own answer as long as voting on the slide is open + * (see hasEditableText()). Open question: `text`, must not be empty. Scale: `comment`, the + * rating itself stays unchanged and an empty comment removes it. Same preconditions as submit(). + * + * @param \App\Model\Entity\Poll $poll Poll + * @param \App\Model\Entity\Slide $slide Slide + * @param string $participantHash Participant hash + * @param array $data Request data (`text` or `comment`) + * @return void + * @throws \App\Service\VoteException + */ + public function editText(Poll $poll, Slide $slide, string $participantHash, array $data): void + { + $this->assertOpen($poll, $slide); + if (!self::hasEditableText($slide)) { + throw new VoteException(__('Diese Antwort kann nicht mehr geändert werden.')); + } + $text = $slide->type === Slide::TYPE_OPEN ? $this->openRows($data)[0]['text_value'] : self::comment($data); + $this->Responses->getConnection()->transactional(function () use ($slide, $participantHash, $text): void { + $this->lockSlide($slide); + $row = $this->Responses->find() + ->where(['slide_id' => $slide->id, 'participant_hash' => $participantHash]) + ->first(); + if ($row === null) { + throw new VoteException($slide->type === Slide::TYPE_OPEN + ? __('Du hast hier noch nicht geantwortet.') + : __('Bitte gib zuerst deine Bewertung ab.')); + } + $row->text_value = $text; + $this->Responses->saveOrFail($row); + }); + } + + /** + * Text of the participant's own answer: open answer or scale comment (null: none or not answered yet). + * + * @param \App\Model\Entity\Slide $slide Slide + * @param string $participantHash Participant hash + * @return string|null + */ + public function ownText(Slide $slide, string $participantHash): ?string + { + $row = $this->Responses->find() + ->select(['text_value']) + ->where(['slide_id' => $slide->id, 'participant_hash' => $participantHash]) + ->disableHydration() + ->first(); + + return $row['text_value'] ?? null; + } + + /** + * Poll active, slide live and interactive, voting open. + * + * @param \App\Model\Entity\Poll $poll Poll + * @param \App\Model\Entity\Slide $slide Slide + * @return void + * @throws \App\Service\VoteException + */ + protected function assertOpen(Poll $poll, Slide $slide): void + { + if (!$poll->is_active) { + throw new VoteException(__('Diese Umfrage ist derzeit geschlossen.')); + } + if ($slide->poll_id !== $poll->id || $poll->current_slide_id !== $slide->id) { + throw new VoteException(__('Diese Frage ist nicht mehr aktiv.')); + } + if (!$slide->isInteractive()) { + throw new VoteException(__('Auf dieser Folie kann nicht abgestimmt werden.')); + } + if (!$slide->isVotingOpen()) { + throw new VoteException(match (true) { + $slide->isQuiz() && $slide->voting_started_at === null => __('Das Quiz hat noch nicht begonnen.'), + $slide->isQuiz() => __('Die Zeit für dieses Quiz ist abgelaufen.'), + $slide->isQa() => __('Die Fragerunde läuft – Fragen und Stimmen sind nicht mehr möglich.'), + default => __('Die Abstimmung zu dieser Frage ist geschlossen.'), + }); + } + } + /** * Serialises answers to one slide for the rest of the transaction. * @@ -274,23 +355,16 @@ class VoteService $vote = $data['vote'] ?? null; $own = $this->Responses->qaVotesOf($slide->id, $participantHash); + if ($vote === 'edit' || $vote === 'delete') { + $this->editQuestion($slide, $own['questions'], $vote, $data); + + return []; + } 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', ' ', self::stringField($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.')); - } - } + $text = $this->qaQuestionText($slide, $data); if (count($own['questions']) >= self::MAX_QA_QUESTIONS) { throw new VoteException(__('Du kannst höchstens {0} Fragen stellen.', self::MAX_QA_QUESTIONS)); } @@ -352,6 +426,68 @@ class VoteService return [['parent_id' => $id]]; } + /** + * Q&A: validated question text from `question` (whitespace collapsed), unique on the slide + * (case-insensitive; `$except` = id of the question being edited). + * + * @param \App\Model\Entity\Slide $slide Slide + * @param array $data Request data + * @param int|null $except Question id to ignore in the duplicate check + * @return string + * @throws \App\Service\VoteException + */ + protected function qaQuestionText(Slide $slide, array $data, ?int $except = null): string + { + $text = trim((string)preg_replace('/\s+/u', ' ', self::stringField($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); + $others = $this->Responses->questionsOf($slide->id)->select(['id', 'text_value'])->disableHydration(); + foreach ($others as $row) { + if ($row['id'] !== $except && mb_strtolower((string)$row['text_value']) === $key) { + throw new VoteException(__('Diese Frage wurde schon gestellt. Du kannst sie gleich beim Abstimmen unterstützen.')); + } + } + + return $text; + } + + /** + * Q&A: changes (`edit`, new text in `question`) or deletes (`delete`) an own question, + * only while collecting – later the question may already carry upvotes or be discussed. + * Deleting also removes its upvotes (left over if the presenter stepped back from voting). + * + * @param \App\Model\Entity\Slide $slide Slide + * @param list $ownQuestions Ids of the participant's questions + * @param string $action `edit` or `delete` + * @param array $data Request data (`question_id`, `question`) + * @return void + * @throws \App\Service\VoteException + */ + protected function editQuestion(Slide $slide, array $ownQuestions, string $action, array $data): void + { + if ($slide->qaStage() !== Slide::QA_COLLECT) { + throw new VoteException(__('Fragen können nur geändert werden, solange sie gesammelt werden.')); + } + $id = is_scalar($data['question_id'] ?? null) ? filter_var($data['question_id'], FILTER_VALIDATE_INT) : false; + if ($id === false || !in_array($id, $ownQuestions, true)) { + throw new VoteException(__('Diese Frage gibt es nicht mehr oder sie stammt nicht von dir.')); + } + $question = $this->Responses->get($id); + if ($action === 'delete') { + $this->Responses->deleteAll(['slide_id' => $slide->id, 'parent_id' => $id]); + $this->Responses->deleteOrFail($question); + + return; + } + $question->text_value = $this->qaQuestionText($slide, $data, $id); + $this->Responses->saveOrFail($question); + } + /** * Normalized key of a word cloud term: whitespace collapsed, trimmed, cut to * MAX_WORD_LENGTH. Use wordKey() for case-insensitive comparison. @@ -394,6 +530,11 @@ class VoteService if (($data['vote'] ?? null) === 'down') { return $this->downvoteRows($slide, self::stringField($data, 'word'), $existing, $downvoted); } + if (($data['vote'] ?? null) === 'remove') { + $this->removeWord($slide, $participantHash, self::stringField($data, 'word')); + + return []; + } $input = array_filter( array_merge((array)($data['words'] ?? []), (array)($data['word'] ?? [])), @@ -439,6 +580,36 @@ class VoteService return array_map(fn(string $word) => ['text_value' => $word], $words); } + /** + * Word cloud: withdraws the participant's own entry for a term – named/upvoted or downvoted – + * e.g. to fix a typo by entering it again. Only the participant's own rows are touched; the term + * stays in the cloud as long as others named it. + * + * @param \App\Model\Entity\Slide $slide Slide + * @param string $participantHash Participant hash + * @param string $word Word to withdraw + * @return void + * @throws \App\Service\VoteException + */ + protected function removeWord(Slide $slide, string $participantHash, string $word): void + { + $key = self::wordKey($word); + $ids = []; + $own = $this->Responses->find() + ->select(['id', 'text_value']) + ->where(['slide_id' => $slide->id, 'participant_hash' => $participantHash, 'text_value IS NOT' => null]) + ->disableHydration(); + foreach ($own as $row) { + if (self::wordKey((string)$row['text_value']) === $key) { + $ids[] = $row['id']; + } + } + if ($key === '' || $ids === []) { + throw new VoteException(__('Diesen Begriff hast du nicht genannt.')); + } + $this->Responses->deleteAll(['id IN' => $ids]); + } + /** * @param \App\Model\Entity\Slide $slide Slide * @param string $word Word to downvote @@ -497,11 +668,23 @@ class VoteService throw new VoteException(__('Bitte wähle einen Wert zwischen {0} und {1}.', $min, $max)); } // The optional comment is stored in the same row; ignored if the slide has no comment field. - $comment = $slide->hasComments() ? trim(self::stringField($data, 'comment')) : ''; + return [['numeric_value' => $value, 'text_value' => $slide->hasComments() ? self::comment($data) : null]]; + } + + /** + * Optional scale comment from the request: trimmed, empty = null. + * + * @param array $data Request data + * @return string|null + * @throws \App\Service\VoteException + */ + protected static function comment(array $data): ?string + { + $comment = trim(self::stringField($data, 'comment')); if (mb_strlen($comment) > self::MAX_TEXT_LENGTH) { throw new VoteException(__('Der Kommentar darf maximal {0} Zeichen lang sein.', self::MAX_TEXT_LENGTH)); } - return [['numeric_value' => $value, 'text_value' => $comment === '' ? null : $comment]]; + return $comment === '' ? null : $comment; } } diff --git a/templates/Participate/view.php b/templates/Participate/view.php index 69466a1..3d20416 100644 --- a/templates/Participate/view.php +++ b/templates/Participate/view.php @@ -8,8 +8,11 @@ * @var \App\Model\Entity\Slide|null $slide * @var array $state * @var string $participantHash Seed for the shuffled items of ordering slides + * @var string|null $ownText Own open answer or scale comment (editable while voting is open) * @var int $pollIntervalMs */ +use App\Service\VoteService; + $this->assign('title', $poll->title); $this->assign('bodyClass', 'participant'); $voteUrl = ['_name' => 'participate:vote', 'code' => $poll->join_code]; @@ -215,8 +218,38 @@ $countdown = function (?int $remaining): string {

Form->button(__('Begriff senden'), ['class' => 'button button--primary button--block']) ?> Form->end() ?> +

✓

+ isVotingOpen()) : + $isOpen = $slide->type === 'open'; ?> + +

+
+ +
+ __('Antwort bearbeiten'), + $ownText !== null => __('Kommentar bearbeiten'), + default => __('Kommentar hinzufügen'), + } ?> + Form->create(null, ['url' => ['_name' => 'participate:edit', 'code' => $poll->join_code], 'class' => 'vote-form']) ?> + Form->hidden('slide_id', ['value' => $slide->id]) ?> + + +

+ Form->button($isOpen ? __('Antwort speichern') : __('Kommentar speichern'), ['class' => 'button button--primary button--block']) ?> + Form->end() ?> +
+ is_voting_open) : ?>

diff --git a/tests/TestCase/Controller/ParticipateControllerTest.php b/tests/TestCase/Controller/ParticipateControllerTest.php index 0fd71ea..6608179 100644 --- a/tests/TestCase/Controller/ParticipateControllerTest.php +++ b/tests/TestCase/Controller/ParticipateControllerTest.php @@ -180,4 +180,62 @@ class ParticipateControllerTest extends TestCase $this->assertArrayHasKey('state', $body); $this->assertSame(2, TableRegistry::getTableLocator()->get('Responses')->find()->where(['slide_id' => $slide->id])->count()); } + + public function testOpenAnswerCanBeEditedWhileVotingIsOpen(): void + { + [$poll] = $this->createPoll(); + $slide = $this->createSlide($poll, Slide::TYPE_OPEN); + $this->goLive($poll, $slide); + $responses = TableRegistry::getTableLocator()->get('Responses'); + + $this->cookie('plenario_pid', self::PID); + $this->post("/p/{$poll->join_code}/vote", ['slide_id' => $slide->id, 'text' => 'Tipfehler']); + $this->cookie('plenario_pid', self::PID); + $this->get('/p/' . $poll->join_code); + $this->assertResponseContains('Antwort bearbeiten'); + $this->assertResponseContains('Tipfehler'); + + $this->cookie('plenario_pid', self::PID); + $this->post("/p/{$poll->join_code}/edit", ['slide_id' => $slide->id, 'text' => ' Tippfehler ']); + $this->assertRedirect(['_name' => 'participate', 'code' => $poll->join_code]); + $this->assertFlashMessage('Deine Antwort wurde geändert.'); + $this->assertSame(1, $responses->find()->count()); + $this->assertSame('Tippfehler', $responses->find()->firstOrFail()->text_value); + + // An open answer cannot be emptied. + $this->cookie('plenario_pid', self::PID); + $this->post("/p/{$poll->join_code}/edit", ['slide_id' => $slide->id, 'text' => ' ']); + $this->assertFlashMessage('Bitte gib eine Antwort ein.'); + $this->assertSame('Tippfehler', $responses->find()->firstOrFail()->text_value); + + // Without an own answer there is nothing to edit (and nothing is created). + $this->cookie('plenario_pid', str_repeat('f', 32)); + $this->post("/p/{$poll->join_code}/edit", ['slide_id' => $slide->id, 'text' => 'Neu']); + $this->assertFlashMessage('Du hast hier noch nicht geantwortet.'); + $this->assertSame(1, $responses->find()->count()); + + // Closed: no form, no change. + TableRegistry::getTableLocator()->get('Slides')->updateAll(['is_voting_open' => false], ['id' => $slide->id]); + $this->cookie('plenario_pid', self::PID); + $this->get('/p/' . $poll->join_code); + $this->assertResponseNotContains('Antwort bearbeiten'); + $this->cookie('plenario_pid', self::PID); + $this->post("/p/{$poll->join_code}/edit", ['slide_id' => $slide->id, 'text' => 'Zu spät']); + $this->assertFlashMessage('Die Abstimmung zu dieser Frage ist geschlossen.'); + $this->assertSame('Tippfehler', $responses->find()->firstOrFail()->text_value); + } + + public function testChoiceAnswersCannotBeEdited(): void + { + [$poll] = $this->createPoll(); + $slide = $this->createSlide($poll, Slide::TYPE_CHOICE); + $this->goLive($poll, $slide); + + $this->cookie('plenario_pid', self::PID); + $this->post("/p/{$poll->join_code}/vote", ['slide_id' => $slide->id, 'option_id' => $slide->slide_options[0]->id]); + $this->cookie('plenario_pid', self::PID); + $this->post("/p/{$poll->join_code}/edit", ['slide_id' => $slide->id, 'text' => 'Hack']); + $this->assertFlashMessage('Diese Antwort kann nicht mehr geändert werden.'); + $this->assertFalse(TableRegistry::getTableLocator()->get('Responses')->exists(['text_value' => 'Hack'])); + } } diff --git a/tests/TestCase/Controller/ScaleCommentsTest.php b/tests/TestCase/Controller/ScaleCommentsTest.php index 989d689..921faa9 100644 --- a/tests/TestCase/Controller/ScaleCommentsTest.php +++ b/tests/TestCase/Controller/ScaleCommentsTest.php @@ -257,4 +257,82 @@ class ScaleCommentsTest extends TestCase $this->assertStringContainsString('Bewertung 4', $html); } + + public function testParticipantCanEditOwnCommentWhileOpen(): void + { + [$poll, , $slide] = $this->scaleWithComments(); + $this->cookie('plenario_pid', str_repeat('a', 32)); + + $this->get('/p/' . $poll->join_code); + $this->assertResponseContains('Kommentar bearbeiten'); + $this->assertResponseContains('Sehr <gut>'); + + $this->post('/p/' . $poll->join_code . '/edit', ['slide_id' => $slide->id, 'comment' => ' Sehr gut! ', 'value' => '1']); + $this->assertRedirect('/p/' . $poll->join_code); + $this->assertFlashMessage('Dein Kommentar wurde gespeichert.'); + + $rows = $this->slidesTable()->Responses->find() + ->where(['slide_id' => $slide->id, 'participant_hash' => $this->hash('a', $poll)]) + ->all(); + $this->assertCount(1, $rows); + $this->assertSame('Sehr gut!', $rows->first()->text_value); + $this->assertSame(4, $rows->first()->numeric_value, 'the rating stays unchanged'); + + // Repeating the request is harmless, an empty comment removes it. + $this->post('/p/' . $poll->join_code . '/edit', ['slide_id' => $slide->id, 'comment' => ' Sehr gut! ']); + $this->post('/p/' . $poll->join_code . '/edit', ['slide_id' => $slide->id, 'comment' => '']); + $this->assertFlashMessage('Dein Kommentar wurde entfernt.'); + $this->assertNull($this->slidesTable()->Responses->get($rows->first()->id)->text_value); + } + + public function testParticipantWithoutCommentCanAddOne(): void + { + [$poll, , $slide] = $this->scaleWithComments(); + $this->cookie('plenario_pid', str_repeat('b', 32)); + + $this->get('/p/' . $poll->join_code); + $this->assertResponseContains('Kommentar hinzufügen'); + + $this->post('/p/' . $poll->join_code . '/edit', ['slide_id' => $slide->id, 'comment' => 'Nachgereicht']); + $row = $this->slidesTable()->Responses->find() + ->where(['slide_id' => $slide->id, 'participant_hash' => $this->hash('b', $poll)]) + ->firstOrFail(); + $this->assertSame('Nachgereicht', $row->text_value); + } + + public function testCommentCannotBeEditedAfterVotingClosed(): void + { + [$poll, , $slide] = $this->scaleWithComments(); + $this->slidesTable()->updateAll(['is_voting_open' => false], ['id' => $slide->id]); + $this->cookie('plenario_pid', str_repeat('a', 32)); + + $this->get('/p/' . $poll->join_code); + $this->assertResponseNotContains('Kommentar bearbeiten'); + + $this->post('/p/' . $poll->join_code . '/edit', ['slide_id' => $slide->id, 'comment' => 'Zu spät']); + $this->assertFlashMessage('Die Abstimmung zu dieser Frage ist geschlossen.'); + $this->assertSame('Sehr ', $this->slidesTable()->Responses->find() + ->where(['slide_id' => $slide->id, 'participant_hash' => $this->hash('a', $poll)]) + ->firstOrFail()->text_value); + } + + public function testCommentEditNeedsARatingAndACommentField(): void + { + [$poll, , $slide] = $this->scaleWithComments(); + $votes = new VoteService(); + + try { + $votes->editText($poll, $slide, $this->hash('z', $poll), ['comment' => 'Ohne Bewertung']); + $this->fail('Expected VoteException'); + } catch (VoteException $e) { + $this->assertSame('Bitte gib zuerst deine Bewertung ab.', $e->getMessage()); + } + $this->assertFalse($this->slidesTable()->Responses->exists(['text_value' => 'Ohne Bewertung'])); + + $plain = $this->createSlide($poll, Slide::TYPE_SCALE, ['settings' => ['scale_min' => 1, 'scale_max' => 5]]); + $poll = $this->goLive($poll, $plain); + $votes->submit($poll, $plain, $this->hash('a', $poll), ['value' => 3]); + $this->expectException(VoteException::class); + $votes->editText($poll, $plain, $this->hash('a', $poll), ['comment' => 'Eingeschmuggelt']); + } } diff --git a/tests/TestCase/Service/QaTest.php b/tests/TestCase/Service/QaTest.php index 409735c..10f2f1a 100644 --- a/tests/TestCase/Service/QaTest.php +++ b/tests/TestCase/Service/QaTest.php @@ -297,4 +297,93 @@ class QaTest extends TestCase $slide = $this->slidesTable()->get($slide->id); $this->assertSame([Slide::QA_COLLECT, true, null], [$slide->qaStage(), $slide->is_voting_open, $slide->focus_response_id]); } + + public function testOwnQuestionCanBeEditedWhileCollecting(): void + { + [$poll, $slide] = $this->createQa(); + $votes = new VoteService(); + $mine = $this->ask($poll, $slide, 'p1', 'Wan gehts los?'); + $other = $this->ask($poll, $slide, 'p2', 'Gibt es Kaffee?'); + + $votes->submit($poll, $slide, 'p1', ['vote' => 'edit', 'question_id' => $mine, 'question' => ' Wann geht es los? ']); + $responses = $this->fetchTable('Responses'); + $this->assertSame('Wann geht es los?', $responses->get($mine)->get('text_value')); + // Repeating the same edit is harmless, case-only changes of the own question are fine. + $votes->submit($poll, $slide, 'p1', ['vote' => 'edit', 'question_id' => $mine, 'question' => 'WANN geht es los?']); + $this->assertSame(2, $responses->find()->where(['slide_id' => $slide->id])->count()); + + $this->assertVoteFails('Diese Frage wurde schon gestellt. Du kannst sie gleich beim Abstimmen unterstützen.', fn() => $votes->submit( + $poll, + $slide, + 'p1', + ['vote' => 'edit', 'question_id' => $mine, 'question' => 'gibt es kaffee?'], + )); + $this->assertVoteFails('Bitte gib eine Frage ein.', fn() => $votes->submit( + $poll, + $slide, + 'p1', + ['vote' => 'edit', 'question_id' => $mine, 'question' => ' '], + )); + $this->assertVoteFails('Diese Frage gibt es nicht mehr oder sie stammt nicht von dir.', fn() => $votes->submit( + $poll, + $slide, + 'p1', + ['vote' => 'edit', 'question_id' => $other, 'question' => 'Gekapert'], + )); + $this->assertSame('Gibt es Kaffee?', $responses->get($other)->get('text_value')); + } + + public function testOwnQuestionCanBeDeletedWhileCollecting(): void + { + [$poll, $slide] = $this->createQa(); + $votes = new VoteService(); + $mine = $this->ask($poll, $slide, 'p1', 'Weg damit'); + $other = $this->ask($poll, $slide, 'p2', 'Bleibt'); + + $this->assertVoteFails('Diese Frage gibt es nicht mehr oder sie stammt nicht von dir.', fn() => $votes->submit( + $poll, + $slide, + 'p1', + ['vote' => 'delete', 'question_id' => $other], + )); + + // Upvotes left over from a voting stage the presenter stepped back from go with it. + $slide = $this->stage($slide, Slide::QA_VOTE); + $this->vote($poll, $slide, 'p2', $mine); + $slide = $this->stage($slide, Slide::QA_COLLECT); + + $votes->submit($poll, $slide, 'p1', ['vote' => 'delete', 'question_id' => $mine]); + $responses = $this->fetchTable('Responses'); + $this->assertSame([$other], $responses->find()->where(['slide_id' => $slide->id])->all()->extract('id')->toList()); + $state = (new PollStateService())->qaState($slide, 'p1'); + $this->assertSame([], $state['mine']); + + // Deleting again is answered with a message, nothing else happens. + $this->assertVoteFails('Diese Frage gibt es nicht mehr oder sie stammt nicht von dir.', fn() => $votes->submit( + $poll, + $slide, + 'p1', + ['vote' => 'delete', 'question_id' => $mine], + )); + } + + public function testQuestionsAreFixedOnceVotingStarts(): void + { + [$poll, $slide] = $this->createQa(); + $votes = new VoteService(); + $mine = $this->ask($poll, $slide, 'p1', 'Feste Frage'); + + foreach ([Slide::QA_VOTE, Slide::QA_DISCUSS] as $stage) { + $slide = $this->stage($slide, $stage); + $poll = $this->fetchTable('Polls')->get($poll->id); + foreach (['edit', 'delete'] as $action) { + try { + $votes->submit($poll, $slide, 'p1', ['vote' => $action, 'question_id' => $mine, 'question' => 'Geändert']); + $this->fail('VoteException expected'); + } catch (VoteException) { + } + } + } + $this->assertSame('Feste Frage', $this->fetchTable('Responses')->get($mine)->get('text_value')); + } } diff --git a/tests/TestCase/Service/VoteServiceTest.php b/tests/TestCase/Service/VoteServiceTest.php index 701ad33..347e4a4 100644 --- a/tests/TestCase/Service/VoteServiceTest.php +++ b/tests/TestCase/Service/VoteServiceTest.php @@ -279,4 +279,49 @@ class VoteServiceTest extends TestCase $this->assertEquals($slide->modified, $this->slidesTable()->get($slide->id)->modified); $this->assertSame($slide->position, $this->slidesTable()->get($slide->id)->position); } + + public function testWordcloudOwnEntryCanBeRemoved(): void + { + [$poll] = $this->createPoll(); + $slide = $this->createSlide($poll, Slide::TYPE_WORDCLOUD); + $poll = $this->goLive($poll, $slide); + $service = new VoteService(); + $service->submit($poll, $slide, 'p1', ['word' => 'Kafee']); + $service->submit($poll, $slide, 'p1', ['word' => 'Tee']); + $service->submit($poll, $slide, 'p2', ['word' => 'tee']); + $service->submit($poll, $slide, 'p2', ['word' => 'Kafee', 'vote' => 'down']); + + $state = (new PollStateService())->wordState($slide, 'p1'); + $this->assertSame([['text' => 'Kafee', 'down' => false], ['text' => 'Tee', 'down' => false]], $state['own']); + + // Only the own row goes: "Tee" stays with the other upvote, "Kafee" keeps p2's downvote. + $service->submit($poll, $slide, 'p1', ['word' => 'TEE', 'vote' => 'remove']); + $service->submit($poll, $slide, 'p1', ['word' => 'Kafee', 'vote' => 'remove']); + $results = (new ResultsService())->forSlide($slide); + $this->assertSame([['tee', 1, 0]], array_map(fn($w) => [$w['text'], $w['count'], $w['down']], $results['words'])); + $this->assertSame([], (new PollStateService())->wordState($slide, 'p1')['own']); + $this->assertSame(2, $this->fetchTable('Responses')->find()->where(['slide_id' => $slide->id])->count()); + + // A downvote can be withdrawn too; afterwards the word can be named again. + $service->submit($poll, $slide, 'p2', ['word' => 'kafee', 'vote' => 'remove']); + $this->assertSame([['text' => 'tee', 'down' => false]], (new PollStateService())->wordState($slide, 'p2')['own']); + $service->submit($poll, $slide, 'p1', ['word' => 'Kaffee']); + $this->assertSame(['kaffee'], (new PollStateService())->wordState($slide, 'p1')['mine']); + + // Removing again (or someone else's word) changes nothing. + foreach ([['p1', 'Tee'], ['p3', 'Kaffee'], ['p1', '']] as [$participant, $word]) { + try { + $service->submit($poll, $slide, $participant, ['word' => $word, 'vote' => 'remove']); + $this->fail('VoteException expected for ' . $participant . '/' . $word); + } catch (VoteException $e) { + $this->assertSame('Diesen Begriff hast du nicht genannt.', $e->getMessage()); + } + } + $this->assertSame(2, $this->fetchTable('Responses')->find()->where(['slide_id' => $slide->id])->count()); + + $this->slidesTable()->updateAll(['is_voting_open' => false], ['id' => $slide->id]); + $slide = $this->slidesTable()->get($slide->id); + $this->expectException(VoteException::class); + $service->submit($poll, $slide, 'p1', ['word' => 'Kaffee', 'vote' => 'remove']); + } } diff --git a/webroot/css/plenario.css b/webroot/css/plenario.css index 0128c4d..679be68 100644 --- a/webroot/css/plenario.css +++ b/webroot/css/plenario.css @@ -336,6 +336,13 @@ textarea { resize: vertical; } .suggestion__meta { font-size: .8rem; color: var(--muted); white-space: nowrap; align-self: center; } .word-message { min-height: 1.4em; margin: 8px 0 0; font-size: .9rem; color: var(--ok); } .word-message.is-error { color: var(--danger); } +.own-words { margin-top: 20px; } +.own-words__heading { font-size: 1rem; margin: 0 0 4px; } +.own-words__list { list-style: none; padding: 0; margin: 8px 0 0; display: flex; flex-wrap: wrap; gap: 8px; } +.own-words__item { display: inline-flex; align-items: center; gap: 2px; padding: 2px 2px 2px 12px; border-radius: 999px; background: var(--primary-soft); overflow-wrap: anywhere; } +.own-words__item.is-down { background: var(--surface-2); color: var(--muted); } +.own-words__remove { min-width: 36px; min-height: 36px; border: 0; border-radius: 999px; background: transparent; color: inherit; font-size: 1.2rem; line-height: 1; cursor: pointer; } +.own-words__remove:hover, .own-words__remove:focus-visible { background: var(--border); } .vote-form textarea { margin: 12px 0 16px; } .vote-form .button { margin-top: 12px; } .scale { display: flex; gap: 6px; margin: 20px 0 6px; } @@ -496,6 +503,12 @@ textarea { resize: vertical; } .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-item:has(.qa-own-actions) { flex-wrap: wrap; } +.qa-own-actions { flex: none; display: inline-flex; gap: 4px; margin-left: auto; } +.qa-own-actions .button { min-height: 36px; } +.qa-item.is-editing { display: block; } +.qa-edit textarea { width: 100%; } +.qa-edit__actions { display: flex; gap: 8px; justify-content: flex-end; margin-top: 8px; } .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); } @@ -530,12 +543,24 @@ button.qa-steps__step:hover:not(:disabled) { color: var(--text); border-color: v .answers-page li { padding: 12px 16px; border: 1px solid var(--border); border-radius: 8px; margin-bottom: 8px; background: var(--surface); white-space: pre-line; overflow-wrap: anywhere; } .answers-page time { display: block; color: var(--muted); font-size: .8rem; margin-top: 4px; } .scale-comment { display: block; margin-top: 16px; font-weight: 600; } +.own-comment__label { margin: 16px 0 4px; color: var(--muted); } +.own-comment { margin: 0; padding: 8px 12px; border-left: 3px solid var(--border); overflow-wrap: anywhere; } +.own-comment__edit { margin-top: 12px; } +.own-comment__edit summary { cursor: pointer; color: var(--muted); width: max-content; max-width: 100%; } +.own-comment__edit summary:hover { color: var(--text); } .comments { margin-top: 20px; padding: 16px 20px; background: var(--surface-2); border-radius: 14px; } .comments__counter { margin: 0 0 6px; font-size: .85em; font-weight: 700; text-transform: uppercase; letter-spacing: .08em; color: var(--muted); font-variant-numeric: tabular-nums; } .comments__text { margin: 0; font-size: 1.25em; font-weight: 600; white-space: pre-line; overflow-wrap: anywhere; } .comments__text::before { content: '„'; } .comments__text::after { content: '“'; } .comments__value { margin: 6px 0 0; color: var(--muted); font-size: .9em; } +.comments__progress { height: 4px; margin-top: 14px; border-radius: 2px; background: var(--border); overflow: hidden; } +.comments__progress[hidden] { display: block; visibility: hidden; } /* keeps the layout steady while paused */ +.comments__progress-fill { height: 100%; background: var(--primary); transform: scaleX(0); transform-origin: left; } +@keyframes comment-progress { + from { transform: scaleX(0); } + to { transform: scaleX(1); } +} .comments__nav { display: flex; gap: 8px; justify-content: flex-end; margin-top: 12px; } .comments__button { min-width: 44px; min-height: 44px; } @media (prefers-reduced-motion: no-preference) { diff --git a/webroot/js/plenario.js b/webroot/js/plenario.js index 652058d..4bb358e 100644 --- a/webroot/js/plenario.js +++ b/webroot/js/plenario.js @@ -303,6 +303,9 @@ timer: null, items: [], node: null, + // Countdown of the comment shown (drives the progress bar across re-renders). + startedAt: 0, + duration: 0, // Time per comment: enough to read it on the stage, within sensible bounds. BASE_MS: 2500, @@ -338,6 +341,10 @@ el('p', { class: 'comments__counter', 'data-comment-counter': '' }), el('blockquote', { class: 'comments__text', 'data-comment-text': '' }), el('p', { class: 'comments__value', 'data-comment-value': '' }), + // Time left until the next comment; decorative, the counter carries the information. + items.length < 2 ? null : el('div', { class: 'comments__progress', 'data-comment-progress': '', 'aria-hidden': 'true' }, [ + el('div', { class: 'comments__progress-fill' }) + ]), items.length < 2 ? null : el('div', { class: 'comments__nav' }, [ button('prev', 'Vorheriger Kommentar', '‹'), button('toggle', '', ''), @@ -360,10 +367,10 @@ Comments.update(false); }); Comments.node = node; - Comments.update(false); if (!Comments.timer) { Comments.restart(); } + Comments.update(false); return node; }, @@ -388,18 +395,44 @@ /** (Re)start the countdown for the comment currently shown. */ restart: function () { clearTimeout(Comments.timer); + Comments.startedAt = Date.now(); + Comments.duration = Comments.delay(Comments.items[Comments.index]); Comments.timer = setTimeout(function () { if (!Comments.node || !document.body.contains(Comments.node)) { // Slide changed: stop until the next comment list is rendered. Comments.timer = null; return; } - if (!Comments.paused && Comments.items.length > 1 && !document.hidden) { + var advance = !Comments.paused && Comments.items.length > 1 && !document.hidden; + if (advance) { Comments.step(1); - Comments.update(true); } Comments.restart(); - }, Comments.delay(Comments.items[Comments.index])); + if (advance) { + Comments.update(true); + } else { + Comments.progress(); + } + }, Comments.duration); + }, + + /** + * Fills the progress bar over the remaining time of the current comment. + * Picks up where it was after a re-render (negative animation delay); hidden while paused. + */ + progress: function () { + var bar = Comments.node && Comments.node.querySelector('[data-comment-progress]'); + if (!bar) { + return; + } + var fill = bar.firstChild; + bar.hidden = Comments.paused; + fill.style.animation = 'none'; + void fill.offsetWidth; // restart the CSS animation + if (!Comments.paused) { + var elapsed = Math.min(Date.now() - Comments.startedAt, Comments.duration); + fill.style.animation = 'comment-progress ' + Comments.duration + 'ms linear -' + elapsed + 'ms forwards'; + } }, update: function (animate) { @@ -427,6 +460,7 @@ toggle.setAttribute('title', label); toggle.setAttribute('aria-pressed', Comments.paused ? 'true' : 'false'); } + Comments.progress(); } }; @@ -1351,6 +1385,9 @@ var qaForm = qaRoot ? qaRoot.querySelector('[data-qa-form]') : null; var qaRendered = ''; var qaSending = false; + // Own question being edited: polling must not re-render the list (and wipe the draft) meanwhile. + var qaEditing = null; + var qaLatest = null; function qaSay(text, isError) { qaMessage.textContent = text; @@ -1369,6 +1406,9 @@ window.location.reload(); return null; } + if (response.ok && data.vote === 'edit') { + qaEditing = null; + } renderQa(response.state); return response; }).catch(function () { @@ -1385,6 +1425,10 @@ if (!qaList || !qa) { return; } + qaLatest = state; + if (qaEditing !== null) { + return; // rendered once the edit is saved or cancelled + } var key = JSON.stringify(qa); if (key === qaRendered) { return; @@ -1403,11 +1447,16 @@ } 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' : '') }, [ + var item = 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 ]); + if (mine) { + item.appendChild(qaOwnActions(item, question)); + } + return item; }))); + restoreQaFocus(focused); return; } @@ -1494,6 +1543,10 @@ }))); } + restoreQaFocus(focused); + } + + function restoreQaFocus(focused) { if (focused) { var again = qaList.querySelector('[data-question-id="' + focused + '"]'); if (again && !again.disabled) { @@ -1502,6 +1555,87 @@ } } + /** Ends editing and shows the latest state, focus back on the question's edit button. */ + function qaStopEditing(id) { + qaEditing = null; + qaRendered = ''; + renderQa(qaLatest); + restoreQaFocus(id + '-edit'); + } + + /** + * Collect stage: edit and delete buttons for an own question. Editing swaps the item + * content for a small form in place. + */ + function qaOwnActions(item, question) { + var button = function (action, text, extraClass) { + return el('button', { + type: 'button', + class: 'button button--small button--ghost' + (extraClass || ''), + 'aria-label': text + ': ' + question.text, + 'data-question-id': question.id + '-' + action, + text: text + }); + }; + var edit = button('edit', 'Bearbeiten'); + var remove = button('delete', 'Löschen', ' button--danger'); + + edit.addEventListener('click', function () { + qaEditing = question.id; + qaSay('', false); + var field = el('textarea', { name: 'question', rows: '3', maxlength: '500', required: '', 'aria-label': 'Deine Frage bearbeiten' }); + field.value = question.text; + var form = el('form', { class: 'qa-edit' }, [ + field, + el('div', { class: 'qa-edit__actions' }, [ + el('button', { type: 'submit', class: 'button button--small button--primary', text: 'Speichern' }), + el('button', { type: 'button', class: 'button button--small', 'data-qa-cancel': '', text: 'Abbrechen' }) + ]) + ]); + form.addEventListener('submit', function (event) { + event.preventDefault(); + var text = field.value.trim(); + if (!text) { + qaSay('Bitte gib eine Frage ein.', true); + field.focus(); + return; + } + if (text === question.text) { + qaStopEditing(question.id); + return; + } + sendQa({ vote: 'edit', question_id: question.id, question: text }).then(function (response) { + if (response && response.ok) { + restoreQaFocus(question.id + '-edit'); + } else { + field.focus(); + } + }); + }); + form.querySelector('[data-qa-cancel]').addEventListener('click', function () { + qaStopEditing(question.id); + }); + field.addEventListener('keydown', function (event) { + if (event.key === 'Escape') { + qaStopEditing(question.id); + } + }); + item.textContent = ''; + item.classList.add('is-editing'); + item.appendChild(form); + field.focus(); + field.setSelectionRange(field.value.length, field.value.length); + }); + + remove.addEventListener('click', function () { + if (window.confirm('Deine Frage wirklich löschen?\n\n„' + question.text + '“')) { + sendQa({ vote: 'delete', question_id: question.id }); + } + }); + + return el('span', { class: 'qa-own-actions' }, [edit, remove]); + } + if (qaForm) { qaForm.addEventListener('submit', function (event) { event.preventDefault(); @@ -1521,6 +1655,7 @@ function renderResults(state) { current = state; renderQa(state); + renderOwnWords(state); if (!card || !container) { return; } @@ -1568,14 +1703,17 @@ sending = true; var slideId = wordForm.querySelector('[name=slide_id]').value; var data = { slide_id: slideId, word: text }; - if (vote === 'down') { - data.vote = 'down'; + if (vote) { + data.vote = vote; } postJson(voteUrl, data).then(function (response) { - var success = vote === 'down' ? '✓ „' + text + '“ abgelehnt.' : '✓ „' + text + '“ ist angekommen.'; + var success = { + down: '✓ „' + text + '“ abgelehnt.', + remove: '✓ „' + text + '“ entfernt.' + }[vote] || '✓ „' + text + '“ ist angekommen.'; message.textContent = response.ok ? success : response.message; message.classList.toggle('is-error', !response.ok); - if (response.ok && vote !== 'down') { + if (response.ok && !vote) { input.value = ''; closeSuggestions(); } @@ -1588,6 +1726,46 @@ }); } + // Own terms with a remove button (fix a typo by removing and entering again). + var ownWords = root.querySelector('[data-own-words]'); + var ownWordsRendered = ''; + + function renderOwnWords(state) { + if (!ownWords || !state.words) { + return; + } + var own = state.words.own || []; + var key = JSON.stringify(own); + if (key === ownWordsRendered) { + return; + } + ownWordsRendered = key; + // Keep keyboard focus in the list after removing a term. + var hadFocus = ownWords.contains(document.activeElement); + var listNode = ownWords.querySelector('[data-own-words-list]'); + listNode.textContent = ''; + ownWords.hidden = own.length === 0; + own.forEach(function (word) { + var label = word.down ? 'Ablehnung von „' + word.text + '“ zurücknehmen' : '„' + word.text + '“ entfernen'; + var remove = el('button', { type: 'button', class: 'own-words__remove', 'aria-label': label, title: label }, [ + el('span', { 'aria-hidden': 'true', text: '×' }) + ]); + remove.addEventListener('click', function () { + sendWord(word.text, 'remove'); + }); + listNode.appendChild(el('li', { class: 'own-words__item' + (word.down ? ' is-down' : '') }, [ + el('span', { text: (word.down ? '− ' : '') + word.text }), + remove + ])); + }); + if (hadFocus) { + var next = listNode.querySelector('button') || input; + if (next) { + next.focus(); + } + } + } + function applyWordState(state) { if (state.version !== version || !state.words) { // Slide changed or voting closed.