Add drag and drop sorting for slides #8
No files matched your search
@@ -55,7 +55,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
|
||||
AdminController Dashboard, Settings, Present, State-JSON, Control, QR, CSV-Export, Token rotieren, Löschen
|
||||
SlidesController Folien-CRUD, Sortieren, Antworten zurücksetzen
|
||||
SlidesController Folien-CRUD, Sortieren (↑/↓ und Drag & Drop via `reorder`, JSON), Antworten zurücksetzen
|
||||
ParticipateController /p/{code}: Ansicht, State-JSON, Abstimmen; anonymes Cookie plenario_pid
|
||||
Mailer/ PollMailer (adminLink, recovery), Transport/FileTransport (lokal)
|
||||
Model/ Polls → Slides → SlideOptions, Slides → Responses
|
||||
@@ -66,7 +66,7 @@ src/
|
||||
ThrottleService Rate-Limit pro IP (Cache 'throttle')
|
||||
templates/ Deutsche UI, Layouts: default, present (Vollbild, dunkel), error, email
|
||||
webroot/css/plenario.css Eigenes CSS, kein Framework
|
||||
webroot/js/plenario.js Vanilla JS: Polling, Ergebnis-Rendering, Presenter-Steuerung
|
||||
webroot/js/plenario.js Vanilla JS: Polling, Ergebnis-Rendering, Presenter-Steuerung, Folien-Sortierung (Pointer Events + Pfeiltasten)
|
||||
tests/ PHPUnit; PlenarioTestTrait erzeugt Testdaten, Fixtures sind leer
|
||||
```
|
||||
|
||||
|
||||
@@ -61,6 +61,8 @@ 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'])
|
||||
->setPatterns($token)->setMethods(['POST']);
|
||||
$admin->connect('/slides/{id}/move/{direction}', 'Slides::move', ['_name' => 'slides:move'])
|
||||
->setPatterns($token + ['direction' => 'up|down'])->setPass(['id', 'direction'])->setMethods(['POST']);
|
||||
$admin->connect('/slides/{id}/reset', 'Slides::reset', ['_name' => 'slides:reset'])
|
||||
|
||||
@@ -120,6 +120,27 @@ class SlidesController extends AdminAppController
|
||||
return $this->redirect($this->adminUrl());
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves a complete new slide order (drag & drop), expects `ids[]` and answers with JSON.
|
||||
*
|
||||
* @return \Cake\Http\Response
|
||||
*/
|
||||
public function reorder(): Response
|
||||
{
|
||||
$this->request->allowMethod(['post']);
|
||||
$ids = $this->request->getData('ids');
|
||||
$ids = is_array($ids) ? array_values(array_map('intval', array_filter($ids, 'is_numeric'))) : [];
|
||||
|
||||
if (!$this->Slides->reorder($this->poll->id, $ids)) {
|
||||
return $this->json([
|
||||
'ok' => false,
|
||||
'message' => __('Die Reihenfolge konnte nicht gespeichert werden. Bitte lade die Seite neu.'),
|
||||
], 409);
|
||||
}
|
||||
|
||||
return $this->json(['ok' => true, 'message' => __('Reihenfolge gespeichert.')]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes all responses of a slide.
|
||||
*
|
||||
|
||||
@@ -294,6 +294,40 @@ class SlidesTable extends Table
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies a complete new order (e.g. from drag & drop).
|
||||
*
|
||||
* The ids must be exactly the slides of the poll, each once – otherwise
|
||||
* (stale page, foreign ids) nothing is changed. Repeating the same order is a no-op.
|
||||
*
|
||||
* @param int $pollId Poll id
|
||||
* @param list<int> $slideIds Slide ids in their new order
|
||||
* @return bool Whether the order was valid and is now applied
|
||||
*/
|
||||
public function reorder(int $pollId, array $slideIds): bool
|
||||
{
|
||||
$current = $this->find('list', valueField: 'position')
|
||||
->where(['poll_id' => $pollId])
|
||||
->toArray();
|
||||
$given = $slideIds;
|
||||
$existing = array_map('intval', array_keys($current));
|
||||
sort($given);
|
||||
sort($existing);
|
||||
if ($given !== $existing) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return (bool)$this->getConnection()->transactional(function () use ($slideIds, $current): bool {
|
||||
foreach ($slideIds as $index => $id) {
|
||||
if ($current[$id] !== $index + 1) {
|
||||
$this->updateAll(['position' => $index + 1], ['id' => $id]);
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Renumbers positions 1..n (closes gaps after deletions).
|
||||
*
|
||||
|
||||
@@ -52,13 +52,21 @@ $url = fn(string $name, array $params = []) => ['_name' => $name, 'token' => $ad
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
|
||||
<ol class="slide-list">
|
||||
<?php if (count($slides) > 1) : ?>
|
||||
<p class="muted slide-list__hint" data-sortable-hint hidden><?= __('Tipp: Folien am Griff ⠿ ziehen, um die Reihenfolge zu ändern (oder Griff fokussieren und Pfeiltasten nutzen).') ?></p>
|
||||
<?php endif; ?>
|
||||
<ol class="slide-list" data-sortable="<?= h($this->Url->build($url('slides:reorder'))) ?>">
|
||||
<?php foreach ($slides as $i => $slide) :
|
||||
$isCurrent = $poll->current_slide_id === $slide->id;
|
||||
$count = $responseCounts[$slide->id] ?? 0;
|
||||
?>
|
||||
<li class="slide-item<?= $isCurrent ? ' slide-item--current' : '' ?>">
|
||||
<div class="slide-item__pos"><?= $i + 1 ?></div>
|
||||
<li class="slide-item<?= $isCurrent ? ' slide-item--current' : '' ?>" data-slide-id="<?= $slide->id ?>">
|
||||
<div class="slide-item__lead">
|
||||
<button type="button" class="drag-handle" data-drag-handle hidden
|
||||
aria-label="<?= h(__('Folie „{0}“ verschieben (Pfeiltasten)', $slide->question)) ?>"
|
||||
title="<?= __('Ziehen zum Sortieren') ?>">⠿</button>
|
||||
<span class="slide-item__pos" data-position><?= $i + 1 ?></span>
|
||||
</div>
|
||||
<div class="slide-item__body">
|
||||
<div class="slide-item__meta">
|
||||
<span class="badge badge--type-<?= h($slide->type) ?>"><?= h($slide->typeLabel()) ?></span>
|
||||
@@ -113,6 +121,7 @@ $url = fn(string $name, array $params = []) => ['_name' => $name, 'token' => $ad
|
||||
</li>
|
||||
<?php endforeach; ?>
|
||||
</ol>
|
||||
<p class="sr-only" role="status" aria-live="polite" data-sortable-status></p>
|
||||
|
||||
<h3><?= __('Neue Folie') ?></h3>
|
||||
<div class="type-picker">
|
||||
|
||||
@@ -182,6 +182,46 @@ class AdminControllerTest extends TestCase
|
||||
$this->assertSame(1, $this->slidesTable()->get($first->id)->position);
|
||||
}
|
||||
|
||||
public function testReorderSlidesByDragAndDrop(): void
|
||||
{
|
||||
[$poll, $token] = $this->createPoll();
|
||||
$a = $this->createSlide($poll, Slide::TYPE_OPEN);
|
||||
$b = $this->createSlide($poll, Slide::TYPE_SCALE);
|
||||
$c = $this->createSlide($poll, Slide::TYPE_CHOICE);
|
||||
$positions = fn(): array => array_map(
|
||||
fn($s) => $s->id,
|
||||
$this->slidesTable()->listForPoll($poll->id),
|
||||
);
|
||||
|
||||
$this->get("/admin/$token");
|
||||
$this->assertResponseContains('data-sortable=');
|
||||
$this->assertResponseContains('data-slide-id="' . $a->id . '"');
|
||||
|
||||
$this->configRequest(['headers' => ['Accept' => 'application/json']]);
|
||||
$this->post("/admin/$token/slides/reorder", ['ids' => [$c->id, $a->id, $b->id]]);
|
||||
$this->assertResponseOk();
|
||||
$this->assertTrue(json_decode((string)$this->_response->getBody(), true)['ok']);
|
||||
$this->assertSame([$c->id, $a->id, $b->id], $positions());
|
||||
$this->assertSame(1, $this->slidesTable()->get($c->id)->position);
|
||||
|
||||
// Same order again is fine (idempotent).
|
||||
$this->configRequest(['headers' => ['Accept' => 'application/json']]);
|
||||
$this->post("/admin/$token/slides/reorder", ['ids' => [$c->id, $a->id, $b->id]]);
|
||||
$this->assertResponseOk();
|
||||
$this->assertSame([$c->id, $a->id, $b->id], $positions());
|
||||
|
||||
// Incomplete, duplicated or foreign ids change nothing.
|
||||
[$other] = $this->createPoll('Andere');
|
||||
$foreign = $this->createSlide($other, Slide::TYPE_OPEN);
|
||||
foreach ([[$a->id, $b->id], [$a->id, $a->id, $b->id], [$a->id, $b->id, $foreign->id], []] as $ids) {
|
||||
$this->configRequest(['headers' => ['Accept' => 'application/json']]);
|
||||
$this->post("/admin/$token/slides/reorder", ['ids' => $ids]);
|
||||
$this->assertResponseCode(409);
|
||||
$this->assertSame([$c->id, $a->id, $b->id], $positions());
|
||||
}
|
||||
$this->assertSame(1, $this->slidesTable()->get($foreign->id)->position);
|
||||
}
|
||||
|
||||
public function testPresentStartsWithFirstSlideAndControlNavigates(): void
|
||||
{
|
||||
[$poll, $token] = $this->createPoll();
|
||||
|
||||
@@ -186,18 +186,33 @@ textarea { resize: vertical; }
|
||||
|
||||
.slide-list { list-style: none; padding: 0; margin: 0 0 16px; }
|
||||
.slide-item {
|
||||
display: grid; grid-template-columns: 40px minmax(0, 1fr) auto; gap: 16px; align-items: center;
|
||||
display: grid; grid-template-columns: auto minmax(0, 1fr) auto; gap: 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__lead { display: flex; align-items: center; gap: 4px; }
|
||||
.slide-list__hint { font-size: .85rem; margin: 0 0 8px; }
|
||||
.drag-handle {
|
||||
width: 32px; height: 40px; display: grid; place-items: center; padding: 0; border: 0; border-radius: 6px;
|
||||
background: transparent; color: var(--muted); font-size: 1.3rem; line-height: 1;
|
||||
cursor: grab; touch-action: none; user-select: none;
|
||||
}
|
||||
.drag-handle:hover { background: var(--surface-2); }
|
||||
.drag-handle:focus-visible { outline: 3px solid var(--primary); outline-offset: 1px; }
|
||||
.slide-list--sorting, .slide-list--sorting * { cursor: grabbing !important; user-select: none; }
|
||||
.slide-item--dragging { position: relative; z-index: 2; opacity: .95; box-shadow: 0 10px 30px rgba(0, 0, 0, .18); border-color: var(--c1); }
|
||||
.slide-item--saving { transition: opacity .2s; opacity: .6; }
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
.slide-item { transition: box-shadow .15s; }
|
||||
}
|
||||
.slide-item__meta { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; font-size: .85rem; margin-bottom: 4px; }
|
||||
.slide-item__title { font-weight: 600; color: var(--text); text-decoration: none; word-break: break-word; }
|
||||
.slide-item__options { margin: 4px 0 0; font-size: .85rem; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.slide-item__actions { display: flex; gap: 6px; flex-wrap: wrap; justify-content: flex-end; }
|
||||
@media (max-width: 700px) {
|
||||
.slide-item { grid-template-columns: 32px minmax(0, 1fr); }
|
||||
.slide-item { grid-template-columns: auto minmax(0, 1fr); }
|
||||
.slide-item__actions { grid-column: 1 / -1; justify-content: flex-start; }
|
||||
}
|
||||
|
||||
|
||||
+173
-1
@@ -7,6 +7,7 @@
|
||||
* - [data-participant] participant page, polls /p/{code}/state
|
||||
* - [data-countdown] quiz timer (data-remaining = seconds), fires `plenario:timeup` on document
|
||||
* - [data-quiz-options] slide form: "add answer" button for quiz slides
|
||||
* - [data-sortable] admin slide list: drag & drop / arrow keys via [data-drag-handle], POSTs ids[] to the URL
|
||||
*
|
||||
* Results JSON shape: see src/Service/ResultsService.php
|
||||
*/
|
||||
@@ -55,7 +56,11 @@
|
||||
function postJson(url, data) {
|
||||
var body = new FormData();
|
||||
Object.keys(data).forEach(function (key) {
|
||||
body.append(key, data[key]);
|
||||
if (Array.isArray(data[key])) {
|
||||
data[key].forEach(function (value) { body.append(key + '[]', value); });
|
||||
} else {
|
||||
body.append(key, data[key]);
|
||||
}
|
||||
});
|
||||
return fetch(url, {
|
||||
method: 'POST',
|
||||
@@ -927,6 +932,172 @@
|
||||
update();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ sortable slide list
|
||||
|
||||
function initSortable(list) {
|
||||
var url = list.getAttribute('data-sortable');
|
||||
var section = list.parentNode;
|
||||
var status = section.querySelector('[data-sortable-status]');
|
||||
var hint = section.querySelector('[data-sortable-hint]');
|
||||
var error = null;
|
||||
var saving = Promise.resolve();
|
||||
var drag = null;
|
||||
|
||||
function items() {
|
||||
return Array.prototype.slice.call(list.children).filter(function (node) {
|
||||
return node.hasAttribute('data-slide-id');
|
||||
});
|
||||
}
|
||||
|
||||
function order() {
|
||||
return items().map(function (item) { return item.getAttribute('data-slide-id'); });
|
||||
}
|
||||
|
||||
function renumber() {
|
||||
items().forEach(function (item, index) {
|
||||
var pos = item.querySelector('[data-position]');
|
||||
if (pos) {
|
||||
pos.textContent = String(index + 1);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function label(item) {
|
||||
var title = item.querySelector('.slide-item__title');
|
||||
return title ? title.textContent : '';
|
||||
}
|
||||
|
||||
function announce(text) {
|
||||
if (status) {
|
||||
status.textContent = text;
|
||||
}
|
||||
}
|
||||
|
||||
function announceMove(item) {
|
||||
var all = items();
|
||||
announce('„' + label(item) + '“ ist jetzt an Position ' + (all.indexOf(item) + 1) + ' von ' + all.length + '.');
|
||||
}
|
||||
|
||||
function showError(message) {
|
||||
if (!error) {
|
||||
var reload = el('button', { type: 'button', class: 'button button--small', text: 'Seite neu laden' });
|
||||
reload.addEventListener('click', function () { window.location.reload(); });
|
||||
error = el('div', { class: 'notice', role: 'alert' }, [el('span'), document.createTextNode(' '), reload]);
|
||||
section.insertBefore(error, list);
|
||||
}
|
||||
error.firstChild.textContent = message;
|
||||
}
|
||||
|
||||
function save(item) {
|
||||
var ids = order();
|
||||
renumber();
|
||||
announceMove(item);
|
||||
item.classList.add('slide-item--saving');
|
||||
// Sequential, so an older order can never overwrite a newer one.
|
||||
saving = saving.then(function () {
|
||||
return postJson(url, { ids: ids });
|
||||
}).catch(function () {
|
||||
showError('Die Reihenfolge konnte nicht gespeichert werden. Bitte lade die Seite neu.');
|
||||
}).then(function () {
|
||||
item.classList.remove('slide-item--saving');
|
||||
});
|
||||
}
|
||||
|
||||
// Keyboard: arrow keys on the handle move the slide by one.
|
||||
list.addEventListener('keydown', function (event) {
|
||||
var handle = event.target.closest('[data-drag-handle]');
|
||||
if (!handle || (event.key !== 'ArrowUp' && event.key !== 'ArrowDown')) {
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
var item = handle.closest('[data-slide-id]');
|
||||
var up = event.key === 'ArrowUp';
|
||||
var sibling = up ? item.previousElementSibling : item.nextElementSibling;
|
||||
if (!sibling || !sibling.hasAttribute('data-slide-id')) {
|
||||
return;
|
||||
}
|
||||
list.insertBefore(item, up ? sibling : sibling.nextElementSibling);
|
||||
handle.focus();
|
||||
save(item);
|
||||
});
|
||||
|
||||
// Pointer (mouse, touch, pen): drag by the handle.
|
||||
function pageTop(node) {
|
||||
return node.getBoundingClientRect().top + window.scrollY;
|
||||
}
|
||||
|
||||
function onMove(event) {
|
||||
if (!drag || event.pointerId !== drag.pointerId) {
|
||||
return;
|
||||
}
|
||||
var item = drag.item;
|
||||
var all = items();
|
||||
var index = all.indexOf(item);
|
||||
var prev = all[index - 1];
|
||||
var next = all[index + 1];
|
||||
var top = event.clientY + window.scrollY - drag.grabOffset;
|
||||
var bottom = top + item.offsetHeight;
|
||||
|
||||
if (prev && top < pageTop(prev) + prev.offsetHeight / 2) {
|
||||
list.insertBefore(item, prev);
|
||||
} else if (next && bottom > pageTop(next) + next.offsetHeight / 2) {
|
||||
list.insertBefore(item, next.nextElementSibling);
|
||||
}
|
||||
item.style.transform = '';
|
||||
item.style.transform = 'translateY(' + (top - pageTop(item)) + 'px)';
|
||||
|
||||
// Scroll the page when dragging close to the viewport edge.
|
||||
if (event.clientY < 60) {
|
||||
window.scrollBy(0, -12);
|
||||
} else if (event.clientY > window.innerHeight - 60) {
|
||||
window.scrollBy(0, 12);
|
||||
}
|
||||
}
|
||||
|
||||
function onEnd(event) {
|
||||
if (!drag || event.pointerId !== drag.pointerId) {
|
||||
return;
|
||||
}
|
||||
var item = drag.item;
|
||||
var changed = order().join(',') !== drag.before;
|
||||
item.style.transform = '';
|
||||
item.classList.remove('slide-item--dragging');
|
||||
list.classList.remove('slide-list--sorting');
|
||||
drag = null;
|
||||
if (changed) {
|
||||
save(item);
|
||||
}
|
||||
}
|
||||
|
||||
list.addEventListener('pointerdown', function (event) {
|
||||
var handle = event.target.closest('[data-drag-handle]');
|
||||
if (!handle || event.button !== 0 || drag) {
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
var item = handle.closest('[data-slide-id]');
|
||||
handle.setPointerCapture(event.pointerId);
|
||||
drag = {
|
||||
item: item,
|
||||
pointerId: event.pointerId,
|
||||
grabOffset: event.clientY - item.getBoundingClientRect().top,
|
||||
before: order().join(',')
|
||||
};
|
||||
item.classList.add('slide-item--dragging');
|
||||
list.classList.add('slide-list--sorting');
|
||||
});
|
||||
list.addEventListener('pointermove', onMove);
|
||||
list.addEventListener('pointerup', onEnd);
|
||||
list.addEventListener('pointercancel', onEnd);
|
||||
|
||||
if (items().length > 1) {
|
||||
list.querySelectorAll('[data-drag-handle]').forEach(function (handle) { handle.hidden = false; });
|
||||
if (hint) {
|
||||
hint.hidden = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ boot
|
||||
|
||||
document.addEventListener('DOMContentLoaded', function () {
|
||||
@@ -934,6 +1105,7 @@
|
||||
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);
|
||||
|
||||
// Prevent double submits of vote forms.
|
||||
document.querySelectorAll('.vote-form').forEach(function (form) {
|
||||
|
||||
Reference in new issue
Block a user