diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..c912c95 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,16 @@ +.git +.gitea +.gitattributes +.phpunit.cache +.claude +vendor +tmp +logs +data +tests +config/app_local.php +config/.env +.env +CLAUDE.local.md +Dockerfile +docker-compose.yml diff --git a/.gitea/workflows/docker.yml b/.gitea/workflows/docker.yml new file mode 100644 index 0000000..bb33172 --- /dev/null +++ b/.gitea/workflows/docker.yml @@ -0,0 +1,46 @@ +# Container image build (Gitea Actions): builds the Dockerfile and pushes it to the Gitea registry +# on every push to main (main is protected: only merged PRs with green tests land there). +# +# Repository variables (Settings → Actions → Variables): +# DOCKER_REPO registry host, e.g. gitea.gnilebein.de +# IMAGE_NAME image name, e.g. plenario +# Repository secrets: +# PAT personal access token with package write permission +# +# Image: ${DOCKER_REPO}/${owner}/${IMAGE_NAME}:latest and : +name: Container Image + +on: + push: + branches: + - main + workflow_dispatch: + +jobs: + docker-build-image: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v6 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: Login to registry + uses: docker/login-action@v4 + with: + registry: ${{ vars.DOCKER_REPO }} + username: ${{ gitea.actor }} + password: ${{ secrets.PAT }} + + - name: Build and push + uses: docker/build-push-action@v6 + with: + file: ./Dockerfile + platforms: linux/amd64 + pull: true + push: true + provenance: false + tags: | + ${{ vars.DOCKER_REPO }}/${{ gitea.repository_owner }}/${{ vars.IMAGE_NAME }}:latest + ${{ vars.DOCKER_REPO }}/${{ gitea.repository_owner }}/${{ vars.IMAGE_NAME }}:${{ gitea.sha }} diff --git a/AGENTS.md b/AGENTS.md index 206bf54..244b94e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -58,7 +58,7 @@ src/ HomeController Startseite, Anlegen (/create), Bestätigung, Join, Recover AdminAppController Basis für /admin/{token}: löst Poll über Token-Hash auf (404 sonst), setzt Privacy-Header (no-referrer, no-store) 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, + SlidesController Folien-CRUD, Ein-/Ausblenden (`visibility`), Duplizieren (`duplicate` → `SlidesTable::duplicate()`, Kopie direkt dahinter, öffnet das Formular der Kopie), 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, eigene Antwort/Kommentar bearbeiten; anonymes Cookie plenario_pid EmbedController /e/{key}/{id}: eine Folie zum Einbetten (z. B. Canva), activate/heartbeat/pause/control @@ -95,6 +95,7 @@ tests/ PHPUnit; PlenarioTestTrait erzeugt Testdaten, Fixtures `embed_key` (Einbett-Schlüssel), `embed_seen_at` (letztes Lebenszeichen der eingebetteten Live-Folie), `paused_slide_id` (Folie vor der Pause), `comment_speed` (Tempo der Skala-Kommentare in Prozent, Standard 100) - `slides`: `type` (`choice|wordcloud|open|scale|content|quiz|youtube|qa|order`), `question`, `description`, `position`, + `is_hidden` (ausgeblendet: vorbereitet, aber nicht Teil der Präsentation), `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) @@ -165,7 +166,8 @@ tests/ PHPUnit; PlenarioTestTrait erzeugt Testdaten, Fixtures wird es während `vote` auf 0 gesetzt, springt `SlidesController::saveSlide()` nach `discuss`. Setting `allow_self_upvote` (Standard aus, für Themen-Priorisierung) erlaubt Stimmen auf eigene Fragen aus demselben Budget (State `qa.allowSelfUpvote`); bewusst aus, weil anonym sonst Selbstvermarktung die Rangfolge bestimmt; - Teilnehmende sehen alle Fragen in Eingangsreihenfolge **ohne** Zählung. `discuss`: Abstimmung zu, Fragen nach Upvotes + Teilnehmende sehen alle Fragen in Eingangsreihenfolge **ohne** Zählung; auch die Bühne (Presenter/Embed, PDF) bekommt in `vote` + keine Zählungen je Frage und keine Rangfolge (`ResultsService::qa()`, nur die Summe `upvotes`), damit niemand beeinflusst wird. `discuss`: Abstimmung zu, Fragen nach Upvotes sortiert (Gleichstand: älteste zuerst), `focus_response_id` = aktuelle Frage. In `discuss` blättern next/prev (→/←, Klicker) zuerst durch die Fragen, erst danach durch die Folien. Fokuswechsel per `updateAll` ohne `modified`, damit Teilnehmerseiten nicht neu laden. Teilnehmende bekommen nie `results`, sondern `qa` aus `PollStateService::qaState()`. @@ -195,6 +197,17 @@ tests/ PHPUnit; PlenarioTestTrait erzeugt Testdaten, Fixtures (`admin:reset`, Dashboard → „Sicherheit“). Nur Quiz (`ready`) und Q&A (`collect`) springen zurück, weil ihre Phasen ohne Antworten keinen Sinn ergeben; offen/geschlossen anderer Folien, aktuelle Folie/Pause, Einstellungen bleiben. Idempotent, in einer Transaktion. Tests: `PollResetTest.php`. +- **Duplizieren** (`slides:duplicate`, POST): kopiert Fragetext (+ „(Kopie)“), Beschreibung, Einstellungen und Optionen + inkl. `is_correct`, **nie Antworten**. Die Kopie landet direkt hinter dem Original und startet wie eine neue Folie + (`Slide::startFresh()`: Quiz `ready`, Q&A `collect`, sonst offen) – auch `add()` nutzt `startFresh()`. + Tests: `DuplicateSlideTest.php`. +- **Ausgeblendete Folien** (`is_hidden`, `slides:visibility` mit `hidden=1|0`, explizit statt Toggle → idempotent): + bleiben in der Verwaltung (gestrichelt, Badge „ausgeblendet“), gehören aber nicht zur Präsentation. Präsentation = + `SlidesTable::listForPoll($pollId, true)`: Start, →/←, `goto` (400 für ausgeblendete), Zähler im Presenter-State + (`count` ohne, `hiddenCount` = ausgeblendete), PDF-Export (Nummerierung wie in der Präsentation). Einbettung einer + ausgeblendeten Folie geht nicht live (`isHidden` im Embed-State). Eine ausgeblendete Folie darf nie live/pausiert sein: + Ausblenden der Live- oder pausierten Folie pausiert wie Löschen (`forgetSlide()` + `SlidesTable::replacementFor()` = + nächste sichtbare Folie, sonst die vorige). `is_hidden` ist nicht mass-assignable. Tests: `HiddenSlideTest.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()` / `forgetSlide()` setzen, nie `current_slide_id` direkt. Presenter: P bzw. der Pause-Button schaltet um (Aktionen `stop`/`resume`, beide idempotent, kein Server-Toggle), @@ -262,6 +275,15 @@ tests/ PHPUnit; PlenarioTestTrait erzeugt Testdaten, Fixtures Die Seite lädt bei Folienwechsel neu: der Wake Lock wird per `sessionStorage` (`plenario-wakelock`) wieder angefordert, Vollbild braucht eine Nutzergeste und muss nach dem Wechsel ggf. neu gewählt werden. +- **Dashboard ohne Neuladen** (`initAdminDashboard()`, `Fragments` in `plenario.js`): Formulare in `[data-live]` (Folienliste, Kopf) + und das Folienformular im `` laufen per `fetch` mit Header `X-Fragment`; `AdminAppController::beforeRender()` nimmt dann + das Layout `fragment` (nur Inhalt + Flash). Die Server-Aktionen bleiben normale POST + Redirect, das JS tauscht die Bereiche + `[data-refresh="head|slides|flash"]` (als DOM-Knoten, nie `innerHTML`) und stellt den Fokus wieder her. Bearbeiten/Anlegen: + Links mit `data-modal` laden das Formular (`[data-modal-content]`) in den Dialog; Validierungsfehler kommen als Formular + zurück (Dialog bleibt offen), Erfolg als Dashboard-Fragment (Dialog schließt). Ohne JS funktioniert alles als normale Seite. + **Buttons mit Bestätigung** nutzen `Form->postButton()` + `data-confirm` (CakePHPs `postLink`/`confirm` erzeugt ein Inline-`onclick`, + das die CSP blockiert); das JS fragt per `window.confirm()` vor dem Absenden. Tests: `AdminFragmentTest.php`. + ### Neuen Folientyp hinzufügen (Checkliste) 1. Konstante + Label + Beschreibung + `DEFAULT_SETTINGS` in `src/Model/Entity/Slide.php` @@ -320,6 +342,16 @@ Deploy erfolgt über Git (Remote: Gitea) mit `.gitea/workflows/ci.yml`: - Benötigte Variablen/Secrets sind im Kopf der Workflow-Datei dokumentiert. Zugangsdaten nur als Gitea-Secret, nie ins Repo. +**Container (Docker):** `Dockerfile` (`php:8.5-cli-alpine`, Multi-Stage mit Composer) startet über +`docker/entrypoint.sh` den eingebauten Server (`bin/cake server -H 0.0.0.0 -p 8765`, `PHP_CLI_SERVER_WORKERS=8`, +sonst bedient er nur einen Request gleichzeitig). Code in `/app`, SQLite in Volume `/data` +(`DATABASE_URL=sqlite:////data/plenario.sqlite`), Konfiguration nur per Umgebungsvariablen (`config/.env.example`). +`SECURITY_SALT` ist Pflicht (Entrypoint bricht sonst ab; `composer install --no-scripts`, damit kein Salt eingebrannt wird). +Der Start ist idempotent (Migrationen + `cache clear_all`). Der Healthcheck prüft eine statische Datei, weil die Host-Prüfung +(`APP_FULL_BASE_URL`) `127.0.0.1` auf echten Seiten mit 400 ablehnt. Betrieb hinter einem TLS-Proxy mit `X-Forwarded-Proto`. +`.gitea/workflows/docker.yml` baut bei Push auf `main` und pusht `:latest` + `:` in die Gitea-Registry +(Variablen `DOCKER_REPO`, `IMAGE_NAME`, Secret `PAT`). Beispiel: `docker-compose.yml`. + Produktiv auf dem Server in `config/.env`: `DEBUG=false`, `APP_FULL_BASE_URL`, `SECURITY_SALT`, SMTP. Ohne `DEBUG=false` steht die per Composer erzeugte `app_local.php` auf debug=true und zeigt Admin-Links direkt an. Document-Root zeigt idealerweise auf `webroot/`; liegt die App direkt im Document-Root (z. B. `public_html`), diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..5f7b8fa --- /dev/null +++ b/Dockerfile @@ -0,0 +1,40 @@ +# PlenarIO container: PHP's built-in server via `bin/cake server`, app in /app, SQLite in /data. +# Configuration only through environment variables (see config/.env.example). + +FROM php:8.5-cli-alpine AS base +RUN apk add --no-cache icu-libs \ + && apk add --no-cache --virtual .build-deps $PHPIZE_DEPS icu-dev \ + && docker-php-ext-install -j"$(nproc)" intl \ + && apk del .build-deps + +FROM base AS build +COPY --from=composer:2 /usr/bin/composer /usr/bin/composer +WORKDIR /app +COPY composer.json composer.lock ./ +# --no-scripts: the installer must not bake a random salt into app_local.php (SECURITY_SALT comes at runtime) +RUN composer install --no-dev --no-scripts --no-progress --prefer-dist --optimize-autoloader +COPY . . +RUN composer dump-autoload --no-dev --optimize \ + && cp config/app_local.example.php config/app_local.php + +FROM base +WORKDIR /app +COPY --from=build /app /app +COPY docker/entrypoint.sh /usr/local/bin/plenario-entrypoint + +ENV DEBUG=false \ + SHOW_ADMIN_LINK_AFTER_CREATE=false \ + DATABASE_URL=sqlite:////data/plenario.sqlite \ + PHP_CLI_SERVER_WORKERS=8 + +RUN chmod +x /usr/local/bin/plenario-entrypoint \ + && mkdir -p /data /app/tmp /app/logs \ + && chown -R www-data:www-data /data /app/tmp /app/logs + +USER www-data +VOLUME /data +EXPOSE 8765 +# static file: the Host-header check (APP_FULL_BASE_URL) would reject 127.0.0.1 on real pages +HEALTHCHECK --interval=30s --timeout=5s --start-period=20s \ + CMD wget -q -O /dev/null http://127.0.0.1:8765/css/plenario.css || exit 1 +ENTRYPOINT ["plenario-entrypoint"] diff --git a/README.md b/README.md index d65aab3..8aa6755 100644 --- a/README.md +++ b/README.md @@ -94,6 +94,20 @@ stehen im Kopf der Workflow-Datei. Einmalig auf dem Server: `config/.env` anlege Liegt die App direkt im Document-Root (z. B. `public_html`), leiten `.htaccess` und `index.php` im Projektroot alles nach `webroot/` weiter. +**Container:** Das [Dockerfile](Dockerfile) baut ein schlankes Image (`php:8.5-cli-alpine`, eingebauter Server auf Port 8765). +Der Workflow [.gitea/workflows/docker.yml](.gitea/workflows/docker.yml) pusht es bei jedem Push auf `main` in die Gitea-Registry. + +```bash +docker run -d -p 8765:8765 -v plenario-data:/data \ + -e SECURITY_SALT="$(php -r 'echo bin2hex(random_bytes(32));')" \ + -e APP_FULL_BASE_URL=https://plenario.example.org \ + gitea.gnilebein.de/gnilebein/plenario:latest +``` + +Die Datenbank liegt im Volume `/data`; weitere Einstellungen (SMTP, Captcha, …) als Umgebungsvariablen +(siehe `config/.env.example`, Beispiel in `docker-compose.yml`). Beim Start laufen die Migrationen automatisch. +Vor einen TLS-Proxy schalten, der `X-Forwarded-Proto` setzt. + Live-Updates laufen über kurzes Polling (Standard alle 2 s) – kein WebSocket-Server nötig. Für sehr große Runden (mehrere hundert Teilnehmende) `POLL_INTERVAL_MS` erhöhen und MySQL/PostgreSQL statt SQLite verwenden. diff --git a/config/Migrations/20261111150000_AddIsHiddenToSlides.php b/config/Migrations/20261111150000_AddIsHiddenToSlides.php new file mode 100644 index 0000000..59ed676 --- /dev/null +++ b/config/Migrations/20261111150000_AddIsHiddenToSlides.php @@ -0,0 +1,37 @@ +table('slides'); + if (!$table->hasColumn('is_hidden')) { + $table->addColumn('is_hidden', 'boolean', [ + 'null' => false, + 'default' => false, + 'after' => 'position', + ])->update(); + } + } + + /** + * @return void + */ + public function down(): void + { + $table = $this->table('slides'); + if ($table->hasColumn('is_hidden')) { + $table->removeColumn('is_hidden')->update(); + } + } +} diff --git a/config/routes.php b/config/routes.php index 54b189e..f216427 100644 --- a/config/routes.php +++ b/config/routes.php @@ -83,7 +83,11 @@ return function (RouteBuilder $routes): void { ->setPatterns($token)->setPass(['id']); $admin->connect('/slides/{id}/delete', 'Slides::delete', ['_name' => 'slides:delete']) ->setPatterns($token)->setPass(['id'])->setMethods(['POST']); - $admin->connect('/slides/reorder', 'Slides::reorder', ['_name' => 'slides:reorder']) + $admin->connect('/slides/{id}/duplicate', 'Slides::duplicate', ['_name' => 'slides:duplicate']) + ->setPatterns($token)->setPass(['id'])->setMethods(['POST']); + $admin->connect('/slides/{id}/visibility', 'Slides::visibility', ['_name' => 'slides:visibility']) + ->setPatterns($token)->setPass(['id'])->setMethods(['POST']); + $admin->connect('/slides/reorder','Slides::reorder', ['_name' => 'slides:reorder']) ->setPatterns($token)->setMethods(['POST']); $admin->connect('/slides/youtube-check', 'Slides::youtubeCheck', ['_name' => 'slides:youtube-check']) ->setPatterns($token)->setMethods(['POST']); diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..df0ffc2 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,15 @@ +# Example: docker compose up -d +# Put it behind a TLS reverse proxy that sets X-Forwarded-Proto; APP_FULL_BASE_URL = public URL. +services: + plenario: + image: gitea.gnilebein.de/gnilebein/plenario:latest + # build: . + restart: unless-stopped + ports: + - "8765:8765" + env_file: .env # SECURITY_SALT, APP_FULL_BASE_URL, MAIL_FROM, EMAIL_TRANSPORT_DEFAULT_URL, ... + volumes: + - plenario-data:/data + +volumes: + plenario-data: diff --git a/docker/entrypoint.sh b/docker/entrypoint.sh new file mode 100644 index 0000000..473c2d0 --- /dev/null +++ b/docker/entrypoint.sh @@ -0,0 +1,16 @@ +#!/bin/sh +# Idempotent start: prepare writable dirs, migrate the database, then run the built-in server. +set -eu + +cd /app +mkdir -p tmp/cache tmp/sessions tmp/mails tmp/dompdf logs + +if [ -z "${SECURITY_SALT:-}" ] || [ "${SECURITY_SALT}" = "__SALT__" ]; then + echo "SECURITY_SALT is not set. Generate one with: php -r \"echo bin2hex(random_bytes(32));\"" >&2 + exit 1 +fi + +php bin/cake.php migrations migrate +php bin/cake.php cache clear_all + +exec php bin/cake.php server -H 0.0.0.0 -p "${PORT:-8765}" diff --git a/src/Controller/AdminAppController.php b/src/Controller/AdminAppController.php index 008c20f..f3d36be 100644 --- a/src/Controller/AdminAppController.php +++ b/src/Controller/AdminAppController.php @@ -71,6 +71,10 @@ abstract class AdminAppController extends AppController { parent::beforeRender($event); $this->response = $this->protect($this->response); + // plenario.js asks for a fragment to update the open page without reloading it. + if ($this->request->getHeaderLine('X-Fragment') !== '') { + $this->viewBuilder()->setLayout('fragment'); + } } /** diff --git a/src/Controller/AdminController.php b/src/Controller/AdminController.php index 883c35c..117ff67 100644 --- a/src/Controller/AdminController.php +++ b/src/Controller/AdminController.php @@ -161,7 +161,7 @@ class AdminController extends AdminAppController { if ($this->poll->current_slide_id === null && !$this->poll->isPaused()) { $first = $this->Slides->find() - ->where(['poll_id' => $this->poll->id]) + ->where(['poll_id' => $this->poll->id, 'is_hidden' => false]) ->orderBy(['position' => 'ASC', 'id' => 'ASC']) ->first(); if ($first !== null) { @@ -203,7 +203,8 @@ class AdminController extends AdminAppController { $this->request->allowMethod(['post']); $action = (string)$this->request->getData('action'); - $slides = $this->Slides->listForPoll($this->poll->id); + // Hidden slides are skipped and can not go live. + $slides = $this->Slides->listForPoll($this->poll->id, true); $ids = array_map(fn(Slide $s) => $s->id, $slides); $index = array_search($this->poll->current_slide_id, $ids, true); $current = $index === false ? null : $slides[$index]; diff --git a/src/Controller/EmbedController.php b/src/Controller/EmbedController.php index 20262ee..46770f7 100644 --- a/src/Controller/EmbedController.php +++ b/src/Controller/EmbedController.php @@ -114,14 +114,14 @@ class EmbedController extends AppController } /** - * The embed became visible: this slide goes live. Idempotent. + * The embed became visible: this slide goes live (unless it is hidden). Idempotent. * * @return \Cake\Http\Response */ public function activate(): Response { $this->request->allowMethod(['post']); - if ($this->poll->is_active) { + if ($this->poll->is_active && !$this->slide->is_hidden) { $this->poll->showEmbeddedSlide($this->slide->id); $this->Polls->saveOrFail($this->poll); } diff --git a/src/Controller/SlidesController.php b/src/Controller/SlidesController.php index 0908100..a9fa3ae 100644 --- a/src/Controller/SlidesController.php +++ b/src/Controller/SlidesController.php @@ -43,10 +43,8 @@ class SlidesController extends AdminAppController 'validate' => false, ]); $slide->poll_id = $this->poll->id; - // A quiz is started by the presenter (that also starts its timer). - $slide->is_voting_open = $type !== Slide::TYPE_QUIZ; - // Q&A starts by collecting questions. - $slide->stage = $type === Slide::TYPE_QA ? Slide::QA_COLLECT : null; + // A quiz is started by the presenter (that also starts its timer), Q&A starts by collecting questions. + $slide->startFresh(); $optionsText = $type === Slide::TYPE_CHOICE ? "\n" : ''; $quizOptions = []; $orderOptions = []; @@ -106,15 +104,7 @@ class SlidesController extends AdminAppController $this->request->allowMethod(['post']); $slide = $this->loadSlide($id); // Deleting the live (or paused) slide pauses the poll; → resumes with the slide taking its place. - $ids = $this->Slides->find() - ->select(['id']) - ->where(['poll_id' => $this->poll->id]) - ->orderBy(['position' => 'ASC', 'id' => 'ASC']) - ->all() - ->extract('id') - ->toList(); - $index = (int)array_search($slide->id, $ids, true); - $this->poll->forgetSlide($slide->id, $ids[$index + 1] ?? $ids[$index - 1] ?? null); + $this->poll->forgetSlide($slide->id, $this->Slides->replacementFor($slide)); $this->Slides->getConnection()->transactional(function () use ($slide): void { $this->Polls->saveOrFail($this->poll); @@ -126,6 +116,49 @@ class SlidesController extends AdminAppController return $this->redirect($this->adminUrl()); } + /** + * Hides a slide from the presentation or shows it again. Field `hidden` (1|0) is explicit + * (not a toggle), so repeating the request changes nothing. Hiding the live (or paused) + * slide pauses the poll like deleting it. + * + * @param string $id Slide id + * @return \Cake\Http\Response|null + */ + public function visibility(string $id): ?Response + { + $this->request->allowMethod(['post']); + $slide = $this->loadSlide($id); + $hidden = filter_var($this->request->getData('hidden'), FILTER_VALIDATE_BOOLEAN); + + $this->Slides->getConnection()->transactional(function () use ($slide, $hidden): void { + if ($hidden) { + $this->poll->forgetSlide($slide->id, $this->Slides->replacementFor($slide)); + $this->Polls->saveOrFail($this->poll); + } + $this->Slides->updateAll(['is_hidden' => $hidden], ['id' => $slide->id]); + }); + $this->Flash->success($hidden + ? __('Folie „{0}“ ist ausgeblendet und wird beim Präsentieren übersprungen.', $slide->question) + : __('Folie „{0}“ ist wieder eingeblendet.', $slide->question)); + + return $this->redirect($this->adminUrl()); + } + + /** + * Copies a slide (without responses) directly behind the original and opens the copy for editing. + * + * @param string $id Slide id + * @return \Cake\Http\Response|null + */ + public function duplicate(string $id): ?Response + { + $this->request->allowMethod(['post']); + $copy = $this->Slides->duplicate($this->loadSlide($id)); + $this->Flash->success(__('Folie dupliziert. Du bearbeitest jetzt die Kopie.')); + + return $this->redirect($this->adminUrl('slides:edit', ['id' => $copy->id])); + } + /** * Saves a complete new slide order (drag & drop), expects `ids[]` and answers with JSON. * diff --git a/src/Model/Entity/Poll.php b/src/Model/Entity/Poll.php index 407c111..890689e 100644 --- a/src/Model/Entity/Poll.php +++ b/src/Model/Entity/Poll.php @@ -110,10 +110,11 @@ class Poll extends Entity } /** - * A slide is being deleted. If it was live or is the one a pause resumes, the poll pauses - * and resumes with $resumeSlideId instead (null: no slides left = not started). Idempotent. + * A slide leaves the presentation (deleted or hidden). If it was live or is the one a pause + * resumes, the poll pauses and resumes with $resumeSlideId instead (null: no slides left = + * not started). Idempotent. * - * @param int $slideId Deleted slide + * @param int $slideId Deleted or hidden slide * @param int|null $resumeSlideId Slide that takes its place (must belong to this poll) * @return void */ diff --git a/src/Model/Entity/Slide.php b/src/Model/Entity/Slide.php index cd88f98..1d1e5fc 100644 --- a/src/Model/Entity/Slide.php +++ b/src/Model/Entity/Slide.php @@ -17,6 +17,7 @@ use Cake\ORM\Entity; * @property string $question * @property string|null $description * @property int $position + * @property bool $is_hidden Prepared, but skipped in the presentation (never live) * @property array|null $settings * @property bool $is_voting_open * @property \Cake\I18n\DateTime|null $voting_started_at Quiz: start of the voting window @@ -408,6 +409,21 @@ class Slide extends Entity return max(0, $this->voting_ends_at->getTimestamp() - ($now ?? DateTime::now())->getTimestamp()); } + /** + * Sets the state of a slide that has not been presented yet (new slide, copy): + * a quiz waits for the presenter to start it, Q&A collects questions, others are open. + * + * @return void + */ + public function startFresh(): void + { + $this->is_voting_open = !$this->isQuiz(); + $this->voting_started_at = null; + $this->voting_ends_at = null; + $this->stage = $this->isQa() ? self::QA_COLLECT : null; + $this->focus_response_id = null; + } + /** * Opens or closes voting. Opening a quiz that is not running (re)starts its * voting window and timer; opening a running quiz changes nothing. diff --git a/src/Model/Table/SlidesTable.php b/src/Model/Table/SlidesTable.php index afb3340..3a7e92c 100644 --- a/src/Model/Table/SlidesTable.php +++ b/src/Model/Table/SlidesTable.php @@ -6,6 +6,7 @@ namespace App\Model\Table; use App\Model\Entity\Slide; use App\Service\YouTubeService; use ArrayObject; +use Cake\Database\Expression\QueryExpression; use Cake\Datasource\EntityInterface; use Cake\Event\EventInterface; use Cake\ORM\RulesChecker; @@ -323,6 +324,46 @@ class SlidesTable extends Table }); } + /** + * Copies a slide incl. its settings and options (with the correct answers) and + * puts the copy directly behind the original. Responses are not copied: the copy + * starts like a new slide (quiz not started, Q&A collecting, others open). + * + * @param \App\Model\Entity\Slide $slide Original incl. slide_options + * @return \App\Model\Entity\Slide The saved copy + */ + public function duplicate(Slide $slide): Slide + { + $copy = $this->newEmptyEntity(); + $copy->poll_id = $slide->poll_id; + $copy->type = $slide->type; + $copy->question = mb_substr(__('{0} (Kopie)', $slide->question), 0, 500); + $copy->description = $slide->description; + $copy->settings = $slide->settings; + $copy->position = $slide->position + 1; + $copy->startFresh(); + + return $this->getConnection()->transactional(function () use ($slide, $copy): Slide { + $this->updateAll( + ['position' => new QueryExpression('position + 1')], + ['poll_id' => $slide->poll_id, 'position >' => $slide->position], + ); + $this->saveOrFail($copy); + foreach ($slide->slide_options ?? [] as $option) { + $newOption = $this->SlideOptions->newEntity([ + 'label' => $option->label, + 'position' => $option->position, + ]); + $newOption->set('slide_id', $copy->id); + $newOption->set('is_correct', $option->is_correct); + $this->SlideOptions->saveOrFail($newOption); + } + $this->normalizePositions($slide->poll_id); + + return $this->get($copy->id, contain: ['SlideOptions']); + }); + } + /** * Applies a complete new order (e.g. from drag & drop). * @@ -382,18 +423,51 @@ class SlidesTable extends Table * Ordered slides of a poll including options. * * @param int $pollId Poll id + * @param bool $visibleOnly Only slides that are part of the presentation (not hidden) * @return list<\App\Model\Entity\Slide> */ - public function listForPoll(int $pollId): array + public function listForPoll(int $pollId, bool $visibleOnly = false): array { - /** @var list<\App\Model\Entity\Slide> $slides */ - $slides = $this->find() + $query = $this->find() ->where(['Slides.poll_id' => $pollId]) ->contain(['SlideOptions']) - ->orderBy(['Slides.position' => 'ASC', 'Slides.id' => 'ASC']) - ->all() - ->toList(); + ->orderBy(['Slides.position' => 'ASC', 'Slides.id' => 'ASC']); + if ($visibleOnly) { + $query->where(['Slides.is_hidden' => false]); + } + /** @var list<\App\Model\Entity\Slide> $slides */ + $slides = $query->all()->toList(); return $slides; } + + /** + * The visible slide that takes the place of a slide leaving the presentation + * (deleted or hidden): the next visible one behind it, otherwise the one before. + * + * @param \App\Model\Entity\Slide $slide Slide leaving the presentation + * @return int|null Slide id, null if no other visible slide is left + */ + public function replacementFor(Slide $slide): ?int + { + $rows = $this->find() + ->select(['id', 'is_hidden']) + ->where(['poll_id' => $slide->poll_id]) + ->orderBy(['position' => 'ASC', 'id' => 'ASC']) + ->disableHydration() + ->all() + ->toList(); + $index = array_search($slide->id, array_column($rows, 'id'), true); + if ($index === false) { + return null; + } + $candidates = array_merge(array_slice($rows, $index + 1), array_reverse(array_slice($rows, 0, $index))); + foreach ($candidates as $row) { + if (!$row['is_hidden']) { + return (int)$row['id']; + } + } + + return null; + } } diff --git a/src/Service/PollStateService.php b/src/Service/PollStateService.php index 55a7a61..55eb5a6 100644 --- a/src/Service/PollStateService.php +++ b/src/Service/PollStateService.php @@ -83,7 +83,8 @@ class PollStateService public function forPresenter(Poll $poll): array { $this->Polls->pauseIfEmbedStale($poll); - $slides = $this->Slides->listForPoll($poll->id); + // The presentation consists of the visible slides only. + $slides = $this->Slides->listForPoll($poll->id, true); $current = null; $index = null; foreach ($slides as $i => $slide) { @@ -102,6 +103,7 @@ class PollStateService ], $slides), 'index' => $index, 'count' => count($slides), + 'hiddenCount' => $this->Slides->find()->where(['poll_id' => $poll->id, 'is_hidden' => true])->count(), 'slide' => $current ? $this->slidePayload($current) : null, 'results' => $current ? $this->results->forSlide($current) : null, ]; @@ -123,6 +125,7 @@ class PollStateService return [ 'poll' => $this->pollPayload($poll), 'isLive' => $poll->current_slide_id === $slide->id, + 'isHidden' => $slide->is_hidden, 'index' => null, 'count' => null, 'slide' => $this->slidePayload($slide), diff --git a/src/Service/ReportService.php b/src/Service/ReportService.php index 03c923b..5d8b806 100644 --- a/src/Service/ReportService.php +++ b/src/Service/ReportService.php @@ -16,7 +16,7 @@ use Cake\ORM\Locator\LocatorAwareTrait; * screen. With $includeInternal it also contains their answers, distribution and comments – * that version is meant for the poll owner only. * - * Per slide: ['slide' => Slide, 'number' => int (position in the poll, 1-based), + * Per slide: ['slide' => Slide, 'number' => int (position in the presentation, 1-based; hidden slides are left out), * 'internal' => bool (private slide), 'withheld' => bool (private and left out), * 'results' => ResultsService::forSlide() shape, where * open: 'answers' contains all texts (not only the newest ones), and @@ -49,7 +49,7 @@ class ReportService */ public function build(Poll $poll, bool $includeInternal): array { - $slides = $this->Slides->listForPoll($poll->id); + $slides = $this->Slides->listForPoll($poll->id, true); $includeInternal = $includeInternal && array_filter($slides, fn(Slide $slide) => $slide->isInteractive() && $slide->isPrivate()) !== []; $sections = []; diff --git a/src/Service/ResultsService.php b/src/Service/ResultsService.php index 61ceee9..f383458 100644 --- a/src/Service/ResultsService.php +++ b/src/Service/ResultsService.php @@ -40,7 +40,8 @@ use Cake\ORM\Locator\LocatorAwareTrait; * - qa: 'stage' (collect|vote|discuss), 'stages' (available stages in order, no 'vote' without upvotes), * 'maxUpvotes' (per participant, 0 = no upvotes), 'maxPerQuestion' (per participant and question), * 'upvotes' (total), - * 'questions' => [['id', 'text', 'votes']] most upvoted first (ties: oldest first), + * 'questions' => [['id', 'text', 'votes']] most upvoted first (ties: oldest first); + * during 'vote' only [['id', 'text']] in submission order (no counts while voting is open), * 'focusId' (question being discussed|null), 'focusIndex' (0-based position in questions|null). * Presenter only – participants get their own view, see PollStateService::qaState(). */ @@ -215,6 +216,12 @@ class ResultsService protected function qa(Slide $slide): array { $questions = (new QaService())->rankedQuestions($slide); + $upvotes = array_sum(array_column($questions, 'votes')); + if ($slide->qaStage() === Slide::QA_VOTE) { + // A live ranking on the stage would sway the vote: submission order, no counts until voting ends. + usort($questions, fn($a, $b) => $a['id'] <=> $b['id']); + $questions = array_map(fn($q) => ['id' => $q['id'], 'text' => $q['text']], $questions); + } $focusIndex = null; foreach ($questions as $index => $question) { if ($question['id'] === $slide->focus_response_id) { @@ -227,7 +234,7 @@ class ResultsService 'stages' => $slide->qaStages(), 'maxUpvotes' => (int)$slide->setting('max_upvotes'), 'maxPerQuestion' => $slide->qaUpvotesPerQuestion(), - 'upvotes' => array_sum(array_column($questions, 'votes')), + 'upvotes' => $upvotes, 'questions' => $questions, 'focusId' => $focusIndex === null ? null : $slide->focus_response_id, 'focusIndex' => $focusIndex, diff --git a/templates/Admin/export.php b/templates/Admin/export.php index 020e1a1..bd8aefa 100644 --- a/templates/Admin/export.php +++ b/templates/Admin/export.php @@ -213,7 +213,7 @@ $bar = function (float $percent, bool $ok = false): string {

