Files
Plenario/webroot/js/plenario.js
T
gnilebein e9e1159ad9
CI / Deploy / test (push) Successful in 57s
CI / Deploy / deploy (push) Successful in 8s
Merge pull request 'Let the presenter resume a paused poll with the pause button' (#38) from fix/presenter-resume into main
Reviewed-on: #38
2026-11-09 10:51:57 +01:00

2093 lines
93 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* PlenarIO frontend – plain JavaScript, no build step, no dependencies.
*
* Modules (auto-initialised by data attributes):
* - [data-copy] copy the value of the sibling [data-copy-source]
* - [data-share] native share sheet (Web Share API), fallback: copy like [data-copy]
* - [data-youtube-form] slide form: "Link prüfen" for YouTube slides (status + preview)
* - [data-presenter] presenter screen, polls /admin/{token}/state;
* with [data-embed]: one embedded slide (/e/{key}/{id}), goes live while visible
* - [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
* - [data-order-options] slide form of ordering slides: sortable rows (correct order), "add entry"
* - [data-order-form] participant answer of ordering slides: sortable items posting order[]
* - [data-theme-switch] cycles the colour scheme (data-theme on <html>, stored in localStorage),
* see templates/element/theme_init.php for the pre-paint part
*
* Results JSON shape: see src/Service/ResultsService.php
*/
(function () {
'use strict';
// ------------------------------------------------------------------ helpers
function el(tag, attrs, children) {
var node = document.createElement(tag);
Object.keys(attrs || {}).forEach(function (key) {
if (key === 'text') {
node.textContent = attrs[key];
} else if (key === 'style') {
node.setAttribute('style', attrs[key]);
} else {
node.setAttribute(key, attrs[key]);
}
});
(children || []).forEach(function (child) {
if (child) {
node.appendChild(child);
}
});
return node;
}
function csrfToken() {
var meta = document.querySelector('meta[name="csrf-token"]');
return meta ? meta.getAttribute('content') : '';
}
function getJson(url) {
return fetch(url, {
headers: { Accept: 'application/json' },
credentials: 'same-origin',
cache: 'no-store'
}).then(function (response) {
if (!response.ok) {
throw new Error('HTTP ' + response.status);
}
return response.json();
});
}
function postJson(url, data) {
var body = new FormData();
Object.keys(data).forEach(function (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',
body: body,
credentials: 'same-origin',
headers: {
Accept: 'application/json',
'X-Requested-With': 'XMLHttpRequest',
'X-CSRF-Token': csrfToken()
}
}).then(function (response) {
// 429 (too many answers) carries a message for the participant like any other rejection.
if (!response.ok && response.status !== 429) {
throw new Error('HTTP ' + response.status);
}
return response.json();
});
}
/** Polls `fn` every `interval` ms, pauses while the tab is hidden. */
function poll(fn, interval) {
var timer = null;
function tick() {
Promise.resolve(fn()).catch(function () { /* retry next tick */ }).then(schedule);
}
function schedule() {
clearTimeout(timer);
timer = setTimeout(tick, document.hidden ? interval * 5 : interval);
}
document.addEventListener('visibilitychange', function () {
if (!document.hidden) {
tick();
}
});
tick();
return { now: tick };
}
function formatNumber(value) {
return Number(value).toLocaleString('de-DE');
}
function formatSeconds(seconds) {
var s = Math.max(0, Math.ceil(seconds));
return Math.floor(s / 60) + ':' + String(s % 60).padStart(2, '0');
}
// ------------------------------------------------------------------ countdown
/**
* Ticks every [data-countdown] element (data-remaining = seconds left when it
* was rendered). The server stays authoritative: when a timer reaches zero,
* `plenario:timeup` is dispatched so the page fetches the new state.
*/
var Countdown = {
timer: null,
start: function () {
if (Countdown.timer === null) {
Countdown.timer = setInterval(Countdown.tick, 250);
}
Countdown.tick();
},
tick: function () {
document.querySelectorAll('[data-countdown]').forEach(function (node) {
if (!node.plenarioDeadline) {
node.plenarioDeadline = Date.now() + parseFloat(node.getAttribute('data-remaining')) * 1000;
}
var left = (node.plenarioDeadline - Date.now()) / 1000;
var value = node.querySelector('[data-countdown-value]') || node;
var text = formatSeconds(left);
if (value.textContent !== text) {
value.textContent = text;
}
node.classList.toggle('is-urgent', left <= 5);
if (left <= 0 && !node.plenarioDone) {
node.plenarioDone = true;
node.classList.add('is-over');
document.dispatchEvent(new CustomEvent('plenario:timeup'));
}
});
}
};
// ------------------------------------------------------------------ word matching
/**
* Suggestions for the word cloud input: prefix/substring matches, small
* typos (Levenshtein) and similar sounding words (Kölner Phonetik).
*/
var Words = {
/** Lower case, umlauts folded, accents and non-alphanumerics removed. */
fold: function (text) {
return String(text).toLowerCase()
.replace(/ä/g, 'ae').replace(/ö/g, 'oe').replace(/ü/g, 'ue').replace(/ß/g, 'ss')
.normalize('NFD').replace(/[̀-ͯ]/g, '')
.replace(/[^a-z0-9]/g, '');
},
/** Kölner Phonetik – phonetic code for German words. */
phonetic: function (text) {
var s = String(text).toUpperCase()
.replace(/Ä/g, 'A').replace(/Ö/g, 'O').replace(/Ü/g, 'U').replace(/ß/g, 'S')
.normalize('NFD').replace(/[̀-ͯ]/g, '')
.replace(/[^A-Z]/g, '');
var codes = '';
for (var i = 0; i < s.length; i++) {
var c = s[i];
var prev = i > 0 ? s[i - 1] : '';
var next = s[i + 1] || '';
var code = '';
if ('AEIJOUY'.indexOf(c) >= 0) {
code = '0';
} else if (c === 'B') {
code = '1';
} else if (c === 'P') {
code = next === 'H' ? '3' : '1';
} else if (c === 'D' || c === 'T') {
code = next && 'CSZ'.indexOf(next) >= 0 ? '8' : '2';
} else if ('FVW'.indexOf(c) >= 0) {
code = '3';
} else if ('GKQ'.indexOf(c) >= 0) {
code = '4';
} else if (c === 'C') {
if (i === 0) {
code = next && 'AHKLOQRUX'.indexOf(next) >= 0 ? '4' : '8';
} else {
code = next && 'AHKOQUX'.indexOf(next) >= 0 && 'SZ'.indexOf(prev) < 0 ? '4' : '8';
}
} else if (c === 'X') {
code = prev && 'CKQ'.indexOf(prev) >= 0 ? '8' : '48';
} else if (c === 'L') {
code = '5';
} else if (c === 'M' || c === 'N') {
code = '6';
} else if (c === 'R') {
code = '7';
} else if (c === 'S' || c === 'Z') {
code = '8';
}
// H and anything else: no code
codes += code;
}
var collapsed = '';
for (var j = 0; j < codes.length; j++) {
if (codes[j] !== collapsed[collapsed.length - 1]) {
collapsed += codes[j];
}
}
return collapsed.charAt(0) + collapsed.slice(1).replace(/0/g, '');
},
levenshtein: function (a, b) {
if (a === b) {
return 0;
}
var row = [];
for (var j = 0; j <= b.length; j++) {
row.push(j);
}
for (var i = 1; i <= a.length; i++) {
var diag = row[0];
row[0] = i;
for (var k = 1; k <= b.length; k++) {
var tmp = row[k];
row[k] = Math.min(row[k] + 1, row[k - 1] + 1, diag + (a[i - 1] === b[k - 1] ? 0 : 1));
diag = tmp;
}
}
return row[b.length];
},
/** Score 0 (no match) .. 100 (same word). */
score: function (input, word) {
var a = Words.fold(input);
var b = Words.fold(word);
if (!a || !b) {
return 0;
}
if (a === b) {
return 100;
}
if (b.indexOf(a) === 0) {
return 90 - Math.min(20, b.length - a.length);
}
var pa = Words.phonetic(input);
var pb = Words.phonetic(word);
if (a.length >= 3 && pa && pa === pb) {
return 70;
}
var tolerance = a.length >= 8 ? 2 : (a.length >= 4 ? 1 : 0);
if (tolerance && Words.levenshtein(a, b) <= tolerance) {
return 65;
}
if (a.length >= 3 && b.indexOf(a) > 0) {
return 60;
}
// Typo within what has been typed so far ("Kafe" → "Kaffeemaschine").
if (tolerance && b.length > a.length && Words.levenshtein(a, b.slice(0, a.length)) <= tolerance) {
return 50;
}
if (a.length >= 4 && pa.length >= 3 && pb.indexOf(pa) === 0) {
return 45;
}
return 0;
},
/** Matching existing cloud words ({key, text, count}) for an input, best first; optional limit. */
suggest: function (input, words, limit) {
if (Words.fold(input).length < 2) {
return [];
}
return words
.map(function (word) { return { word: word, score: Words.score(input, word.text) }; })
.filter(function (item) { return item.score > 0; })
.sort(function (x, y) { return y.score - x.score || y.word.count - x.word.count; })
.slice(0, limit || undefined)
.map(function (item) { return item.word; });
}
};
// ------------------------------------------------------------------ comments
/**
* Rotating comments of a scale slide. The results are re-rendered on every poll,
* so position, pause and timer live here and survive the re-render.
*/
var Comments = {
intervalMs: 8000,
key: null,
index: 0,
paused: false,
timer: null,
items: [],
node: null,
/**
* @param {Array} items comments, oldest first
* @param {number} [seconds] time per comment (slide setting), default 8
*/
render: function (items, seconds) {
// A different first comment means a different slide (or a reset): start over.
var key = String(items[0].id);
if (key !== Comments.key) {
Comments.key = key;
Comments.index = 0;
Comments.paused = false;
}
var intervalMs = seconds > 0 ? seconds * 1000 : 8000;
if (intervalMs !== Comments.intervalMs) {
// Setting changed (or another slide): apply it right away.
Comments.intervalMs = intervalMs;
clearInterval(Comments.timer);
Comments.timer = null;
}
Comments.items = items;
Comments.index = Math.min(Comments.index, items.length - 1);
var button = function (action, label, text) {
return el('button', {
type: 'button',
class: 'button button--small comments__button',
'data-comment-action': action,
'aria-label': label,
title: label,
text: text
});
};
var node = el('section', { class: 'comments', 'data-comments': '', 'aria-label': 'Kommentare' }, [
el('p', { class: 'comments__counter', 'data-comment-counter': '' }),
el('blockquote', { class: 'comments__text', 'data-comment-text': '' }),
el('p', { class: 'comments__value', 'data-comment-value': '' }),
items.length < 2 ? null : el('div', { class: 'comments__nav' }, [
button('prev', 'Vorheriger Kommentar', '‹'),
button('toggle', '', ''),
button('next', 'Nächster Kommentar', '›')
])
]);
node.addEventListener('click', function (event) {
var target = event.target.closest('[data-comment-action]');
if (!target) {
return;
}
var action = target.getAttribute('data-comment-action');
if (action === 'toggle') {
Comments.paused = !Comments.paused;
} else {
Comments.step(action === 'next' ? 1 : -1);
Comments.restart();
}
Comments.update(false);
});
Comments.node = node;
Comments.update(false);
if (!Comments.timer) {
Comments.restart();
}
return node;
},
step: function (delta) {
var n = Comments.items.length;
Comments.index = (Comments.index + delta + n) % n;
},
restart: function () {
clearInterval(Comments.timer);
Comments.timer = setInterval(function () {
if (!Comments.node || !document.body.contains(Comments.node)) {
// Slide changed: stop until the next comment list is rendered.
clearInterval(Comments.timer);
Comments.timer = null;
return;
}
if (Comments.paused || Comments.items.length < 2 || document.hidden) {
return;
}
Comments.step(1);
Comments.update(true);
}, Comments.intervalMs);
},
update: function (animate) {
var node = Comments.node;
var item = Comments.items[Comments.index];
var text = node.querySelector('[data-comment-text]');
node.querySelector('[data-comment-counter]').textContent =
'Kommentar ' + (Comments.index + 1) + ' von ' + Comments.items.length;
text.textContent = item.text;
var value = node.querySelector('[data-comment-value]');
value.textContent = item.value === null || item.value === undefined ? '' : 'Bewertung: ' + item.value;
value.hidden = value.textContent === '';
// Only announce changes the viewer triggered, not every automatic rotation.
node.setAttribute('aria-live', Comments.paused ? 'polite' : 'off');
text.classList.remove('is-entering');
if (animate) {
void text.offsetWidth; // restart the CSS animation
text.classList.add('is-entering');
}
var toggle = node.querySelector('[data-comment-action="toggle"]');
if (toggle) {
var label = Comments.paused ? 'Kommentare automatisch weiterblättern' : 'Automatisches Weiterblättern anhalten';
toggle.textContent = Comments.paused ? '▶' : '❚❚';
toggle.setAttribute('aria-label', label);
toggle.setAttribute('title', label);
toggle.setAttribute('aria-pressed', Comments.paused ? 'true' : 'false');
}
}
};
// ------------------------------------------------------------------ results
var Results = {
/**
* @param {Object} [options] renderer specific; wordcloud: {mine: [keys], onUpvote: fn(word)|null}
*/
render: function (container, results, options) {
// Keep keyboard focus on controls inside the results (e.g. comment buttons) across re-renders.
var active = document.activeElement;
var focusKey = active && container.contains(active) ? active.getAttribute('data-comment-action') : null;
container.innerHTML = '';
if (!results) {
return;
}
var renderer = Results[results.type];
if (typeof renderer !== 'function') {
return;
}
// A quiz shows its answer options even before anyone has answered.
// A Q&A slide always shows its stages.
// An ordering slide shows its items before and the solution after the reveal.
if (results.participants === 0 && results.type !== 'qa' && results.type !== 'order'
&& !(results.type === 'quiz' && !results.revealed)) {
container.appendChild(el('p', { class: 'results-empty', text: 'Noch keine Antworten' }));
return;
}
container.appendChild(renderer(results, options || {}));
var refocus = focusKey && container.querySelector('[data-comment-action="' + focusKey + '"]');
if (refocus) {
refocus.focus();
}
},
choice: function (results) {
var max = Math.max.apply(null, results.options.map(function (o) { return o.count; }).concat([1]));
return el('div', { class: 'bars' }, results.options.map(function (option, index) {
return el('div', { class: 'bar bar--c' + (index % 6) }, [
el('div', { class: 'bar__label', text: option.label }),
el('div', { class: 'bar__track' }, [
el('div', { class: 'bar__fill', style: 'width:' + (option.count / max * 100) + '%' })
]),
el('div', { class: 'bar__value', text: formatNumber(option.percent) + ' % (' + option.count + ')' })
]);
}));
},
/**
* Placeholder for a private slide (anonymous/internal feedback) while its results
* are hidden on stage: only the count, the presenter can show the rest with H.
*/
privateSummary: function (results) {
var n = results.participants;
var noun = results.type === 'scale'
? (n === 1 ? 'Bewertung' : 'Bewertungen')
: (n === 1 ? 'anonyme Antwort' : 'anonyme Antworten');
return el('div', { class: 'private-summary' }, [
el('p', { class: 'private-summary__count', text: String(n) }),
el('p', { text: noun + ' eingegangen' }),
el('p', { class: 'private-summary__hint', text: results.type === 'scale'
? '🔒 Internes Feedback – Ergebnis verborgen.'
: '🔒 Anonymes Feedback – Antworten verborgen.' })
]);
},
scale: function (results) {
var max = Math.max.apply(null, results.buckets.map(function (b) { return b.count; }).concat([1]));
var total = results.buckets.reduce(function (sum, b) { return sum + b.count; }, 0);
var hasAverage = results.average !== null;
var nearest = hasAverage ? Math.round(results.average) : null;
var columns = el('div', { class: 'columns' }, results.buckets.map(function (bucket) {
return el('div', { class: 'column' + (bucket.value === nearest ? ' column--avg' : '') }, [
el('div', { class: 'column__count', text: String(bucket.count) }),
el('div', { class: 'column__track' }, [
el('div', { class: 'column__fill', style: 'height:' + (bucket.count / max * 100) + '%' })
]),
el('div', { class: 'column__label', text: String(bucket.value) })
]);
}));
var labels = el('div', { class: 'scale__labels' }, [
el('span', { text: results.minLabel || '' }),
el('span', { text: results.maxLabel || '' })
]);
var averageText = hasAverage
? Number(results.average).toLocaleString('de-DE', { minimumFractionDigits: 1, maximumFractionDigits: 1 })
: '–';
var span = results.max - results.min;
var position = hasAverage && span > 0 ? (results.average - results.min) / span * 100 : 50;
var gauge = el('div', {
class: 'average__gauge',
role: 'img',
'aria-label': 'Durchschnitt ' + averageText + ' auf einer Skala von ' + results.min + ' bis ' + results.max
}, [
el('div', { class: 'average__track' }, [
hasAverage ? el('div', { class: 'average__marker', style: 'left:' + position + '%' }) : null
]),
el('div', { class: 'average__ends' }, [
el('span', { text: String(results.min) }),
el('span', { text: String(results.max) })
])
]);
var average = el('div', { class: 'average' }, [
el('div', { class: 'average__figure' }, [
el('span', { class: 'average__label', text: 'Durchschnitt' }),
el('span', { class: 'average__value' }, [
el('strong', { text: averageText }),
el('span', { class: 'average__of', text: ' / ' + results.max })
]),
el('span', { class: 'average__count', text: total + (total === 1 ? ' Bewertung' : ' Bewertungen') })
]),
gauge
]);
var comments = results.comments && results.comments.length ? Comments.render(results.comments, results.commentInterval) : null;
return el('div', { class: 'scale-results' }, [average, columns, labels, comments]);
},
/**
* options: {mine: [keys], down: [keys], onUpvote: fn(word)|null, onDownvote: fn(word)|null}
* Counts are shown as "+up" and "−down" (down only when > 0 or clickable).
*/
wordcloud: function (results, options) {
var mine = (options && options.mine) || [];
var down = (options && options.down) || [];
var onUpvote = options && options.onUpvote;
var onDownvote = options && options.onDownvote;
// Interleave big and small words so the biggest ends up in the middle.
var words = results.words.slice();
var ordered = [];
words.forEach(function (word, index) {
if (index % 2 === 0) {
ordered.push(word);
} else {
ordered.unshift(word);
}
});
return el('div', { class: 'cloud' + (onUpvote ? ' cloud--interactive' : '') }, ordered.map(function (word, index) {
var size = 0.9 + word.weight * 2.6;
var isMine = mine.indexOf(word.key) >= 0;
var isDown = down.indexOf(word.key) >= 0;
var rated = isMine || isDown;
var downCount = word.down || 0;
var attrs = {
class: 'cloud__word cloud__word--c' + (index % 6) + (isMine ? ' is-mine' : '') + (isDown ? ' is-down' : ''),
style: 'font-size:' + size.toFixed(2) + 'em',
title: '+' + word.count + ' / −' + downCount
+ (isMine ? ' – von dir genannt' : (isDown ? ' – von dir abgelehnt' : ''))
};
if (!onUpvote) {
// Presenter (and participants without upvotes): show the counts next to the word.
return el('span', attrs, [
el('span', { text: word.text }),
el('span', { class: 'cloud__count cloud__count--up', text: '+' + word.count }),
downCount > 0 ? el('span', { class: 'cloud__count cloud__count--down', text: '−' + downCount }) : null
]);
}
var up = el('button', {
type: 'button',
class: 'cloud__vote cloud__vote--up',
'aria-pressed': isMine ? 'true' : 'false',
'aria-label': word.text + ', ' + word.count + ' Stimmen'
+ (isMine ? ', von dir genannt' : (isDown ? '' : ', unterstützen'))
}, [
el('span', { text: word.text }),
el('span', { class: 'cloud__count cloud__count--up', 'aria-hidden': 'true', text: (isMine ? '✓ ' : '+') + word.count })
]);
up.disabled = rated;
if (!rated) {
up.addEventListener('click', function () { onUpvote(word); });
}
var downEl = null;
if (onDownvote) {
downEl = el('button', {
type: 'button',
class: 'cloud__vote cloud__vote--down',
'aria-pressed': isDown ? 'true' : 'false',
'aria-label': word.text + ', ' + downCount + ' Ablehnungen'
+ (isDown ? ', von dir abgelehnt' : (isMine ? '' : ', ablehnen'))
}, [
el('span', { class: 'cloud__count cloud__count--down', 'aria-hidden': 'true', text: (isDown ? '✓ ' : '') + '−' + downCount })
]);
downEl.disabled = rated;
if (!rated) {
downEl.addEventListener('click', function () { onDownvote(word); });
}
} else if (downCount > 0) {
downEl = el('span', { class: 'cloud__count cloud__count--down', text: '−' + downCount });
}
return el('span', attrs, [up, downEl]);
}));
},
/**
* Before the end only the answer options (and the timer) are shown;
* counts and correct answers arrive with `revealed` (see ResultsService).
* options: {answerId: id of the participant's own answer|null}
*/
quiz: function (results, options) {
var answerId = options && options.answerId;
if (!results.revealed) {
var children = [];
if (results.phase === 'running' && results.remaining !== null) {
children.push(el('p', {
class: 'quiz-timer',
role: 'timer',
'data-countdown': '',
'data-remaining': String(results.remaining)
}, [el('strong', { 'data-countdown-value': '', text: formatSeconds(results.remaining) })]));
} else if (results.phase === 'running') {
children.push(el('p', { class: 'quiz-status', text: 'Quiz läuft – ohne Zeitlimit' }));
} else {
children.push(el('p', { class: 'quiz-status', text: 'Bereit – starte das Quiz, um die Antworten freizugeben' }));
}
children.push(el('ol', { class: 'quiz-grid' }, results.options.map(function (option, index) {
return el('li', { class: 'quiz-tile quiz-tile--c' + (index % 6), text: option.label });
})));
return el('div', { class: 'quiz-results quiz-results--' + results.phase }, children);
}
if (results.correctCount === undefined) {
// Participant device: the solution only, the distribution is for the stage.
return el('ul', { class: 'quiz-solution' }, results.options.map(function (option) {
var mine = answerId !== null && answerId !== undefined && option.id === answerId;
return el('li', {
class: 'quiz-solution__item ' + (option.correct ? 'is-correct' : 'is-wrong') + (mine ? ' is-mine' : '')
}, [
el('span', { 'aria-hidden': 'true', text: option.correct ? '✓ ' : '✗ ' }),
document.createTextNode(option.label),
el('span', { class: 'sr-only', text: option.correct ? ' – richtig' : ' – falsch' }),
mine ? el('span', { class: 'quiz-solution__mine', text: ' (deine Antwort)' }) : null
]);
}));
}
var max = Math.max.apply(null, results.options.map(function (o) { return o.count; }).concat([1]));
var percent = results.participants > 0 ? Math.round(results.correctCount / results.participants * 100) : 0;
var summary = el('p', { class: 'quiz-summary' }, [
el('strong', { text: results.correctCount + ' von ' + results.participants }),
el('span', { text: ' richtig (' + percent + ' %)' })
]);
var bars = el('div', { class: 'bars' }, results.options.map(function (option) {
var mine = answerId !== null && answerId !== undefined && option.id === answerId;
var label = (option.correct ? '✓ ' : '') + option.label + (mine ? ' (deine Antwort)' : '');
return el('div', { class: 'bar ' + (option.correct ? 'bar--correct' : 'bar--wrong') + (mine ? ' is-mine' : '') }, [
el('div', { class: 'bar__label', text: label }),
el('div', { class: 'bar__track' }, [
el('div', { class: 'bar__fill', style: 'width:' + (option.count / max * 100) + '%' })
]),
el('div', { class: 'bar__value', text: formatNumber(option.percent) + ' % (' + option.count + ')' })
]);
}));
return el('div', { class: 'quiz-results quiz-results--finished' }, [summary, bars]);
},
/**
* Ordering slide. Before the reveal only the items in a shuffled order;
* afterwards the correct order with how often each item was placed right.
* options: {order: participant state {answer: [ids]|null}} marks own placements.
*/
order: function (results, options) {
var answer = options && options.order ? options.order.answer : null;
if (!results.revealed) {
return el('div', { class: 'order-results' }, [
el('p', { class: 'quiz-status', text: 'Die Teilnehmenden sortieren – aufgelöst wird beim Schließen der Abstimmung' }),
el('ul', { class: 'quiz-grid' }, results.items.map(function (item, index) {
return el('li', { class: 'quiz-tile quiz-tile--c' + (index % 6), text: item.label });
}))
]);
}
var children = [];
// Participant device (no correctCount): only the solution with the own placements,
// the verdict above it is part of the page.
var onStage = results.correctCount !== undefined;
var withCounts = onStage && results.participants > 0;
if (withCounts) {
var percent = Math.round(results.correctCount / results.participants * 100);
children.push(el('p', { class: 'quiz-summary' }, [
el('strong', { text: results.correctCount + ' von ' + results.participants }),
el('span', { text: ' komplett richtig (' + percent + ' %)' })
]));
} else if (onStage) {
children.push(el('p', { class: 'results-empty', text: 'Keine Antworten – so wäre es richtig gewesen:' }));
}
children.push(el('ol', { class: 'order-solution' }, results.items.map(function (item, index) {
var mine = answer ? answer[index] === item.id : null;
var label = item.label + (mine === true ? ' ✓' : (mine === false ? ' ✗' : ''));
return el('li', { class: 'bar order-solution__item' + (mine === true ? ' is-mine' : '') }, [
el('div', { class: 'bar__label' }, [
el('span', { class: 'order-solution__pos', text: item.position + '.' }),
document.createTextNode(' ' + label),
mine === null ? null : el('span', {
class: 'sr-only',
text: mine ? ' – von dir richtig platziert' : ' – von dir an anderer Stelle'
})
]),
withCounts ? el('div', { class: 'bar__track' }, [
el('div', { class: 'bar__fill', style: 'width:' + item.percent + '%' })
]) : null,
withCounts ? el('div', {
class: 'bar__value',
text: formatNumber(item.percent) + ' % an dieser Stelle (' + item.placed + ')'
}) : null
]);
})));
return el('div', { class: 'order-results order-results--revealed' }, children);
},
open: function (results) {
return el('ul', { class: 'answers' }, results.answers.map(function (answer) {
return el('li', { class: 'answer', text: answer.text });
}));
},
/**
* Presenter view of a Q&A slide: stage stepper, then per stage the
* collected questions, the live ranking or the question being discussed.
* options: {onStage: fn(stage)|null, onQuestion: fn(step)|null}
*/
qa: function (results, options) {
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;
function votes(question) {
if (!withVotes) {
return null;
}
return el('span', {
class: 'qa-votes',
'aria-label': question.votes + (question.votes === 1 ? ' Stimme' : ' Stimmen'),
text: '▲ ' + question.votes
});
}
if (results.stage === 'collect') {
children.push(el('p', { class: 'qa-summary', text: questions.length === 0
? 'Noch keine Fragen – jetzt mitmachen und Fragen einreichen!'
: questions.length + (questions.length === 1 ? ' Frage eingereicht' : ' Fragen eingereicht') }));
children.push(el('ul', { class: 'answers' }, questions.slice().reverse().map(function (question) {
return el('li', { class: 'answer', text: question.text });
})));
} else if (results.stage === 'vote') {
children.push(el('p', { class: 'qa-summary', text: 'Abstimmen: jede Person hat '
+ 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) {
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) + '%' })
]);
})));
} else if (questions.length === 0) {
children.push(el('p', { class: 'qa-summary', text: 'Es wurden keine Fragen eingereicht.' }));
} else {
var index = results.focusIndex === null ? 0 : results.focusIndex;
var focus = questions[index];
var nav = function (step, label, symbol, disabled) {
if (!onQuestion) {
return null;
}
var button = el('button', { type: 'button', class: 'ctrl', title: label }, [
el('span', { 'aria-hidden': 'true', text: symbol }),
el('span', { class: 'sr-only', text: label })
]);
button.disabled = disabled;
button.addEventListener('click', function () { onQuestion(step); });
return button;
};
children.push(el('div', { class: 'qa-focus', 'aria-live': 'polite' }, [
el('p', { class: 'qa-focus__meta' }, [
el('span', { text: 'Frage ' + (index + 1) + ' von ' + questions.length }),
votes(focus)
]),
el('p', { class: 'qa-focus__text', text: focus.text }),
el('div', { class: 'qa-focus__nav' }, [
nav(-1, 'Vorherige Frage', '←', index === 0),
nav(1, 'Nächste Frage', '→', index === questions.length - 1)
])
]));
children.push(el('ol', { class: 'qa-list qa-list--compact' }, questions.map(function (question, i) {
var attrs = { class: 'qa-item' + (i < index ? ' is-done' : '') + (i === index ? ' is-current' : '') };
if (i === index) {
attrs['aria-current'] = 'true';
}
return el('li', attrs, [
el('span', { class: 'qa-item__text', text: (i < index ? '✓ ' : '') + question.text }),
votes(question)
]);
})));
}
return el('div', { class: 'qa-results qa-results--' + results.stage }, children);
}
};
// ------------------------------------------------------------------ Q&A
var Qa = {
labels: { collect: 'Fragen sammeln', vote: 'Abstimmen', discuss: 'Besprechen' },
/** Stepper of the stages (without upvotes there is no voting stage); clickable for the presenter (onStage). */
steps: function (stage, onStage, stages) {
return el('ol', { class: 'qa-steps', 'aria-label': 'Ablauf' }, (stages || ['collect', 'vote', 'discuss']).map(function (key, i) {
var current = key === stage;
var label = (i + 1) + ' ' + Qa.labels[key];
var item = onStage
? el('button', { type: 'button', class: 'qa-steps__step', text: label })
: el('span', { class: 'qa-steps__step', text: label });
if (current) {
item.setAttribute('aria-current', 'step');
}
if (onStage) {
item.disabled = current;
item.addEventListener('click', function () { onStage(key); });
}
return el('li', { class: current ? 'is-current' : '' }, [item]);
}));
}
};
// ------------------------------------------------------------------ copy
/** Copies the value of the [data-copy-source] next to `button` and confirms on the button. */
function copyFrom(button) {
var source = button.parentNode.querySelector('[data-copy-source]');
if (!source) {
return;
}
source.select();
var done = function () {
var label = button.textContent;
button.textContent = 'Kopiert ✓';
setTimeout(function () { button.textContent = label; }, 1500);
};
if (navigator.clipboard) {
navigator.clipboard.writeText(source.value).then(done, function () {
document.execCommand('copy');
done();
});
} else {
document.execCommand('copy');
done();
}
}
function initCopy() {
document.querySelectorAll('[data-copy]').forEach(function (button) {
button.addEventListener('click', function () { copyFrom(button); });
});
}
// ------------------------------------------------------------------ share
/**
* [data-share]: native share sheet (smartphones) with data-share-url / data-share-title,
* otherwise copies the sibling [data-copy-source]. Hidden without JS.
*/
function initShare() {
document.querySelectorAll('[data-share]').forEach(function (button) {
var canShare = typeof navigator.share === 'function';
button.textContent = button.getAttribute(canShare ? 'data-label-share' : 'data-label-copy');
button.hidden = false;
button.addEventListener('click', function () {
if (!canShare) {
copyFrom(button);
return;
}
navigator.share({
title: button.getAttribute('data-share-title') || document.title,
url: button.getAttribute('data-share-url')
}).catch(function (error) {
if (!error || error.name !== 'AbortError') {
copyFrom(button);
}
});
});
});
}
// ------------------------------------------------------------------ youtube
function youtubeFrame(src, title) {
// The admin pages send no referrer at all; YouTube refuses to play without one.
// strict-origin sends only the origin, never the path with the admin token.
return el('iframe', {
src: src,
title: title,
referrerpolicy: 'strict-origin',
allow: 'autoplay; encrypted-media; picture-in-picture; fullscreen',
allowfullscreen: ''
});
}
/** [data-youtube-form]: "Link prüfen" in the slide form, shows status + preview. */
function initYouTubeForm(root) {
var url = root.getAttribute('data-youtube-form');
var input = root.querySelector('[data-youtube-url]');
var start = root.querySelector('[data-youtube-start]');
var startHint = root.querySelector('[data-youtube-start-hint]');
var button = root.querySelector('[data-youtube-check]');
var status = root.querySelector('[data-youtube-status]');
var preview = root.querySelector('[data-youtube-preview]');
var title = document.querySelector('[data-youtube-title]');
var lastChecked = null;
function show(text, kind) {
status.textContent = text;
status.classList.toggle('is-ok', kind === 'ok');
status.classList.toggle('is-error', kind === 'error');
}
function check() {
var value = input.value.trim();
if (value === '') {
show('Bitte gib einen YouTube-Link ein.', 'error');
input.focus();
return;
}
var key = value + '|' + start.value.trim();
if (key === lastChecked) {
return;
}
lastChecked = key;
button.disabled = true;
show('Link wird geprüft …');
postJson(url, { url: value, start: start.value }).then(function (result) {
var text = result.message;
if (result.ok && result.linkStart && start.value.trim() === '') {
text += ' Start bei ' + result.linkStart + ' (aus dem Link).';
}
show((result.ok ? '✓ ' : '') + text, result.ok ? 'ok' : 'error');
input.setAttribute('aria-invalid', result.ok ? 'false' : 'true');
preview.textContent = '';
preview.hidden = !result.embedUrl;
if (result.embedUrl) {
preview.appendChild(youtubeFrame(result.embedUrl, 'Vorschau des Videos'));
}
if (result.ok && result.title && title && title.value.trim() === '') {
title.value = result.title;
}
if (result.ok) {
start.placeholder = result.linkStart || '0:00';
if (startHint && result.linkStart) {
startHint.textContent = 'Leer lassen, um beim Zeitpunkt aus dem Link (' + result.linkStart + ') zu starten.';
}
}
}).catch(function () {
lastChecked = null;
show('Die Prüfung hat gerade nicht geklappt. Beim Speichern wird der Link erneut geprüft.', 'error');
}).then(function () {
button.disabled = false;
});
}
button.hidden = false;
button.addEventListener('click', check);
input.addEventListener('change', check);
input.addEventListener('paste', function () { setTimeout(check, 0); });
start.addEventListener('change', function () {
if (input.value.trim() !== '') {
check();
}
});
}
// ------------------------------------------------------------------ presenter
function initPresenter(root) {
var stateUrl = root.getAttribute('data-state-url');
var controlUrl = root.getAttribute('data-control-url');
var interval = parseInt(root.getAttribute('data-interval'), 10) || 2000;
var q = function (selector) { return root.querySelector(selector); };
var embedded = root.hasAttribute('data-embed');
var setText = function (selector, text) {
var node = q(selector);
if (node) {
node.textContent = text;
}
};
var last = '';
// hideAll: the presenter's choice for normal slides (kept across slides).
// hideResults: what applies to the current slide - private slides start hidden.
var hideAll = false;
var hideResults = false;
var hideSlideId = null;
var state = null;
var mediaKey = '';
/** Embeds the video of a YouTube slide; kept as is while the slide stays (no restart on polls). */
function renderMedia(slide) {
var media = q('[data-media]');
var video = slide && slide.video ? slide.video : null;
var key = video ? slide.id + '|' + video.embedUrl : '';
if (key === mediaKey) {
return;
}
mediaKey = key;
media.textContent = '';
media.hidden = !video;
if (video) {
media.appendChild(youtubeFrame(video.embedUrl, slide.question));
}
}
function render(newState) {
var serialized = JSON.stringify(newState);
if (serialized === last) {
return;
}
last = serialized;
state = newState;
var slide = state.slide;
setText('[data-counter]', state.count === 0
? '0 / 0'
: (state.index === null ? (state.poll.isPaused ? '⏸' : '–') : state.index + 1) + ' / ' + state.count);
var pauseButton = q('[data-pause]');
if (pauseButton) {
var paused = !slide && !!state.poll.isPaused;
pauseButton.hidden = !slide && !paused;
pauseButton.setAttribute('data-action', paused ? 'resume' : 'stop');
pauseButton.setAttribute('aria-pressed', paused ? 'true' : 'false');
pauseButton.title = pauseButton.getAttribute(paused ? 'data-title-resume' : 'data-title-pause') || '';
pauseButton.querySelector('[data-pause-icon]').textContent = paused ? '▶' : '⏸';
pauseButton.querySelector('[data-pause-label]').textContent = paused ? 'Fortsetzen' : 'Pause';
}
if (embedded) {
renderLive();
}
if (!slide) {
q('[data-type]').textContent = state.poll.isPaused ? 'Pause' : '';
q('[data-question]').textContent = state.count === 0
? 'Noch keine Folien angelegt'
: state.poll.title;
q('[data-description]').textContent = state.count === 0
? '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.');
q('[data-results]').innerHTML = '';
renderMedia(null);
root.classList.remove('stage--video');
q('[data-voting]').hidden = true;
setText('[data-participants]', '');
return;
}
var quizPhase = slide.type === 'quiz' && state.results ? state.results.phase : null;
var qaStage = slide.type === 'qa' && state.results ? state.results.stage : null;
var orderRevealed = slide.type === 'order' && state.results ? state.results.revealed : null;
q('[data-type]').textContent = quizPhase
? slide.typeLabel + ' · ' + { ready: 'bereit', running: 'läuft', finished: 'Auflösung' }[quizPhase]
: (qaStage ? slide.typeLabel + ' · ' + Qa.labels[qaStage]
: (orderRevealed ? slide.typeLabel + ' · Auflösung' : slide.typeLabel));
q('[data-question]').textContent = slide.question;
q('[data-description]').textContent = slide.description;
root.classList.toggle('stage--content', !slide.isInteractive);
root.classList.toggle('stage--video', slide.type === 'youtube');
renderMedia(slide);
root.classList.toggle('stage--closed', slide.isInteractive && !slide.isVotingOpen && !quizPhase && !qaStage && !orderRevealed);
root.classList.toggle('stage--qa', !!qaStage);
var voting = q('[data-voting]');
// Q&A: V switches to the next stage, there is none after "discuss".
voting.hidden = !slide.isInteractive || qaStage === 'discuss';
voting.querySelector('[data-label]').textContent = quizPhase
? { ready: 'Quiz starten', running: 'Quiz beenden', finished: 'Quiz erneut öffnen' }[quizPhase]
: (qaStage
? { collect: 'Einreichen beenden', vote: 'Abstimmung beenden', discuss: '' }[qaStage]
: (slide.type === 'order'
? (slide.isVotingOpen ? 'Schließen & auflösen' : 'Abstimmung wieder öffnen')
: (slide.isVotingOpen ? 'Abstimmung schließen' : 'Abstimmung öffnen')));
var count = qaStage ? state.results.questions.length : (slide.isInteractive ? state.results.participants : 0);
setText('[data-participants]', !slide.isInteractive ? '' : (qaStage
? count + (count === 1 ? ' Frage' : ' Fragen')
: count + ' ' + (count === 1 ? 'Antwort' : 'Antworten')));
if (slide.id !== hideSlideId) {
hideSlideId = slide.id;
hideResults = isPrivate() || hideAll;
hideLabel();
}
renderResults();
Countdown.start();
}
function isPrivate() {
return !!(state && state.slide && state.slide.isInteractive && state.results && state.results.private);
}
function renderResults() {
var container = q('[data-results]');
var slide = state.slide;
// Hidden private slides show how many answered instead of an empty stage.
var summary = hideResults && isPrivate();
container.classList.toggle('is-hidden', hideResults && !summary);
if (summary) {
container.textContent = '';
container.appendChild(Results.privateSummary(state.results));
return;
}
Results.render(container, slide && slide.isInteractive ? state.results : null, {
onStage: function (stage) { control('stage', { stage: stage }); },
onQuestion: function (step) { control('question', { step: step }); }
});
}
function hideLabel() {
setText('[data-hide-results] [data-label]', hideResults ? 'Ergebnisse zeigen' : 'Ergebnisse verbergen');
}
function refresh() {
return getJson(stateUrl).then(render);
}
function control(action, extra) {
var data = Object.assign({ action: action }, extra || {});
return postJson(controlUrl, data).then(render).catch(function () { /* next poll fixes it */ });
}
root.querySelectorAll('[data-action]').forEach(function (button) {
button.addEventListener('click', function () {
control(button.getAttribute('data-action'));
});
});
function toggleHide() {
hideResults = !hideResults;
// Showing a private slide is a decision for this slide only.
if (!isPrivate()) {
hideAll = hideResults;
}
hideLabel();
if (state) {
renderResults();
}
}
q('[data-hide-results]').addEventListener('click', toggleHide);
/*
* Embed mode: the slide goes live while the embed is really on screen (tab visible and
* at least half of it in the viewport - IntersectionObserver also sees through the
* iframes of the surrounding presentation), stays live with heartbeats, pauses when gone.
*/
var live = false;
function renderLive() {
var isLive = !!state.isLive;
var indicator = q('[data-live]');
indicator.textContent = !state.poll.isActive
? 'Umfrage geschlossen'
: (isLive ? '● live' : 'nicht live');
indicator.classList.toggle('is-live', isLive);
q('[data-go-live]').hidden = isLive || !state.poll.isActive;
}
function goLive() {
live = true;
postJson(root.getAttribute('data-activate-url'), {}).then(render).catch(function () {});
}
function leave() {
if (!live) {
return;
}
live = false;
var url = root.getAttribute('data-pause-url');
// sendBeacon survives page unload; embed routes need no CSRF token.
if (!(navigator.sendBeacon && navigator.sendBeacon(url, new FormData()))) {
postJson(url, {}).catch(function () {});
}
}
if (embedded) {
var inView = false;
var check = function () {
if (inView && document.visibilityState === 'visible') {
if (!live) {
goLive();
}
} else {
leave();
}
};
if ('IntersectionObserver' in window) {
new IntersectionObserver(function (entries) {
inView = entries[entries.length - 1].intersectionRatio >= 0.5;
check();
}, { threshold: [0, 0.5, 1] }).observe(root);
} else {
inView = true;
check();
}
document.addEventListener('visibilitychange', check);
window.addEventListener('pagehide', leave);
q('[data-go-live]').addEventListener('click', goLive);
setInterval(function () {
if (live) {
postJson(root.getAttribute('data-heartbeat-url'), {}).then(render).catch(function () {});
}
}, parseInt(root.getAttribute('data-heartbeat'), 10) || 5000);
}
function toggleFullscreen() {
if (!document.fullscreenElement) {
(document.documentElement.requestFullscreen || function () {}).call(document.documentElement);
} else if (document.exitFullscreen) {
document.exitFullscreen();
}
}
if (q('[data-fullscreen]')) {
q('[data-fullscreen]').addEventListener('click', toggleFullscreen);
}
var overlay = q('[data-qr-overlay]');
function toggleQr() {
if (overlay) {
overlay.hidden = !overlay.hidden;
}
}
if (overlay) {
q('[data-qr-toggle]').addEventListener('click', toggleQr);
overlay.addEventListener('click', toggleQr);
}
document.addEventListener('keydown', function (event) {
if (event.target.closest('input, textarea, select')) {
return;
}
if ((event.key === ' ' || event.key === 'Enter') && event.target.closest('[data-comments]')) {
return; // activates the focused comment button, not the next slide
}
if (embedded && ['ArrowRight', 'ArrowLeft', 'PageUp', 'PageDown', ' ', 'p', 'P', 'f', 'F', 'q', 'Q'].indexOf(event.key) >= 0) {
return; // slide navigation belongs to the surrounding presentation
}
switch (event.key) {
case 'p':
case 'P':
control(state && !state.slide && state.poll.isPaused ? 'resume' : 'stop');
break;
case 'ArrowRight':
case 'PageDown':
case ' ':
event.preventDefault();
control('next');
break;
case 'ArrowLeft':
case 'PageUp':
event.preventDefault();
control('prev');
break;
case 'v':
case 'V':
if (state && state.slide && state.slide.isInteractive) {
control('toggle');
}
break;
case 'h':
case 'H':
toggleHide();
break;
case 'f':
case 'F':
toggleFullscreen();
break;
case 'q':
case 'Q':
toggleQr();
break;
case 't':
case 'T':
if (themeSwitch) {
themeSwitch.click();
}
break;
case 'Escape':
if (overlay) {
overlay.hidden = true;
}
break;
}
});
var themeSwitch = q('[data-theme-switch]');
var poller = poll(refresh, interval);
document.addEventListener('plenario:timeup', function () {
// The server closes the quiz once the deadline has passed.
setTimeout(poller.now, 300);
});
}
// ------------------------------------------------------------------ participant
function initParticipant(root) {
var stateUrl = root.getAttribute('data-state-url');
var voteUrl = root.getAttribute('data-vote-url');
var version = root.getAttribute('data-version');
var interval = parseInt(root.getAttribute('data-interval'), 10) || 2000;
var card = root.querySelector('[data-results-card]');
var container = root.querySelector('[data-results]');
var wordForm = root.querySelector('[data-word-form]');
var current = null;
var lastRendered = '';
function canUpvote(state) {
return !!(wordForm && state.words && state.words.allowUpvotes
&& state.isVotingOpen);
}
// --- Q&A: submit questions, upvote, follow the discussion ----------
var qaRoot = root.querySelector('[data-qa]');
var qaList = qaRoot ? qaRoot.querySelector('[data-qa-list]') : null;
var qaMessage = qaRoot ? qaRoot.querySelector('[data-qa-message]') : null;
var qaForm = qaRoot ? qaRoot.querySelector('[data-qa-form]') : null;
var qaRendered = '';
var qaSending = false;
function qaSay(text, isError) {
qaMessage.textContent = text;
qaMessage.classList.toggle('is-error', !!isError);
}
function sendQa(data) {
if (qaSending) {
return Promise.resolve(null);
}
qaSending = true;
data.slide_id = root.querySelector('[name=slide_id]').value;
return postJson(voteUrl, data).then(function (response) {
qaSay(response.message, !response.ok);
if (response.state.version !== version) {
window.location.reload();
return null;
}
renderQa(response.state);
return response;
}).catch(function () {
qaSay('Das hat nicht geklappt. Bitte versuche es noch einmal.', true);
return null;
}).then(function (response) {
qaSending = false;
return response;
});
}
function renderQa(state) {
var qa = state.qa;
if (!qaList || !qa) {
return;
}
var key = JSON.stringify(qa);
if (key === qaRendered) {
return;
}
qaRendered = key;
// Keep keyboard focus on the same question after re-rendering.
var focused = document.activeElement && document.activeElement.getAttribute('data-question-id');
qaList.textContent = '';
if (qa.stage === 'collect') {
// All questions so far, so participants can spot duplicates before asking.
qaList.appendChild(el('h2', { class: 'qa-heading', text: 'Bereits gestellte Fragen (' + qa.questions.length + ')' }));
if (!qa.questions.length) {
qaList.appendChild(el('p', { class: 'results-empty', text: 'Noch keine – stell gern die erste Frage!' }));
return;
}
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' : '') }, [
el('span', { class: 'qa-item__text', text: question.text }),
mine ? el('span', { class: 'qa-own', text: 'deine Frage' }) : null
]);
})));
return;
}
if (qa.stage === 'vote') {
var used = qa.maxUpvotes - qa.votesLeft;
qaList.appendChild(el('p', { class: 'qa-budget', 'aria-live': 'polite' }, [
el('strong', { text: String(qa.votesLeft) }),
el('span', { text: ' von ' + qa.maxUpvotes + (qa.maxUpvotes === 1 ? ' Stimme' : ' Stimmen') + ' übrig' })
].concat(Array.apply(null, Array(qa.maxUpvotes)).map(function (_, i) {
return el('span', { class: 'qa-budget__dot' + (i < used ? ' is-used' : ''), 'aria-hidden': 'true' });
}))));
if (!qa.questions.length) {
qaList.appendChild(el('p', { class: 'results-empty', text: 'Es wurden keine Fragen eingereicht.' }));
return;
}
if (qa.mine.length && !qa.allowSelfUpvote) {
qaList.appendChild(el('p', { class: 'hint', text: 'Deine eigenen Fragen kannst du nicht unterstützen – verteile deine Stimmen auf die Fragen der anderen.' }));
}
qaList.appendChild(el('ul', { class: 'qa-list' }, qa.questions.map(function (question) {
var mine = qa.mine.indexOf(question.id) >= 0;
// Own upvotes on this question – several are allowed to push important questions.
var given = (qa.upvoted || {})[question.id] || 0;
var action;
if (mine && !qa.allowSelfUpvote) {
action = el('span', { class: 'qa-own', text: 'deine Frage' });
} else {
var button = function (vote, symbol, label, disabled) {
var b = el('button', {
type: 'button',
class: 'qa-upvote qa-upvote--' + vote,
'aria-label': label + ': ' + question.text,
'data-question-id': question.id + '-' + vote
}, [el('span', { 'aria-hidden': 'true', text: symbol })]);
b.disabled = disabled;
b.addEventListener('click', function () {
sendQa({ vote: vote, question_id: question.id });
});
return b;
};
action = el('span', { class: 'qa-stepper' + (given > 0 ? ' is-active' : '') }, [
button('remove', '−', 'Stimme zurücknehmen', given === 0),
el('span', {
class: 'qa-stepper__count',
'aria-label': given === 0 ? 'keine Stimme von dir' : given + (given === 1 ? ' Stimme' : ' Stimmen') + ' von dir',
text: '▲ ' + given
}),
button('up', '+', 'Stimme geben', qa.votesLeft === 0 || given >= qa.maxPerQuestion)
]);
}
return el('li', { class: 'qa-item' + (mine ? ' is-mine' : '') + (given > 0 ? ' is-upvoted' : '') }, [
el('span', { class: 'qa-item__text', text: question.text + (mine && qa.allowSelfUpvote ? ' (deine Frage)' : '') }),
action
]);
})));
} else {
if (!qa.questions.length) {
qaList.appendChild(el('p', { class: 'results-empty', text: 'Es wurden keine Fragen eingereicht.' }));
return;
}
var index = -1;
qa.questions.forEach(function (question, i) {
if (question.id === qa.focusId) {
index = i;
}
});
if (index >= 0) {
qaList.appendChild(el('div', { class: 'qa-focus', 'aria-live': 'polite' }, [
el('p', { class: 'qa-focus__meta', text: 'Wird gerade besprochen · Frage ' + (index + 1) + ' von ' + qa.questions.length }),
el('p', { class: 'qa-focus__text', text: qa.questions[index].text })
]));
}
qaList.appendChild(el('ol', { class: 'qa-list qa-list--compact' }, qa.questions.map(function (question, i) {
var mine = qa.mine.indexOf(question.id) >= 0;
var attrs = { class: 'qa-item' + (i < index ? ' is-done' : '') + (i === index ? ' is-current' : '') + (mine ? ' is-mine' : '') };
if (i === index) {
attrs['aria-current'] = 'true';
}
return el('li', attrs, [
el('span', { class: 'qa-item__text', text: (i < index ? '✓ ' : '') + question.text + (mine ? ' (deine Frage)' : '') }),
qa.maxUpvotes > 0
? el('span', { class: 'qa-votes', 'aria-label': question.votes + (question.votes === 1 ? ' Stimme' : ' Stimmen'), text: '▲ ' + question.votes })
: null
]);
})));
}
if (focused) {
var again = qaList.querySelector('[data-question-id="' + focused + '"]');
if (again && !again.disabled) {
again.focus();
}
}
}
if (qaForm) {
qaForm.addEventListener('submit', function (event) {
event.preventDefault();
var field = qaForm.querySelector('[name=question]');
var text = field.value.trim();
if (!text) {
return;
}
sendQa({ question: text }).then(function (response) {
if (response && response.ok) {
field.value = '';
}
});
});
}
function renderResults(state) {
current = state;
renderQa(state);
if (!card || !container) {
return;
}
var upvote = canUpvote(state);
var key = JSON.stringify([state.results, state.words, upvote]);
if (key === lastRendered) {
return;
}
lastRendered = key;
card.hidden = !state.results;
var hint = root.querySelector('[data-upvote-hint]');
if (hint) {
hint.hidden = !upvote;
}
Results.render(container, state.results, {
mine: state.words ? state.words.mine : [],
down: state.words ? state.words.down : [],
answerId: state.quiz ? state.quiz.answerId : null,
order: state.order,
onUpvote: upvote ? function (word) { sendWord(word.text); } : null,
onDownvote: upvote && state.words.allowDownvotes ? function (word) { sendWord(word.text, 'down'); } : null
});
}
// --- word cloud: one word per submit, suggestions, upvotes ----------
var input = wordForm ? wordForm.querySelector('[data-word-input]') : null;
var list = wordForm ? wordForm.querySelector('[data-suggestions]') : null;
var message = wordForm ? wordForm.querySelector('[data-word-message]') : null;
var matches = [];
var activeIndex = -1;
var sending = false;
function isMine(word) {
return !!(current && current.words && current.words.mine.indexOf(word.key) >= 0);
}
function isDown(word) {
return !!(current && current.words && current.words.down.indexOf(word.key) >= 0);
}
function sendWord(text, vote) {
if (!wordForm || sending) {
return;
}
sending = true;
var slideId = wordForm.querySelector('[name=slide_id]').value;
var data = { slide_id: slideId, word: text };
if (vote === 'down') {
data.vote = 'down';
}
postJson(voteUrl, data).then(function (response) {
var success = vote === 'down' ? '✓ „' + text + '“ abgelehnt.' : '✓ „' + text + '“ ist angekommen.';
message.textContent = response.ok ? success : response.message;
message.classList.toggle('is-error', !response.ok);
if (response.ok && vote !== 'down') {
input.value = '';
closeSuggestions();
}
applyWordState(response.state);
}).catch(function () {
message.textContent = 'Das hat nicht geklappt. Bitte versuche es noch einmal.';
message.classList.add('is-error');
}).then(function () {
sending = false;
});
}
function applyWordState(state) {
if (state.version !== version || !state.words) {
// Slide changed or voting closed.
window.location.reload();
return;
}
renderResults(state);
}
function closeSuggestions() {
matches = [];
activeIndex = -1;
list.hidden = true;
list.textContent = '';
input.setAttribute('aria-expanded', 'false');
input.removeAttribute('aria-activedescendant');
}
function highlight(index) {
var items = list.querySelectorAll('[role=option]');
activeIndex = items.length ? (index + items.length) % items.length : -1;
items.forEach(function (item, i) {
item.classList.toggle('is-active', i === activeIndex);
item.setAttribute('aria-selected', i === activeIndex ? 'true' : 'false');
});
if (activeIndex >= 0) {
input.setAttribute('aria-activedescendant', items[activeIndex].id);
items[activeIndex].scrollIntoView({ block: 'nearest' });
}
}
function pick(word) {
if (isMine(word) || isDown(word)) {
return;
}
input.value = word.text;
closeSuggestions();
sendWord(word.text);
}
function updateSuggestions() {
var words = current && current.results && current.results.words ? current.results.words : [];
var found = Words.suggest(input.value, words);
closeSuggestions();
if (!found.length) {
return;
}
matches = found;
found.forEach(function (word, i) {
var mine = isMine(word);
var rejected = isDown(word);
var item = el('li', {
id: 'word-suggestion-' + i,
role: 'option',
class: 'suggestion' + (mine || rejected ? ' is-mine' : ''),
'aria-selected': 'false',
'aria-disabled': mine || rejected ? 'true' : 'false'
}, [
el('span', { class: 'suggestion__text', text: word.text }),
el('span', {
class: 'suggestion__meta',
text: mine ? 'schon genannt' : (rejected ? 'von dir abgelehnt' : '+' + word.count + ' · unterstützen')
})
]);
item.addEventListener('mousedown', function (event) {
event.preventDefault(); // keep focus in the input
pick(word);
});
list.appendChild(item);
});
list.hidden = false;
input.setAttribute('aria-expanded', 'true');
}
if (wordForm && input && list) {
wordForm.addEventListener('submit', function (event) {
event.preventDefault();
var text = input.value.trim();
if (text) {
sendWord(text);
}
});
input.addEventListener('input', updateSuggestions);
input.addEventListener('blur', function () { setTimeout(closeSuggestions, 150); });
input.addEventListener('keydown', function (event) {
if (list.hidden) {
return;
}
if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
event.preventDefault();
highlight(activeIndex + (event.key === 'ArrowDown' ? 1 : -1));
} else if (event.key === 'Enter' && activeIndex >= 0) {
event.preventDefault();
pick(matches[activeIndex]);
} else if (event.key === 'Escape') {
closeSuggestions();
}
});
}
var initial = root.querySelector('[data-initial-state]');
if (initial) {
try {
renderResults(JSON.parse(initial.textContent));
} catch (e) { /* ignore */ }
}
var quizForm = root.querySelector('[data-quiz-form]');
document.addEventListener('plenario:timeup', function () {
if (quizForm) {
quizForm.querySelectorAll('input, button').forEach(function (input) { input.disabled = true; });
}
setTimeout(participantPoller.now, 300);
});
Countdown.start();
var participantPoller = poll(function () {
return getJson(stateUrl).then(function (state) {
if (state.version !== version) {
// Do not destroy what the participant is typing right now.
var typing = document.activeElement && document.activeElement.closest('.vote-form textarea, .vote-form input[type=text]');
if (typing && typing.value && state.isVotingOpen && String(state.slideId) === String(root.querySelector('[name=slide_id]').value)) {
return;
}
window.location.reload();
return;
}
renderResults(state);
});
}, interval);
}
// ------------------------------------------------------------------ slide form
/** Quiz slide form: add further answer rows (the server renders a few already). */
function initQuizOptions(fieldset) {
var list = fieldset.querySelector('[data-quiz-list]');
var button = fieldset.querySelector('[data-quiz-add]');
var max = parseInt(fieldset.getAttribute('data-max'), 10) || 10;
function rows() {
return list.querySelectorAll('[data-quiz-row]');
}
function update() {
button.hidden = rows().length >= max;
}
button.addEventListener('click', function () {
var index = rows().length;
if (index >= max) {
return;
}
var row = rows()[0].cloneNode(true);
var label = row.querySelector('label[for]');
var text = row.querySelector('input[type=text]');
var check = row.querySelector('input[type=checkbox]');
var id = 'quiz-option-' + index;
label.setAttribute('for', id);
label.textContent = 'Antwort ' + (index + 1);
text.id = id;
text.name = 'quiz_options[' + index + '][label]';
text.value = '';
text.placeholder = 'Antwort ' + (index + 1);
text.required = false;
check.name = 'quiz_options[' + index + '][correct]';
check.checked = false;
list.appendChild(row);
text.focus();
update();
});
update();
}
// ------------------------------------------------------------------ sortable lists
/**
* Reorderable list: drag by [data-drag-handle] (pointer events: mouse, touch, pen),
* arrow keys on a focused handle, and optional [data-move="up|down"] buttons.
* Only moves DOM nodes; options.onChange(item) runs after every completed move.
*
* @param {Element} list
* @param {{item: string, onChange: function(Element), draggingClass: string, sortingClass: string}} options
*/
function makeSortable(list, options) {
var drag = null;
function items() {
return Array.prototype.filter.call(list.children, function (node) {
return node.matches(options.item);
});
}
function move(item, up) {
var sibling = up ? item.previousElementSibling : item.nextElementSibling;
if (!sibling || !sibling.matches(options.item)) {
return false;
}
list.insertBefore(item, up ? sibling : sibling.nextElementSibling);
return true;
}
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(options.item);
if (move(item, event.key === 'ArrowUp')) {
handle.focus();
options.onChange(item);
}
});
list.addEventListener('click', function (event) {
var button = event.target.closest('[data-move]');
if (!button) {
return;
}
var item = button.closest(options.item);
if (move(item, button.getAttribute('data-move') === 'up')) {
button.focus();
options.onChange(item);
}
});
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 = items().indexOf(item) !== drag.index;
item.style.transform = '';
item.classList.remove(options.draggingClass);
list.classList.remove(options.sortingClass);
drag = null;
if (changed) {
options.onChange(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(options.item);
handle.setPointerCapture(event.pointerId);
drag = {
item: item,
pointerId: event.pointerId,
grabOffset: event.clientY - item.getBoundingClientRect().top,
index: items().indexOf(item)
};
item.classList.add(options.draggingClass);
list.classList.add(options.sortingClass);
});
list.addEventListener('pointermove', onMove);
list.addEventListener('pointerup', onEnd);
list.addEventListener('pointercancel', onEnd);
return { items: items };
}
/** Updates the visible [data-position] numbers of sortable items. */
function renumber(items, suffix) {
items.forEach(function (item, index) {
var pos = item.querySelector('[data-position]');
if (pos) {
pos.textContent = String(index + 1) + (suffix || '');
}
var label = item.querySelector('[data-row-label]');
if (label) {
label.textContent = 'Platz ' + (index + 1);
}
});
}
/** Admin slide list: saves the new order right away (POST ids[] to [data-sortable]). */
function initSortable(list) {
var url = list.getAttribute('data-sortable');
var section = list.parentNode;
var status = section.querySelector('[data-sortable-status]');
var hint = section.querySelector('[data-sortable-hint]');
var error = null;
var saving = Promise.resolve();
function showError(message) {
if (!error) {
var reload = el('button', { type: 'button', class: 'button button--small', text: 'Seite neu laden' });
reload.addEventListener('click', function () { window.location.reload(); });
error = el('div', { class: 'notice', role: 'alert' }, [el('span'), document.createTextNode(' '), reload]);
section.insertBefore(error, list);
}
error.firstChild.textContent = message;
}
var sortable = makeSortable(list, {
item: '[data-slide-id]',
draggingClass: 'slide-item--dragging',
sortingClass: 'slide-list--sorting',
onChange: function (item) {
var all = sortable.items();
var ids = all.map(function (node) { return node.getAttribute('data-slide-id'); });
var title = item.querySelector('.slide-item__title');
renumber(all);
if (status) {
status.textContent = '„' + (title ? title.textContent : '') + '“ ist jetzt an Position '
+ (all.indexOf(item) + 1) + ' von ' + all.length + '.';
}
item.classList.add('slide-item--saving');
// Sequential, so an older order can never overwrite a newer one.
saving = saving.then(function () {
return postJson(url, { ids: ids });
}).catch(function () {
showError('Die Reihenfolge konnte nicht gespeichert werden. Bitte lade die Seite neu.');
}).then(function () {
item.classList.remove('slide-item--saving');
});
}
});
if (sortable.items().length > 1) {
list.querySelectorAll('[data-drag-handle]').forEach(function (handle) { handle.hidden = false; });
if (hint) {
hint.hidden = false;
}
}
}
/**
* Local reordering inside a form (ordering slide editor and participant answer):
* only the DOM order changes, the form posts its fields in that order.
*/
function initOrderList(container, itemSelector, describe) {
var list = container.querySelector('[data-order-list]');
var status = container.querySelector('[data-order-status]');
var sortable = makeSortable(list, {
item: itemSelector,
draggingClass: 'is-dragging',
sortingClass: 'is-sorting',
onChange: function (item) {
var all = sortable.items();
renumber(all, list.hasAttribute('data-position-suffix') ? '.' : '');
if (status) {
status.textContent = describe(item) + ' ist jetzt an Position ' + (all.indexOf(item) + 1) + ' von ' + all.length + '.';
}
}
});
list.querySelectorAll('[data-drag-handle]').forEach(function (handle) { handle.hidden = false; });
return sortable;
}
/** Ordering slide editor: sortable rows plus "add entry". */
function initOrderOptions(fieldset) {
var list = fieldset.querySelector('[data-order-list]');
var button = fieldset.querySelector('[data-order-add]');
var hint = fieldset.querySelector('[data-order-hint]');
var max = parseInt(fieldset.getAttribute('data-max'), 10) || 10;
list.setAttribute('data-position-suffix', '');
var sortable = initOrderList(fieldset, '[data-order-row]', function (item) {
var value = item.querySelector('input[type=text]').value.trim();
return value ? '„' + value + '“' : 'Die leere Zeile';
});
if (hint) {
hint.hidden = false;
}
function update() {
button.hidden = sortable.items().length >= max;
}
button.addEventListener('click', function () {
var all = sortable.items();
if (all.length >= max) {
return;
}
var row = all[all.length - 1].cloneNode(true);
var text = row.querySelector('input[type=text]');
var id = 'order-option-' + all.length + '-' + Date.now();
row.querySelector('[data-row-label]').setAttribute('for', id);
text.id = id;
text.value = '';
text.required = false;
text.placeholder = 'Eintrag ' + (all.length + 1);
list.appendChild(row);
renumber(sortable.items(), '.');
text.focus();
update();
});
update();
}
/** Participant answer of an ordering slide. */
function initOrderForm(form) {
initOrderList(form, '[data-order-item]', function (item) {
return '„' + item.querySelector('[data-label]').textContent + '“';
});
}
// ------------------------------------------------------------------ theme switch
var THEME_ICONS = { auto: '◐', light: '☀', dark: '☾' };
function initThemeSwitch(button) {
var key = button.getAttribute('data-theme-key');
var modes = button.getAttribute('data-theme-modes').split(',');
var root = document.documentElement;
function current() {
var theme = root.getAttribute('data-theme') || 'auto';
return modes.indexOf(theme) >= 0 ? theme : modes[0];
}
function label(mode) {
return button.getAttribute('data-label-' + mode);
}
function render() {
var mode = current();
var next = modes[(modes.indexOf(mode) + 1) % modes.length];
button.querySelector('[data-theme-icon]').textContent = THEME_ICONS[mode];
var text = button.getAttribute('data-label-prefix') + ': ' + label(mode) + ', '
+ button.getAttribute('data-label-next') + ' ' + label(next);
button.setAttribute('aria-label', text);
button.title = text + (button.hasAttribute('aria-keyshortcuts') ? ' (' + button.getAttribute('aria-keyshortcuts') + ')' : '');
}
button.addEventListener('click', function () {
var next = modes[(modes.indexOf(current()) + 1) % modes.length];
if (next === 'auto') {
root.removeAttribute('data-theme');
} else {
root.setAttribute('data-theme', next);
}
try {
localStorage.setItem(key, next);
} catch (e) {
// private mode: the choice just lasts until reload
}
render();
});
render();
button.hidden = false;
}
// ------------------------------------------------------------------ boot
// 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;
if (message) {
message.classList.add('hidden');
}
});
document.addEventListener('DOMContentLoaded', function () {
document.querySelectorAll('[data-theme-switch]').forEach(initThemeSwitch);
initCopy();
initShare();
document.querySelectorAll('[data-youtube-form]').forEach(initYouTubeForm);
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);
// Prevent double submits of vote forms.
document.querySelectorAll('.vote-form').forEach(function (form) {
form.addEventListener('submit', function (event) {
if (event.defaultPrevented) {
return; // handled via fetch (word cloud)
}
var button = form.querySelector('button[type=submit], button:not([type])');
if (button) {
setTimeout(function () { button.disabled = true; }, 0);
}
});
});
});
window.Plenario = { Results: Results, Words: Words, Countdown: Countdown };
})();