Files
Plenario/webroot/js/plenario.js
T
gnilebeinandClaude Opus 5.5 1cb439de18
CI / Deploy / test (push) Successful in 45s
CI / Deploy / deploy (push) Skipped
Enlarge participant headings and make theme switch icon-only
The slide heading on the participant page was smaller than a regular h1
on phones. The theme switch now shows only its icon; the current and
next scheme stay available as aria-label and tooltip.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 16:48:59 +01:00

1711 lines
74 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-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) {
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.
// A Q&A slide always shows its stages.
if (results.participants === 0 && results.type !== 'qa' && !(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) {
if (results.private) {
// Anonymous feedback: the texts never reach the stage, only the count.
var n = results.participants;
return el('div', { class: 'private-summary' }, [
el('p', { class: 'private-summary__count', text: String(n) }),
el('p', { text: (n === 1 ? 'anonyme Antwort' : 'anonyme Antworten') + ' eingegangen' }),
el('p', { class: 'private-summary__hint', text: '🔒 Antworten werden nicht öffentlich angezeigt.' })
]);
}
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)];
function votes(question) {
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')
+ ' · 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 three stages; clickable for the presenter (onStage). */
steps: function (stage, onStage) {
return el('ol', { class: 'qa-steps', 'aria-label': 'Ablauf' }, ['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 = '';
var hideResults = false;
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-action="stop"]');
if (pauseButton) {
pauseButton.hidden = !slide;
}
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 → 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;
q('[data-type]').textContent = quizPhase
? slide.typeLabel + ' · ' + { ready: 'bereit', running: 'läuft', finished: 'Auflösung' }[quizPhase]
: (qaStage ? slide.typeLabel + ' · ' + Qa.labels[qaStage] : 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);
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.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')));
var container = q('[data-results]');
container.classList.toggle('is-hidden', hideResults);
Results.render(container, slide.isInteractive ? state.results : null, {
onStage: function (stage) { control('stage', { stage: stage }); },
onQuestion: function (step) { control('question', { step: step }); }
});
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);
setText('[data-hide-results] [data-label]', hideResults ? 'Ergebnisse zeigen' : 'Ergebnisse verbergen');
}
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 (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('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;
}
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) {
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)
]);
}
return el('li', { class: 'qa-item' + (mine ? ' is-mine' : '') + (given > 0 ? ' is-upvoted' : '') }, [
el('span', { class: 'qa-item__text', text: question.text }),
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)' : '') }),
el('span', { class: 'qa-votes', 'aria-label': question.votes + (question.votes === 1 ? ' Stimme' : ' Stimmen'), text: '▲ ' + question.votes })
]);
})));
}
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,
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 slide list
function initSortable(list) {
var url = list.getAttribute('data-sortable');
var section = list.parentNode;
var status = section.querySelector('[data-sortable-status]');
var hint = section.querySelector('[data-sortable-hint]');
var error = null;
var saving = Promise.resolve();
var drag = null;
function items() {
return Array.prototype.slice.call(list.children).filter(function (node) {
return node.hasAttribute('data-slide-id');
});
}
function order() {
return items().map(function (item) { return item.getAttribute('data-slide-id'); });
}
function renumber() {
items().forEach(function (item, index) {
var pos = item.querySelector('[data-position]');
if (pos) {
pos.textContent = String(index + 1);
}
});
}
function label(item) {
var title = item.querySelector('.slide-item__title');
return title ? title.textContent : '';
}
function announce(text) {
if (status) {
status.textContent = text;
}
}
function announceMove(item) {
var all = items();
announce('„' + label(item) + '“ ist jetzt an Position ' + (all.indexOf(item) + 1) + ' von ' + all.length + '.');
}
function showError(message) {
if (!error) {
var reload = el('button', { type: 'button', class: 'button button--small', text: 'Seite neu laden' });
reload.addEventListener('click', function () { window.location.reload(); });
error = el('div', { class: 'notice', role: 'alert' }, [el('span'), document.createTextNode(' '), reload]);
section.insertBefore(error, list);
}
error.firstChild.textContent = message;
}
function save(item) {
var ids = order();
renumber();
announceMove(item);
item.classList.add('slide-item--saving');
// Sequential, so an older order can never overwrite a newer one.
saving = saving.then(function () {
return postJson(url, { ids: ids });
}).catch(function () {
showError('Die Reihenfolge konnte nicht gespeichert werden. Bitte lade die Seite neu.');
}).then(function () {
item.classList.remove('slide-item--saving');
});
}
// Keyboard: arrow keys on the handle move the slide by one.
list.addEventListener('keydown', function (event) {
var handle = event.target.closest('[data-drag-handle]');
if (!handle || (event.key !== 'ArrowUp' && event.key !== 'ArrowDown')) {
return;
}
event.preventDefault();
var item = handle.closest('[data-slide-id]');
var up = event.key === 'ArrowUp';
var sibling = up ? item.previousElementSibling : item.nextElementSibling;
if (!sibling || !sibling.hasAttribute('data-slide-id')) {
return;
}
list.insertBefore(item, up ? sibling : sibling.nextElementSibling);
handle.focus();
save(item);
});
// Pointer (mouse, touch, pen): drag by the handle.
function pageTop(node) {
return node.getBoundingClientRect().top + window.scrollY;
}
function onMove(event) {
if (!drag || event.pointerId !== drag.pointerId) {
return;
}
var item = drag.item;
var all = items();
var index = all.indexOf(item);
var prev = all[index - 1];
var next = all[index + 1];
var top = event.clientY + window.scrollY - drag.grabOffset;
var bottom = top + item.offsetHeight;
if (prev && top < pageTop(prev) + prev.offsetHeight / 2) {
list.insertBefore(item, prev);
} else if (next && bottom > pageTop(next) + next.offsetHeight / 2) {
list.insertBefore(item, next.nextElementSibling);
}
item.style.transform = '';
item.style.transform = 'translateY(' + (top - pageTop(item)) + 'px)';
// Scroll the page when dragging close to the viewport edge.
if (event.clientY < 60) {
window.scrollBy(0, -12);
} else if (event.clientY > window.innerHeight - 60) {
window.scrollBy(0, 12);
}
}
function onEnd(event) {
if (!drag || event.pointerId !== drag.pointerId) {
return;
}
var item = drag.item;
var changed = order().join(',') !== drag.before;
item.style.transform = '';
item.classList.remove('slide-item--dragging');
list.classList.remove('slide-list--sorting');
drag = null;
if (changed) {
save(item);
}
}
list.addEventListener('pointerdown', function (event) {
var handle = event.target.closest('[data-drag-handle]');
if (!handle || event.button !== 0 || drag) {
return;
}
event.preventDefault();
var item = handle.closest('[data-slide-id]');
handle.setPointerCapture(event.pointerId);
drag = {
item: item,
pointerId: event.pointerId,
grabOffset: event.clientY - item.getBoundingClientRect().top,
before: order().join(',')
};
item.classList.add('slide-item--dragging');
list.classList.add('slide-list--sorting');
});
list.addEventListener('pointermove', onMove);
list.addEventListener('pointerup', onEnd);
list.addEventListener('pointercancel', onEnd);
if (items().length > 1) {
list.querySelectorAll('[data-drag-handle]').forEach(function (handle) { handle.hidden = false; });
if (hint) {
hint.hidden = false;
}
}
}
// ------------------------------------------------------------------ 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
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);
// 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 };
})();