- 0; ?> + 0 && $r['stage'] !== 'vote'; ?> diff --git a/templates/Admin/index.php b/templates/Admin/index.php index e3bb1b9..1dccab9 100644 --- a/templates/Admin/index.php +++ b/templates/Admin/index.php @@ -15,9 +15,9 @@ $this->assign('title', $poll->title); $this->assign('noindex', '1'); $url = fn(string $name, array $params = []) => ['_name' => $name, 'token' => $adminToken] + $params; -$hasInternal = array_filter($slides, fn($slide) => $slide->isInteractive() && $slide->isPrivate()) !== []; +$hasInternal = array_filter($slides, fn($slide) => !$slide->is_hidden && $slide->isInteractive() && $slide->isPrivate()) !== []; ?> -
+

title) ?>

@@ -37,7 +37,7 @@ $hasInternal = array_filter($slides, fn($slide) => $slide->isInteractive() && $s ▶ current_slide_id !== null) : ?> - Form->postLink('⏸ ' . __('Pause'), $url('admin:control'), [ + Form->postButton('⏸ ' . __('Pause'), $url('admin:control'), [ 'data' => ['action' => 'stop'], 'class' => 'button', 'title' => __('Keine Folie zeigen – Teilnehmende sehen eine Pause-Seite'), @@ -64,6 +64,7 @@ $hasInternal = array_filter($slides, fn($slide) => $slide->isInteractive() && $s
+
1) : ?> @@ -72,7 +73,7 @@ $hasInternal = array_filter($slides, fn($slide) => $slide->isInteractive() && $s $isCurrent = $poll->current_slide_id === $slide->id; $count = $responseCounts[$slide->id] ?? 0; ?> -
  • +
  • - - Form->postLink(__('Live'), $url('admin:control'), [ + is_hidden) : ?> + Form->postButton('▶', $url('admin:control'), [ 'data' => ['action' => 'goto', 'slide_id' => $slide->id], - 'class' => 'button button--small', - 'title' => __('Diese Folie jetzt den Teilnehmenden zeigen'), + 'class' => 'button button--small button--icon', + 'title' => __('Live: diese Folie jetzt den Teilnehmenden zeigen'), + 'aria-label' => __('Folie „{0}“ live schalten', $slide->question), ]) ?> - type === 'open' || $slide->isPrivate() || $slide->hasComments()) && $count > 0) : ?> - type === 'scale' ? __('Auswertung') : __('Antworten') ?> + type === 'open' || $slide->isPrivate() || $slide->hasComments()) && $count > 0) : + $answersLabel = $slide->type === 'scale' ? __('Auswertung') : __('Antworten'); ?> + 📊 + + ✎ + Form->postButton('⧉', $url('slides:duplicate', ['id' => $slide->id]), [ + 'class' => 'button button--small button--icon', + 'title' => __('Duplizieren: Kopie direkt dahinter anlegen (ohne Antworten)'), + 'aria-label' => __('Folie „{0}“ duplizieren', $slide->question), + ]) ?> + is_hidden) : ?> + Form->postButton('👁', $url('slides:visibility', ['id' => $slide->id]), [ + 'data' => ['hidden' => 0], + 'class' => 'button button--small button--icon', + 'title' => __('Einblenden: Folie wieder in die Präsentation aufnehmen'), + 'aria-label' => __('Folie „{0}“ einblenden', $slide->question), + ]) ?> + + Form->postButton('⊘', $url('slides:visibility', ['id' => $slide->id]), [ + 'data' => ['hidden' => 1], + 'class' => 'button button--small button--icon', + 'title' => __('Ausblenden: Folie behalten, aber beim Präsentieren überspringen'), + 'aria-label' => __('Folie „{0}“ ausblenden', $slide->question), + 'data-confirm' => $isCurrent ? __('Diese Folie ist gerade live. Ausblenden und die Umfrage pausieren?') : null, + ]) ?> - 0) : ?> - Form->postLink(__('Zurücksetzen'), $url('slides:reset', ['id' => $slide->id]), [ - 'class' => 'button button--small', - 'confirm' => __('Alle {0} Antworten dieser Folie löschen?', $count), + Form->postButton('↺', $url('slides:reset', ['id' => $slide->id]), [ + 'class' => 'button button--small button--icon', + 'title' => __('Zurücksetzen: alle Antworten dieser Folie löschen'), + 'aria-label' => __('Antworten der Folie „{0}“ zurücksetzen', $slide->question), + 'data-confirm' => __('Alle {0} Antworten dieser Folie löschen?', $count), ]) ?> - Form->postLink(__('Löschen'), $url('slides:delete', ['id' => $slide->id]), [ - 'class' => 'button button--small button--danger', - 'confirm' => __('Folie „{0}“ inkl. aller Antworten löschen?', $slide->question), + Form->postButton('🗑', $url('slides:delete', ['id' => $slide->id]), [ + 'class' => 'button button--small button--icon button--danger', + 'title' => __('Löschen'), + 'aria-label' => __('Folie „{0}“ löschen', $slide->question), + 'data-confirm' => __('Folie „{0}“ inkl. aller Antworten löschen?', $slide->question), ]) ?>
  • +

    $label) : ?> - + @@ -214,9 +246,9 @@ $hasInternal = array_filter($slides, fn($slide) => $slide->isInteractive() && $s

    - Form->postLink(__('Neue Einbett-Links erzeugen'), $url('admin:rotate-embed'), [ + Form->postButton(__('Neue Einbett-Links erzeugen'), $url('admin:rotate-embed'), [ 'class' => 'button button--small', - 'confirm' => __('Neue Einbett-Links erzeugen? Alle bisher eingebetteten Folien funktionieren danach nicht mehr.'), + 'data-confirm' => __('Neue Einbett-Links erzeugen? Alle bisher eingebetteten Folien funktionieren danach nicht mehr.'), ]) ?> @@ -249,18 +281,18 @@ $hasInternal = array_filter($slides, fn($slide) => $slide->isInteractive() && $s

    - Form->postLink(__('Neuen Admin-Link erzeugen'), $url('admin:rotate'), [ + Form->postButton(__('Neuen Admin-Link erzeugen'), $url('admin:rotate'), [ 'class' => 'button button--small', - 'confirm' => __('Neuen Admin-Link erzeugen? Der aktuelle Link funktioniert danach nicht mehr.'), + 'data-confirm' => __('Neuen Admin-Link erzeugen? Der aktuelle Link funktioniert danach nicht mehr.'), ]) ?>

    Html->link(__('Ergebnisse vorher als PDF sichern'), '#export') ?>

    - Form->postLink(__('Alle Antworten löschen'), $url('admin:reset'), [ + Form->postButton(__('Alle Antworten löschen'), $url('admin:reset'), [ 'class' => 'button button--small button--danger', - 'confirm' => __('Alle Antworten aller Folien unwiderruflich löschen?'), + 'data-confirm' => __('Alle Antworten aller Folien unwiderruflich löschen?'), ]) ?>

    @@ -278,3 +310,12 @@ $hasInternal = array_filter($slides, fn($slide) => $slide->isInteractive() && $s
    + + + + + + diff --git a/templates/Slides/form.php b/templates/Slides/form.php index 3927f82..3924b2b 100644 --- a/templates/Slides/form.php +++ b/templates/Slides/form.php @@ -26,9 +26,9 @@ $optionsError = $slide->getError('options_text'); ?>

    ← title)) ?>

    -
    +

    typeLabel()) ?>

    -

    +

    Form->create($slide, ['url' => $formUrl]) ?> Form->hidden('type') ?> @@ -337,7 +337,7 @@ $optionsError = $slide->getError('options_text');
    Form->button($isNew ? __('Folie anlegen') : __('Speichern'), ['class' => 'button button--primary']) ?> - +
    Form->end() ?>
    diff --git a/templates/layout/default.php b/templates/layout/default.php index 5a136cb..652a2a7 100644 --- a/templates/layout/default.php +++ b/templates/layout/default.php @@ -36,7 +36,7 @@ $title = $this->fetch('title');
    - Flash->render() ?> +
    Flash->render() ?>
    fetch('content') ?>
    diff --git a/templates/layout/fragment.php b/templates/layout/fragment.php new file mode 100644 index 0000000..70bca6d --- /dev/null +++ b/templates/layout/fragment.php @@ -0,0 +1,10 @@ + +
    Flash->render() ?>
    +fetch('content') ?> diff --git a/tests/TestCase/Controller/AdminFragmentTest.php b/tests/TestCase/Controller/AdminFragmentTest.php new file mode 100644 index 0000000..a1968f9 --- /dev/null +++ b/tests/TestCase/Controller/AdminFragmentTest.php @@ -0,0 +1,105 @@ + + */ + protected array $fixtures = ['app.Polls', 'app.Slides', 'app.SlideOptions', 'app.Responses']; + + protected function setUp(): void + { + parent::setUp(); + $this->enableCsrfToken(); + } + + public function testFragmentContainsRegionsButNoPageFrame(): void + { + [$poll, $token] = $this->createPoll(); + $this->createSlide($poll, Slide::TYPE_CHOICE); + + $this->configRequest(['headers' => ['X-Fragment' => '1']]); + $this->get("/admin/$token"); + + $this->assertResponseOk(); + $this->assertResponseContains('data-refresh="slides"'); + $this->assertResponseContains('data-refresh="head"'); + $this->assertResponseContains('data-refresh="flash"'); + $this->assertResponseNotContains('assertResponseNotContains('site-header'); + } + + public function testFullPageKeepsFrameAndRegions(): void + { + [$poll, $token] = $this->createPoll(); + $this->createSlide($poll, Slide::TYPE_CHOICE); + + $this->get("/admin/$token"); + + $this->assertResponseContains('assertResponseContains('data-refresh="flash"'); + $this->assertResponseContains('createPoll(); + $this->createSlide($poll, Slide::TYPE_CHOICE); + + $this->get("/admin/$token"); + + $this->assertResponseNotContains('onclick='); + $this->assertResponseContains('data-confirm='); + } + + public function testSlideFormFragmentIsTheDialogContent(): void + { + [$poll, $token] = $this->createPoll(); + $slide = $this->createSlide($poll, Slide::TYPE_OPEN); + + $this->configRequest(['headers' => ['X-Fragment' => '1']]); + $this->get("/admin/$token/slides/{$slide->id}/edit"); + + $this->assertResponseOk(); + $this->assertResponseContains('data-modal-content'); + $this->assertResponseNotContains('site-header'); + } + + public function testValidationErrorKeepsTheFormInTheFragment(): void + { + [$poll, $token] = $this->createPoll(); + $slide = $this->createSlide($poll, Slide::TYPE_OPEN); + + $this->configRequest(['headers' => ['X-Fragment' => '1']]); + $this->post("/admin/$token/slides/{$slide->id}/edit", ['question' => '']); + + $this->assertResponseOk(); + $this->assertResponseContains('data-modal-content'); + $this->assertResponseContains('Bitte prüfe deine Eingaben.'); + } + + public function testSuccessfulSaveRedirectsToTheDashboard(): void + { + [$poll, $token] = $this->createPoll(); + $slide = $this->createSlide($poll, Slide::TYPE_OPEN); + + $this->configRequest(['headers' => ['X-Fragment' => '1']]); + $this->post("/admin/$token/slides/{$slide->id}/edit", ['question' => 'Neue Frage']); + + $this->assertRedirect(['_name' => 'admin', 'token' => $token]); + } +} diff --git a/tests/TestCase/Controller/DuplicateSlideTest.php b/tests/TestCase/Controller/DuplicateSlideTest.php new file mode 100644 index 0000000..b7671e1 --- /dev/null +++ b/tests/TestCase/Controller/DuplicateSlideTest.php @@ -0,0 +1,129 @@ + + */ + protected array $fixtures = ['app.Polls', 'app.Slides', 'app.SlideOptions', 'app.Responses']; + + protected function setUp(): void + { + parent::setUp(); + $this->enableCsrfToken(); + } + + public function testCopyIsPlacedBehindOriginalWithoutResponses(): void + { + [$poll, $token] = $this->createPoll(); + $first = $this->createSlide($poll, Slide::TYPE_CHOICE, [ + 'description' => '*Wichtig*', + 'settings' => ['multiple' => true] + Slide::DEFAULT_SETTINGS[Slide::TYPE_CHOICE], + ], ['Rot', 'Grün', 'Blau']); + $last = $this->createSlide($poll, Slide::TYPE_OPEN); + $poll = $this->goLive($poll, $first); + (new VoteService())->submit($poll, $first, VoteService::participantHash(str_repeat('a', 32), $poll->id), [ + 'option_id' => $first->slide_options[0]->id, + ]); + + $this->post("/admin/$token/slides/{$first->id}/duplicate"); + + $slides = $this->slidesTable()->listForPoll($poll->id); + $this->assertSame([$first->id, $last->id], [$slides[0]->id, $slides[2]->id]); + $copy = $slides[1]; + $this->assertRedirect(['_name' => 'slides:edit', 'token' => $token, 'id' => $copy->id]); + $this->assertSame([1, 2, 3], array_map(fn($s) => $s->position, $slides)); + $this->assertSame('Frage choice (Kopie)', $copy->question); + $this->assertSame('*Wichtig*', $copy->description); + $this->assertSame($first->getSettings(), $copy->getSettings()); + $this->assertSame(['Rot', 'Grün', 'Blau'], array_map(fn($o) => $o->label, $copy->slide_options)); + $this->assertNotContains($copy->slide_options[0]->id, array_map(fn($o) => $o->id, $first->slide_options)); + + $responses = TableRegistry::getTableLocator()->get('Responses'); + $this->assertSame(0, $responses->find()->where(['slide_id' => $copy->id])->count()); + $this->assertSame(1, $responses->find()->where(['slide_id' => $first->id])->count(), 'original keeps its votes'); + $this->assertSame($first->id, $this->pollsTable()->get($poll->id)->current_slide_id, 'live slide stays'); + } + + public function testCopyStartsFresh(): void + { + [$poll, $token] = $this->createPoll(); + $quiz = $this->createSlide($poll, Slide::TYPE_QUIZ, [], ['Richtig', 'Falsch', 'Auch falsch']); + $quiz->setVotingOpen(true); + $quiz->is_voting_open = false; + $qa = $this->createSlide($poll, Slide::TYPE_QA); + $qa->stage = Slide::QA_DISCUSS; + $qa->is_voting_open = false; + $closed = $this->createSlide($poll, Slide::TYPE_SCALE, ['is_voting_open' => false]); + $this->slidesTable()->saveManyOrFail([$quiz, $qa]); + + foreach ([$quiz, $qa, $closed] as $slide) { + $this->post("/admin/$token/slides/{$slide->id}/duplicate"); + $this->assertResponseCode(302); + } + + $slides = $this->slidesTable()->listForPoll($poll->id); + $this->assertCount(6, $slides); + [, $quizCopy, , $qaCopy, , $scaleCopy] = $slides; + + $this->assertSame(Slide::QUIZ_READY, $quizCopy->quizPhase()); + $this->assertNull($quizCopy->voting_started_at); + $this->assertSame([true, false, false], array_map(fn($o) => $o->is_correct, $quizCopy->slide_options)); + $this->assertSame(Slide::QA_COLLECT, $qaCopy->qaStage()); + $this->assertTrue($qaCopy->is_voting_open); + $this->assertSame(Slide::TYPE_SCALE, $scaleCopy->type); + $this->assertTrue($scaleCopy->is_voting_open); + } + + public function testOnlySlidesOfOwnPollAndOnlyPost(): void + { + [$poll, $token] = $this->createPoll(); + [$other] = $this->createPoll('Andere'); + $own = $this->createSlide($poll); + $foreign = $this->createSlide($other); + + $this->post("/admin/$token/slides/{$foreign->id}/duplicate"); + $this->assertResponseCode(404); + $this->assertSame(1, $this->slidesTable()->find()->where(['poll_id' => $other->id])->count()); + + $this->get("/admin/$token/slides/{$own->id}/duplicate"); + $this->assertResponseCode(404); + $this->assertSame(1, $this->slidesTable()->find()->where(['poll_id' => $poll->id])->count()); + } + + public function testLongQuestionIsShortened(): void + { + [$poll, $token] = $this->createPoll(); + $slide = $this->createSlide($poll, Slide::TYPE_CONTENT, ['question' => str_repeat('x', 500)], []); + + $this->post("/admin/$token/slides/{$slide->id}/duplicate"); + + $copy = $this->slidesTable()->listForPoll($poll->id)[1]; + $this->assertSame(500, mb_strlen($copy->question)); + } + + public function testDashboardOffersDuplicate(): void + { + [$poll, $token] = $this->createPoll(); + $slide = $this->createSlide($poll); + $this->get("/admin/$token"); + $this->assertResponseContains("/admin/$token/slides/{$slide->id}/duplicate"); + $this->assertResponseContains('Duplizieren'); + } +} diff --git a/tests/TestCase/Controller/HiddenSlideTest.php b/tests/TestCase/Controller/HiddenSlideTest.php new file mode 100644 index 0000000..5e89f7e --- /dev/null +++ b/tests/TestCase/Controller/HiddenSlideTest.php @@ -0,0 +1,172 @@ + + */ + protected array $fixtures = ['app.Polls', 'app.Slides', 'app.SlideOptions', 'app.Responses']; + + protected function setUp(): void + { + parent::setUp(); + $this->enableCsrfToken(); + } + + public function testHideAndShowAgainIsIdempotent(): void + { + [$poll, $token] = $this->createPoll(); + $slide = $this->createSlide($poll); + $this->assertFalse($slide->is_hidden, 'new slides are visible'); + + foreach ([1, 1] as $hidden) { + $this->post("/admin/$token/slides/{$slide->id}/visibility", ['hidden' => $hidden]); + $this->assertRedirect(['_name' => 'admin', 'token' => $token]); + $this->assertTrue($this->slidesTable()->get($slide->id)->is_hidden); + } + $this->get("/admin/$token"); + $this->assertResponseContains('ausgeblendet'); + $this->assertResponseContains('Einblenden'); + + foreach ([0, 0] as $hidden) { + $this->post("/admin/$token/slides/{$slide->id}/visibility", ['hidden' => $hidden]); + $this->assertFalse($this->slidesTable()->get($slide->id)->is_hidden); + } + } + + public function testPresentationSkipsHiddenSlides(): void + { + [$poll, $token] = $this->createPoll(); + $first = $this->hidden($this->createSlide($poll, Slide::TYPE_CHOICE)); + $second = $this->createSlide($poll, Slide::TYPE_OPEN); + $third = $this->hidden($this->createSlide($poll, Slide::TYPE_WORDCLOUD)); + $fourth = $this->createSlide($poll, Slide::TYPE_SCALE); + + // Starting the presentation begins with the first visible slide. + $this->get("/admin/$token/present"); + $this->assertSame($second->id, $this->pollsTable()->get($poll->id)->current_slide_id); + + $this->configRequest(['headers' => ['Accept' => 'application/json']]); + $this->post("/admin/$token/control", ['action' => 'next']); + $state = json_decode((string)$this->_response->getBody(), true); + $this->assertSame($fourth->id, $state['slide']['id']); + $this->assertSame(1, $state['index']); + $this->assertSame(2, $state['count']); + $this->assertSame(2, $state['hiddenCount']); + $this->assertSame([$second->id, $fourth->id], array_column($state['slides'], 'id')); + + $this->post("/admin/$token/control", ['action' => 'prev']); + $this->assertSame($second->id, $this->pollsTable()->get($poll->id)->current_slide_id); + + // A hidden slide can not go live. + $this->post("/admin/$token/control", ['action' => 'goto', 'slide_id' => $third->id]); + $this->assertResponseCode(400); + $this->assertSame($second->id, $this->pollsTable()->get($poll->id)->current_slide_id); + $this->assertNotSame($first->id, $this->pollsTable()->get($poll->id)->current_slide_id); + } + + public function testHidingTheLiveSlidePausesWithTheNextVisibleSlide(): void + { + [$poll, $token] = $this->createPoll(); + $live = $this->createSlide($poll, Slide::TYPE_CHOICE); + $this->hidden($this->createSlide($poll, Slide::TYPE_OPEN)); + $next = $this->createSlide($poll, Slide::TYPE_SCALE); + $this->goLive($poll, $live); + + $this->post("/admin/$token/slides/{$live->id}/visibility", ['hidden' => 1]); + + $poll = $this->pollsTable()->get($poll->id); + $this->assertNull($poll->current_slide_id); + $this->assertSame($next->id, $poll->paused_slide_id, 'resumes with the next visible slide'); + + // Participants see the pause page. + $this->get('/p/' . $poll->join_code . '/state'); + $state = json_decode((string)$this->_response->getBody(), true); + $this->assertNull($state['slide']); + } + + public function testHidingTheLastVisibleSlideFallsBackToThePreviousOne(): void + { + [$poll, $token] = $this->createPoll(); + $previous = $this->createSlide($poll, Slide::TYPE_CHOICE); + $paused = $this->createSlide($poll, Slide::TYPE_OPEN); + $poll = $this->goLive($poll, $paused); + $poll->pause(); + $this->pollsTable()->saveOrFail($poll); + + $this->post("/admin/$token/slides/{$paused->id}/visibility", ['hidden' => 1]); + $this->assertSame($previous->id, $this->pollsTable()->get($poll->id)->paused_slide_id); + } + + public function testDeletingSkipsHiddenSlidesForResuming(): void + { + [$poll, $token] = $this->createPoll(); + $live = $this->createSlide($poll, Slide::TYPE_CHOICE); + $this->hidden($this->createSlide($poll, Slide::TYPE_OPEN)); + $this->goLive($poll, $live); + + $this->post("/admin/$token/slides/{$live->id}/delete"); + $poll = $this->pollsTable()->get($poll->id); + $this->assertNull($poll->current_slide_id); + $this->assertNull($poll->paused_slide_id, 'no visible slide left'); + } + + public function testEmbeddedHiddenSlideDoesNotGoLive(): void + { + [$poll] = $this->createPoll(); + $slide = $this->hidden($this->createSlide($poll, Slide::TYPE_CHOICE)); + $key = $this->pollsTable()->ensureEmbedKey($poll); + + $this->post("/e/$key/{$slide->id}/activate"); + $this->assertResponseOk(); + $state = json_decode((string)$this->_response->getBody(), true); + $this->assertFalse($state['isLive']); + $this->assertTrue($state['isHidden']); + $this->assertNull($this->pollsTable()->get($poll->id)->current_slide_id); + } + + public function testPdfExportLeavesHiddenSlidesOut(): void + { + [$poll, $token] = $this->createPoll(); + $this->hidden($this->createSlide($poll, Slide::TYPE_CHOICE, ['question' => 'Versteckte Frage'])); + $this->createSlide($poll, Slide::TYPE_OPEN, ['question' => 'Sichtbare Frage']); + + $html = $this->exportHtml($token); + $this->assertStringNotContainsString('Versteckte Frage', $html); + $this->assertStringContainsString('Sichtbare Frage', $html); + $this->assertStringContainsString('Folie 1', $html); + } + + protected function hidden(Slide $slide): Slide + { + $slide->is_hidden = true; + $this->slidesTable()->saveOrFail($slide); + + return $slide; + } + + public function testOnlySlidesOfOwnPoll(): void + { + [, $token] = $this->createPoll(); + [$other] = $this->createPoll('Andere'); + $foreign = $this->createSlide($other); + + $this->post("/admin/$token/slides/{$foreign->id}/visibility", ['hidden' => 1]); + $this->assertResponseCode(404); + $this->assertFalse($this->slidesTable()->get($foreign->id)->is_hidden); + } +} diff --git a/tests/TestCase/Service/QaTest.php b/tests/TestCase/Service/QaTest.php index 10f2f1a..e805027 100644 --- a/tests/TestCase/Service/QaTest.php +++ b/tests/TestCase/Service/QaTest.php @@ -203,12 +203,16 @@ class QaTest extends TestCase $this->assertVoteFails('Du hast diese Frage nicht unterstützt.', fn() => $this->vote($poll, $slide, 'p3', $c, 'remove')); $this->vote($poll, $slide, 'p3', $a); + // While voting is open, the stage only gets the total: no ranking, no counts per question. $results = (new ResultsService())->forSlide($slide); - $this->assertSame([[$b, 3], [$a, 1], [$c, 0]], array_map(fn($q) => [$q['id'], $q['votes']], $results['questions'])); + $this->assertSame([$a, $b, $c], array_column($results['questions'], 'id')); + $this->assertArrayNotHasKey('votes', $results['questions'][0]); $this->assertSame(4, $results['upvotes']); + $ranked = (new QaService())->rankedQuestions($slide); + $this->assertSame([[$b, 3], [$a, 1], [$c, 0]], array_map(fn($q) => [$q['id'], $q['votes']], $ranked)); $this->vote($poll, $slide, 'p3', $b, 'remove'); - $this->assertSame(2, (new ResultsService())->forSlide($slide)['questions'][0]['votes'], 'remove withdraws only one upvote'); + $this->assertSame(2, (new QaService())->rankedQuestions($slide)[0]['votes'], 'remove withdraws only one upvote'); $this->vote($poll, $slide, 'p3', $b); // Voting view of participants: all questions, submission order, no counts. diff --git a/webroot/css/plenario.css b/webroot/css/plenario.css index 7ded41a..bc047a9 100644 --- a/webroot/css/plenario.css +++ b/webroot/css/plenario.css @@ -228,12 +228,14 @@ textarea { resize: vertical; } .slide-list { list-style: none; padding: 0; margin: 0 0 16px; } .slide-item { - display: grid; grid-template-columns: auto minmax(0, 1fr) auto; gap: 16px; align-items: center; + display: grid; grid-template-columns: auto minmax(0, 1fr); gap: 10px 16px; align-items: center; background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius); padding: 14px 16px; margin-bottom: 10px; } .slide-item--current { border-color: var(--c1); box-shadow: 0 0 0 2px rgba(224, 69, 123, .15); } -.slide-item__pos { width: 32px; height: 32px; border-radius: 50%; display: grid; place-items: center; background: var(--surface-2); font-weight: 700; } +.slide-item--hidden { border-style: dashed; background: var(--surface-2); } +.slide-item--hidden .slide-item__body { opacity: .75; } +.slide-item__pos {width: 32px; height: 32px; border-radius: 50%; display: grid; place-items: center; background: var(--surface-2); font-weight: 700; } .slide-item__lead { display: flex; align-items: center; gap: 4px; } .slide-list__hint { font-size: .85rem; margin: 0 0 8px; } .drag-handle { @@ -257,11 +259,8 @@ textarea { resize: vertical; } .slide-embed summary:hover { color: var(--text); } .slide-embed .copy-field { margin-top: 6px; } .slide-embed input { min-width: 0; flex: 1; } -.slide-item__actions { display: flex; gap: 6px; flex-wrap: wrap; justify-content: flex-end; } -@media (max-width: 700px) { - .slide-item { grid-template-columns: auto minmax(0, 1fr); } - .slide-item__actions { grid-column: 1 / -1; justify-content: flex-start; } -} +.slide-item__actions { grid-column: 2; display: flex; gap: 6px; flex-wrap: wrap; justify-content: flex-start; } +.button--icon { min-width: 40px; min-height: 36px; padding: 6px 8px; font-size: 1.05rem; } .type-picker { display: grid; grid-template-columns: repeat(auto-fill, minmax(190px, 1fr)); gap: 12px; } .type-card { display: block; padding: 14px; border-radius: var(--radius); border: 1px solid var(--border); background: var(--surface); text-decoration: none; color: var(--text); border-top: 4px solid var(--c0); } @@ -542,7 +541,9 @@ 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; } +/* Own questions: text on its own row, label and edit/delete below it (otherwise the text gets squeezed on phones). */ +.qa-item:has(.qa-own-actions) { flex-wrap: wrap; row-gap: 6px; } +.qa-item:has(.qa-own-actions) .qa-item__text { flex-basis: 100%; } .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; } @@ -551,6 +552,12 @@ textarea { resize: vertical; } .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); } +/* Phones: voting controls below the question, so the text keeps the full width. */ +@media (max-width: 700px) { + .qa-item:has(.qa-stepper) { flex-wrap: wrap; row-gap: 8px; } + .qa-item:has(.qa-stepper) .qa-item__text { flex-basis: 100%; } + .qa-item:has(.qa-stepper) { justify-content: center; } +} .qa-upvote { width: 44px; height: 44px; padding: 0; border-radius: 50%; border: 2px solid var(--qa); background: var(--surface); color: var(--qa); font: inherit; font-size: 1.3rem; font-weight: 700; line-height: 1; cursor: pointer; } .qa-upvote--up { background: var(--qa); color: var(--surface); } .qa-upvote:disabled { opacity: .45; cursor: not-allowed; } @@ -735,3 +742,27 @@ body.present { .theme-switch { display: inline-flex; align-items: center; justify-content: center; gap: 6px; min-width: 40px; height: 40px; padding: 0 8px; border-radius: 8px; border: 1px solid var(--border); background: transparent; color: var(--text); font: inherit; font-size: .9rem; cursor: pointer; } .theme-switch:hover { border-color: var(--primary); } .theme-switch__icon { font-size: 1.3em; line-height: 1; } + +/* Slide form in a dialog (admin dashboard) */ +/* The dialog itself does not scroll (overflow visible), so the close button can sit on its outer corner; + the inner panel carries border, background and scrolling. */ +.modal { width: min(720px, calc(100vw - 24px)); padding: 0; border: 0; background: transparent; color: var(--text); overflow: visible; } +.modal::backdrop { background: rgba(10, 12, 30, .55); } +.modal__panel { + max-height: calc(100dvh - 24px); overflow: auto; + border: 1px solid var(--border); border-radius: var(--radius); background: var(--surface); + box-shadow: 0 20px 60px rgba(0, 0, 0, .35); +} +.modal .card--form { max-width: none; margin: 0; border: 0; box-shadow: none; background: transparent; } +.modal__close { + position: absolute; top: -14px; right: -14px; z-index: 1; width: 36px; height: 36px; padding: 0; + display: grid; place-items: center; border: 1px solid var(--border); border-radius: 50%; + background: var(--surface); color: var(--text); font-size: 1rem; line-height: 1; cursor: pointer; + box-shadow: var(--shadow); +} +.modal__close:hover { background: var(--surface-2); } +.modal__close:focus-visible { outline: 3px solid var(--primary); outline-offset: 2px; } +.modal .message { margin: 16px 16px 0; cursor: default; } +body:has(dialog[open]) { overflow: hidden; } +.slide-item__actions form { display: contents; } +.slide-item__actions button:disabled, .admin-head__actions button:disabled { opacity: .6; cursor: progress; } diff --git a/webroot/js/plenario.js b/webroot/js/plenario.js index 897d729..89c25ff 100644 --- a/webroot/js/plenario.js +++ b/webroot/js/plenario.js @@ -13,6 +13,10 @@ * - [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-live] admin dashboard: forms inside (hide, delete, duplicate, …) run via fetch and refresh + * the [data-refresh] regions instead of reloading the page (header X-Fragment) + * - [data-modal] link whose target page (slide form) opens in the + * - [data-confirm] on a submit button: window.confirm() before the form is sent (replaces inline onclick, CSP) * - [data-theme-switch] cycles the colour scheme (data-theme on , stored in localStorage), * see templates/element/theme_init.php for the pre-paint part * @@ -1000,7 +1004,6 @@ var onStage = options && options.onStage; var onQuestion = options && options.onQuestion; var questions = results.questions; - var maxVotes = Math.max.apply(null, questions.map(function (q) { return q.votes; }).concat([1])); var children = [Qa.steps(results.stage, onStage, results.stages)]; var withVotes = results.maxUpvotes > 0; @@ -1027,11 +1030,10 @@ + results.maxUpvotes + (results.maxUpvotes === 1 ? ' Stimme' : ' Stimmen') + (results.maxPerQuestion < results.maxUpvotes ? ' (höchstens ' + results.maxPerQuestion + ' pro Frage)' : '') + ' · bisher ' + results.upvotes + ' vergeben' })); - children.push(el('ol', { class: 'qa-list' }, questions.map(function (question) { + // No counts or ranking while voting is open (the server sends none), so the stage does not sway the vote. + children.push(el('ul', { class: 'qa-list' }, questions.map(function (question) { return el('li', { class: 'qa-item' }, [ - el('span', { class: 'qa-item__text', text: question.text }), - votes(question), - el('span', { class: 'qa-item__bar', style: 'width:' + (question.votes / maxVotes * 100) + '%' }) + el('span', { class: 'qa-item__text', text: question.text }) ]); }))); } else if (questions.length === 0) { @@ -1127,8 +1129,8 @@ } } - function initCopy() { - document.querySelectorAll('[data-copy]').forEach(function (button) { + function initCopy(root) { + (root || document).querySelectorAll('[data-copy]').forEach(function (button) { button.addEventListener('click', function () { copyFrom(button); }); }); } @@ -1314,11 +1316,12 @@ if (!slide) { q('[data-status]').textContent = state.poll.isPaused ? 'Pause' : ''; + var allHidden = state.count === 0 && state.hiddenCount > 0; q('[data-question]').textContent = state.count === 0 - ? 'Noch keine Folien angelegt' + ? (allHidden ? 'Alle Folien sind ausgeblendet' : 'Noch keine Folien angelegt') : state.poll.title; q('[data-description]').textContent = state.count === 0 - ? 'Lege in der Verwaltung Fragen an.' + ? (allHidden ? 'Blende in der Verwaltung mindestens eine Folie ein.' : 'Lege in der Verwaltung Fragen an.') : (state.poll.isPaused ? 'Teilnehmende sehen gerade eine Pause-Seite. Drücke P oder → zum Fortsetzen.' : 'Drücke → um zu starten.'); @@ -1437,9 +1440,9 @@ var indicator = q('[data-live]'); indicator.textContent = !state.poll.isActive ? 'Umfrage geschlossen' - : (isLive ? '● live' : 'nicht live'); + : (state.isHidden ? 'ausgeblendet' : (isLive ? '● live' : 'nicht live')); indicator.classList.toggle('is-live', isLive); - q('[data-go-live]').hidden = isLive || !state.poll.isActive; + q('[data-go-live]').hidden = isLive || !state.poll.isActive || !!state.isHidden; } function goLive() { live = true; @@ -2562,8 +2565,228 @@ button.hidden = false; } + // ------------------------------------------------------------------ admin dashboard without reloads + + /** + * Loads server-rendered admin pages as fragments (layout "fragment": content + flash only) + * and merges them into the open page. The HTML comes from our own templates (escaped there); + * it is adopted as DOM nodes, never written with innerHTML. + */ + var Fragments = { + request: function (url, options) { + options = options || {}; + return fetch(url, { + method: options.method || 'GET', + body: options.body, + credentials: 'same-origin', + cache: 'no-store', + headers: { Accept: 'text/html', 'X-Fragment': '1', 'X-CSRF-Token': csrfToken() } + }).then(function (response) { + if (!response.ok) { + throw new Error('HTTP ' + response.status); + } + return response.text(); + }).then(function (html) { + return new DOMParser().parseFromString(html, 'text/html'); + }); + }, + + /** Replaces the [data-refresh] regions (all, or only `names`) with those of `doc`. */ + apply: function (doc, names) { + doc.querySelectorAll('[data-refresh]').forEach(function (fresh) { + var name = fresh.getAttribute('data-refresh'); + var old = document.querySelector('[data-refresh="' + name + '"]'); + if (!old || (names && names.indexOf(name) < 0)) { + return; + } + var node = document.importNode(fresh, true); + old.replaceWith(node); + initWidgets(node); + }); + }, + + /** Shows an error where the user is looking (dialog or flash area). */ + fail: function (container, text) { + var message = el('div', { class: 'message error', role: 'alert', 'data-dismiss': '', text: text }); + container.insertBefore(message, container.firstChild); + } + }; + + function initAdminDashboard() { + var dialog = document.querySelector('[data-modal-dialog]'); + var body = dialog ? dialog.querySelector('[data-modal-body]') : null; + var dirty = false; + var focusId = null; + + function flashArea() { + return document.querySelector('[data-refresh="flash"]') || document.body; + } + + /** Keeps the keyboard position after a list refresh: same button, else the slide, else the next slide. */ + function restoreFocus(target) { + if (!target) { + return; + } + var item = target.id ? document.querySelector('[data-slide-id="' + target.id + '"]') : null; + var node = null; + if (item) { + node = (target.action && item.querySelector('form[action="' + target.action + '"] button')) + || item.querySelector('.slide-item__title'); + } else if (target.nextId) { + node = document.querySelector('[data-slide-id="' + target.nextId + '"] .slide-item__title'); + } + if (node) { + node.focus(); + } + } + + function refreshList() { + return Fragments.request(window.location.href).then(function (doc) { + Fragments.apply(doc, ['head', 'slides']); + }); + } + + function openModal(doc) { + var content = doc.querySelector('[data-modal-content]'); + var flash = doc.querySelector('[data-refresh="flash"]'); + body.replaceChildren(); + if (flash && flash.childNodes.length) { + // Shown inside the dialog (validation errors), not as flash of the page behind it. + var notes = document.importNode(flash, true); + notes.removeAttribute('data-refresh'); + body.appendChild(notes); + } + body.appendChild(document.importNode(content, true)); + initWidgets(body); + dirty = false; + if (!dialog.open) { + dialog.showModal(); + } + dialog.querySelector('[data-modal-panel]').scrollTop = 0; + } + + function requestClose() { + if (dirty && !window.confirm('Änderungen verwerfen?')) { + return; + } + dialog.close(); + } + + /** Result of a POST: either the dashboard (done) or a form (open in the dialog). */ + function handle(doc, source) { + if (doc.querySelector('[data-modal-content]')) { + // A form: validation errors (dialog stays open) or the copy of a duplicated slide. + var wasOpen = dialog.open; + openModal(doc); + + return wasOpen ? null : refreshList(); + } + Fragments.apply(doc); + if (dialog && dialog.open) { + dirty = false; + dialog.close(); + } + restoreFocus(source); + + return null; + } + + document.addEventListener('submit', function (event) { + var form = event.target; + var submitter = event.submitter || form.querySelector('button[type=submit], button:not([type])'); + var confirmText = submitter && submitter.getAttribute('data-confirm'); + if (confirmText && !window.confirm(confirmText)) { + event.preventDefault(); + return; + } + var inDialog = dialog !== null && dialog.contains(form); + if (!inDialog && !form.closest('[data-live]')) { + return; // plain form: normal navigation + } + event.preventDefault(); + if (form.hasAttribute('aria-busy')) { + return; + } + var item = form.closest('[data-slide-id]'); + var next = item ? item.nextElementSibling : null; + var source = inDialog ? { id: focusId } : { + id: item ? item.getAttribute('data-slide-id') : null, + action: form.getAttribute('action'), + nextId: next ? next.getAttribute('data-slide-id') : null + }; + form.setAttribute('aria-busy', 'true'); + if (submitter) { + submitter.disabled = true; + } + Fragments.request(form.action, { method: 'POST', body: new FormData(form) }) + .then(function (doc) { return handle(doc, source); }) + .catch(function () { + form.removeAttribute('aria-busy'); + if (submitter) { + submitter.disabled = false; + } + Fragments.fail(inDialog ? body : flashArea(), 'Das hat nicht geklappt. Bitte lade die Seite neu und versuche es noch einmal.'); + }); + }); + + if (!dialog) { + return; + } + + document.addEventListener('click', function (event) { + var link = event.target.closest ? event.target.closest('a[data-modal]') : null; + if (!link || event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) { + return; + } + event.preventDefault(); + var item = link.closest('[data-slide-id]'); + focusId = item ? item.getAttribute('data-slide-id') : null; + Fragments.request(link.href).then(openModal).catch(function () { + window.location.href = link.href; // no dialog possible: open the page as usual + }); + }); + + dialog.addEventListener('click', function (event) { + if (event.target.closest('[data-modal-close]')) { + event.preventDefault(); + requestClose(); + } + }); + + // Only a click that starts and ends on the backdrop closes (not a text selection dragged outside). + var pressedOnBackdrop = false; + dialog.addEventListener('mousedown', function (event) { pressedOnBackdrop = event.target === dialog; }); + dialog.addEventListener('click', function (event) { + if (event.target === dialog && pressedOnBackdrop) { + requestClose(); + } + }); + + dialog.addEventListener('cancel', function (event) { + if (dirty && !window.confirm('Änderungen verwerfen?')) { + event.preventDefault(); + } + }); + dialog.addEventListener('close', function () { + body.replaceChildren(); + dirty = false; + }); + body.addEventListener('input', function () { dirty = true; }); + body.addEventListener('change', function () { dirty = true; }); + } + // ------------------------------------------------------------------ boot + /** Initialises the widgets inside `root` (the whole page at boot, or a freshly inserted fragment). */ + function initWidgets(root) { + initCopy(root); + root.querySelectorAll('[data-youtube-form]').forEach(initYouTubeForm); + root.querySelectorAll('[data-quiz-options]').forEach(initQuizOptions); + root.querySelectorAll('[data-sortable]').forEach(initSortable); + root.querySelectorAll('[data-order-options]').forEach(initOrderOptions); + root.querySelectorAll('[data-scale-style]').forEach(initScaleStyle); + } + // Flash messages: click hides them (delegated, no inline handlers because of the CSP). document.addEventListener('click', function (event) { var message = event.target.closest ? event.target.closest('[data-dismiss]') : null; @@ -2574,16 +2797,12 @@ document.addEventListener('DOMContentLoaded', function () { document.querySelectorAll('[data-theme-switch]').forEach(initThemeSwitch); - initCopy(); + initWidgets(document); initShare(); - document.querySelectorAll('[data-youtube-form]').forEach(initYouTubeForm); + initAdminDashboard(); document.querySelectorAll('[data-presenter]').forEach(initPresenter); 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); - document.querySelectorAll('[data-scale-style]').forEach(initScaleStyle); // Prevent double submits of vote forms. document.querySelectorAll('.vote-form').forEach(function (form) {
    #