Quiz slides have predefined answers with one or more marked as correct. The presenter starts the quiz, which then runs until its optional time limit expires or the presenter ends it. Counts and correct answers are only revealed once the quiz is finished; participants then see whether their answer was right. - migration: slide_options.is_correct, slides.voting_started_at/voting_ends_at - Slide::isVotingOpen() includes the quiz deadline, expired quizzes are closed lazily when the state is read - presenter countdown, quiz tiles and reveal with correct-answer summary - CSV export marks quiz answers as right/wrong Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
954 lines
40 KiB
JavaScript
954 lines
40 KiB
JavaScript
/**
|
||
* 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-presenter] presenter screen, polls /admin/{token}/state
|
||
* - [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
|
||
*
|
||
* 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) {
|
||
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) {
|
||
if (!response.ok) {
|
||
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; });
|
||
}
|
||
};
|
||
|
||
// ------------------------------------------------------------------ results
|
||
|
||
var Results = {
|
||
/**
|
||
* @param {Object} [options] renderer specific; wordcloud: {mine: [keys], onUpvote: fn(word)|null}
|
||
*/
|
||
render: function (container, results, options) {
|
||
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.
|
||
if (results.participants === 0 && !(results.type === 'quiz' && !results.revealed)) {
|
||
container.appendChild(el('p', { class: 'results-empty', text: 'Noch keine Antworten' }));
|
||
return;
|
||
}
|
||
container.appendChild(renderer(results, options || {}));
|
||
},
|
||
|
||
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 + ')' })
|
||
]);
|
||
}));
|
||
},
|
||
|
||
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
|
||
]);
|
||
return el('div', { class: 'scale-results' }, [average, columns, labels]);
|
||
},
|
||
|
||
/**
|
||
* 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);
|
||
}
|
||
|
||
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]);
|
||
},
|
||
|
||
open: function (results) {
|
||
return el('ul', { class: 'answers' }, results.answers.map(function (answer) {
|
||
return el('li', { class: 'answer', text: answer.text });
|
||
}));
|
||
}
|
||
};
|
||
|
||
// ------------------------------------------------------------------ copy
|
||
|
||
function initCopy() {
|
||
document.querySelectorAll('[data-copy]').forEach(function (button) {
|
||
button.addEventListener('click', function () {
|
||
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();
|
||
}
|
||
});
|
||
});
|
||
}
|
||
|
||
// ------------------------------------------------------------------ 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 last = '';
|
||
var hideResults = false;
|
||
var state = null;
|
||
|
||
function render(newState) {
|
||
var serialized = JSON.stringify(newState);
|
||
if (serialized === last) {
|
||
return;
|
||
}
|
||
last = serialized;
|
||
state = newState;
|
||
var slide = state.slide;
|
||
|
||
q('[data-counter]').textContent = state.count === 0
|
||
? '0 / 0'
|
||
: (state.index === null ? '–' : state.index + 1) + ' / ' + state.count;
|
||
|
||
if (!slide) {
|
||
q('[data-type]').textContent = '';
|
||
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.'
|
||
: 'Drücke → um zu starten.';
|
||
q('[data-results]').innerHTML = '';
|
||
q('[data-voting]').hidden = true;
|
||
q('[data-participants]').textContent = '';
|
||
return;
|
||
}
|
||
|
||
var quizPhase = slide.type === 'quiz' && state.results ? state.results.phase : null;
|
||
q('[data-type]').textContent = quizPhase
|
||
? slide.typeLabel + ' · ' + { ready: 'bereit', running: 'läuft', finished: 'Auflösung' }[quizPhase]
|
||
: 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--closed', slide.isInteractive && !slide.isVotingOpen && !quizPhase);
|
||
|
||
var voting = q('[data-voting]');
|
||
voting.hidden = !slide.isInteractive;
|
||
voting.textContent = quizPhase
|
||
? { ready: 'Quiz starten', running: 'Quiz beenden', finished: 'Quiz erneut öffnen' }[quizPhase]
|
||
: (slide.isVotingOpen ? 'Abstimmung schließen' : 'Abstimmung öffnen');
|
||
|
||
q('[data-participants]').textContent = slide.isInteractive
|
||
? state.results.participants + ' ' + (state.results.participants === 1 ? 'Antwort' : 'Antworten')
|
||
: '';
|
||
|
||
var container = q('[data-results]');
|
||
container.classList.toggle('is-hidden', hideResults);
|
||
Results.render(container, slide.isInteractive ? state.results : null);
|
||
Countdown.start();
|
||
}
|
||
|
||
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;
|
||
q('[data-results]').classList.toggle('is-hidden', hideResults);
|
||
q('[data-hide-results]').textContent = hideResults ? 'Ergebnisse zeigen' : 'Ergebnisse verbergen';
|
||
}
|
||
q('[data-hide-results]').addEventListener('click', toggleHide);
|
||
|
||
function toggleFullscreen() {
|
||
if (!document.fullscreenElement) {
|
||
(document.documentElement.requestFullscreen || function () {}).call(document.documentElement);
|
||
} else if (document.exitFullscreen) {
|
||
document.exitFullscreen();
|
||
}
|
||
}
|
||
q('[data-fullscreen]').addEventListener('click', toggleFullscreen);
|
||
|
||
var overlay = q('[data-qr-overlay]');
|
||
function toggleQr() {
|
||
overlay.hidden = !overlay.hidden;
|
||
}
|
||
q('[data-qr-toggle]').addEventListener('click', toggleQr);
|
||
overlay.addEventListener('click', toggleQr);
|
||
|
||
document.addEventListener('keydown', function (event) {
|
||
if (event.target.closest('input, textarea, select')) {
|
||
return;
|
||
}
|
||
switch (event.key) {
|
||
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 'Escape':
|
||
overlay.hidden = true;
|
||
break;
|
||
}
|
||
});
|
||
|
||
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);
|
||
}
|
||
|
||
function renderResults(state) {
|
||
current = 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,
|
||
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();
|
||
}
|
||
|
||
// ------------------------------------------------------------------ boot
|
||
|
||
document.addEventListener('DOMContentLoaded', function () {
|
||
initCopy();
|
||
document.querySelectorAll('[data-presenter]').forEach(initPresenter);
|
||
document.querySelectorAll('[data-participant]').forEach(initParticipant);
|
||
document.querySelectorAll('[data-quiz-options]').forEach(initQuizOptions);
|
||
|
||
// 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 };
|
||
})();
|