Files
Plenario/webroot/js/plenario.js
T
gnilebein 1b48ce7852
CI / Deploy / PHP 8.4 (push) Successful in 1m44s
CI / Deploy / PHP 8.5 (push) Successful in 1m47s
CI / Deploy / test (push) Successful in 1s
CI / Deploy / deploy (push) Successful in 6s
Merge pull request 'Add an optional countdown to every slide that collects answers' (#122) from feature/countdown-all-types into main
Reviewed-on: #122
2026-11-21 12:22:12 +01:00

3303 lines
148 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-qr-download] save the sibling QR <img> (SVG) as PNG via canvas
* - [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-audio-form] admin menu: countdown music dropzone, sends the file as soon as it is chosen or dropped
* - [data-sortable] admin slide list: drag & drop / arrow keys via [data-drag-handle], POSTs ids[] to the URL
* - [data-order-options] slide form of ordering slides: sortable rows (correct order), "add entry"
* - [data-order-form] participant answer of ordering slides: sortable items posting order[]
* - [data-live] admin dashboard: forms inside (hide, delete, duplicate, …) run via fetch and refresh
* the [data-refresh] regions instead of reloading the page (header X-Fragment)
* - [data-modal] link whose target page (slide form) opens in the <dialog data-modal-dialog>
* - [data-confirm] on a submit button: window.confirm() before the form is sent (replaces inline onclick, CSP)
* - [data-theme-switch] cycles the colour scheme (data-theme on <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;
}
/**
* Light formatting of slide texts in WhatsApp style, same rules as App\View\Helper\FormatHelper:
* *bold*, _italic_, ~strikethrough~, lists with "- " or "* " at the start of a line.
* Builds DOM nodes (text via textContent), never HTML strings.
*/
var Format = {
INLINE: /(^|[^\p{L}\p{N}])([*_~])(\S|\S[^\n]*?\S)\2(?=$|[^\p{L}\p{N}])/u,
LIST_ITEM: /^\s*[-*•]\s+(.*)$/u,
TAGS: { '*': 'strong', '_': 'em', '~': 's' },
render: function (container, text) {
container.textContent = '';
var lines = String(text || '').trim().split(/\r\n|\r|\n/);
var list = null;
var lineBefore = false;
lines.forEach(function (line) {
var item = Format.LIST_ITEM.exec(line);
if (item) {
if (!list) {
list = container.appendChild(el('ul'));
}
list.appendChild(el('li', {}, Format.inline(item[1])));
lineBefore = false;
return;
}
if (lineBefore) {
container.appendChild(el('br'));
}
list = null;
Format.inline(line).forEach(function (node) { container.appendChild(node); });
lineBefore = true;
});
},
inline: function (text) {
var m = Format.INLINE.exec(text);
if (!m) {
return text ? [document.createTextNode(text)] : [];
}
var before = text.slice(0, m.index) + m[1];
return (before ? [document.createTextNode(before)] : [])
.concat([el(Format.TAGS[m[2]], {}, Format.inline(m[3]))])
.concat(Format.inline(text.slice(m.index + m[0].length)));
}
};
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'));
}
});
}
};
// ------------------------------------------------------------------ stage audio
/**
* Music of the presentation (presenter view only): plays in a loop while a quiz runs, so it also covers a
* countdown that is longer than the file, and stops when the quiz ends or the slide changes.
* Browsers may refuse to start audio without a previous click or key press; the presenter has
* always pressed something to start the quiz, and a refused start is retried on the next one.
*/
var StageAudio = {
element: null,
url: null,
wanted: false,
/** @param {string|null} url audio URL of the poll, only passed while a quiz is running */
sync: function (url) {
StageAudio.wanted = !!url;
if (!url) {
StageAudio.stop();
return;
}
if (!StageAudio.element) {
StageAudio.element = new Audio();
StageAudio.element.loop = true;
StageAudio.element.preload = 'auto';
}
var audio = StageAudio.element;
if (StageAudio.url !== url) {
StageAudio.url = url;
audio.src = url;
}
if (audio.paused) {
StageAudio.play();
}
},
play: function () {
var attempt = StageAudio.element && StageAudio.element.play();
if (attempt && attempt.catch) {
attempt.catch(function () {
// Blocked (no user activation yet): try again on the next click or key press.
var retry = function () {
document.removeEventListener('click', retry, true);
document.removeEventListener('keydown', retry, true);
if (StageAudio.wanted && StageAudio.element && StageAudio.element.paused) {
StageAudio.play();
}
};
document.addEventListener('click', retry, true);
document.addEventListener('keydown', retry, true);
});
}
},
stop: function () {
StageAudio.wanted = false;
if (StageAudio.element && !StageAudio.element.paused) {
StageAudio.element.pause();
}
if (StageAudio.element && StageAudio.element.currentTime) {
StageAudio.element.currentTime = 0;
}
}
};
// ------------------------------------------------------------------ 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 = {
key: null,
index: 0,
paused: false,
timer: null,
items: [],
format: String,
// Speed factor of the poll (state.poll.commentSpeed): 2 = half the time per comment.
speed: 1,
node: null,
// Countdown of the comment shown (drives the progress bar across re-renders).
startedAt: 0,
duration: 0,
// Time per comment: enough to read it on the stage, within sensible bounds.
BASE_MS: 2500,
CHARS_PER_SECOND: 15,
MIN_MS: 5000,
MAX_MS: 30000,
/**
* @param {Array} items comments, oldest first
* @param {Function} format turns a rating into display text (number or stars)
*/
render: function (items, format) {
Comments.format = format || String;
// 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;
}
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
});
};
// Every comment sits invisibly in the same grid cell as the one shown, so the box is as
// tall as the longest comment and the centred stage does not jump while they rotate.
var sizers = items.length < 2 ? [] : items.map(function (item) {
return el('div', { class: 'comments__sizer', 'aria-hidden': 'true' }, [
el('blockquote', { class: 'comments__text', text: item.text })
]);
});
// The rating (same height for every comment, all or none per slide) sits above the
// text, so it stays in place while the comments rotate.
var node = el('section', { class: 'comments', 'data-comments': '', 'aria-label': 'Kommentare' }, [
el('p', { class: 'comments__counter', 'data-comment-counter': '' }),
el('p', { class: 'comments__value', 'data-comment-value': '' }),
el('div', { class: 'comments__body' }, sizers.concat([
el('div', { class: 'comments__current' }, [
el('blockquote', { class: 'comments__text', 'data-comment-text': '' })
])
])),
// Time left until the next comment; decorative, the counter carries the information.
items.length < 2 ? null : Comments.progressBorder(),
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);
}
// The comment shown now gets its full reading time.
Comments.restart();
Comments.update(false);
});
Comments.node = node;
if (!Comments.timer) {
Comments.restart();
}
Comments.update(false);
return node;
},
/**
* The box has a maximum height (CSS --comment-max); a comment that does not fit is set
* smaller step by step instead of being cut off. The invisible sizers are capped the same
* way, so a single long comment does not make the box huge.
*/
fit: function () {
var node = Comments.node;
if (!node || !document.body.contains(node)) {
return;
}
var current = node.querySelector('.comments__current');
var text = node.querySelector('[data-comment-text]');
var size = 1;
text.style.fontSize = '';
while (current.scrollHeight > current.clientHeight + 1 && size > Comments.MIN_FONT) {
size = Math.max(Comments.MIN_FONT, size - 0.05);
text.style.fontSize = 'calc(' + size + ' * var(--comment-size))';
}
},
// Smallest font size (factor) for a long comment.
MIN_FONT: 0.5,
step: function (delta) {
var n = Comments.items.length;
Comments.index = (Comments.index + delta + n) % n;
},
/**
* How long a comment stays on the stage: a base time plus reading time
* for its length, between MIN_MS and MAX_MS.
*
* @param {Object} item comment
* @return {number} milliseconds
*/
delay: function (item) {
var length = item && item.text ? Array.from(item.text).length : 0;
var ms = Comments.BASE_MS + length / Comments.CHARS_PER_SECOND * 1000;
// The poll's speed factor scales the bounds too, so short comments change as well.
var speed = Comments.speed > 0 ? Comments.speed : 1;
return Math.round(Math.min(Comments.MAX_MS, Math.max(Comments.MIN_MS, ms)) / speed);
},
/** (Re)start the countdown for the comment currently shown. */
restart: function () {
clearTimeout(Comments.timer);
Comments.startedAt = Date.now();
Comments.duration = Comments.delay(Comments.items[Comments.index]);
Comments.timer = setTimeout(function () {
if (!Comments.node || !document.body.contains(Comments.node)) {
// Slide changed: stop until the next comment list is rendered.
Comments.timer = null;
return;
}
var advance = !Comments.paused && Comments.items.length > 1 && !document.hidden;
if (advance) {
Comments.step(1);
}
Comments.restart();
if (advance) {
Comments.update(true);
} else {
Comments.progress();
}
}, Comments.duration);
},
/**
* Progress as the border of the box: an SVG outline (follows the rounded corners) whose
* dash pattern repeats every half perimeter, so two lines start at opposite corners
* (top left along the top, bottom right along the bottom) and meet when the time is up.
*/
progressBorder: function () {
var ns = 'http://www.w3.org/2000/svg';
var svg = document.createElementNS(ns, 'svg');
var rect = document.createElementNS(ns, 'rect');
rect.setAttribute('class', 'comments__progress-fill');
rect.setAttribute('pathLength', '100');
rect.setAttribute('data-comment-progress-fill', '');
svg.appendChild(rect);
return el('div', { class: 'comments__progress', 'data-comment-progress': '', 'aria-hidden': 'true' }, [svg]);
},
/**
* Fills the progress bar over the remaining time of the current comment.
* Picks up where it was after a re-render (negative animation delay); hidden while paused.
*/
progress: function () {
var bar = Comments.node && Comments.node.querySelector('[data-comment-progress]');
if (!bar) {
return;
}
var fill = bar.querySelector('[data-comment-progress-fill]');
bar.hidden = Comments.paused;
fill.style.animation = 'none';
void fill.getBoundingClientRect(); // restart the CSS animation (SVG has no offsetWidth)
if (!Comments.paused) {
var elapsed = Math.min(Date.now() - Comments.startedAt, Comments.duration);
fill.style.animation = 'comment-progress ' + Comments.duration + 'ms linear -' + elapsed + 'ms forwards';
}
},
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: ' + Comments.format(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');
}
// Measure once the box is in the document (render() calls this before it is attached).
requestAnimationFrame(Comments.fit);
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');
}
Comments.progress();
}
};
// A different width changes the line breaks: fit the comment again.
window.addEventListener('resize', function () { Comments.fit(); });
// ------------------------------------------------------------------ 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 || results.ready) {
// A slide with a countdown that has not started shows only its question.
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]));
var bars = 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 + ')' })
]);
}));
if (!results.comments || !results.comments.length) {
return bars;
}
return el('div', { class: 'choice-results' }, [bars, Comments.render(results.comments, String)]);
},
/**
* 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) {
if (results.stars) {
return Results.stars(results);
}
var total = Results.scaleTotal(results);
var hasAverage = results.average !== null;
var averageText = Results.averageText(results);
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: results.min + (results.minLabel ? ' · ' + results.minLabel : '') }),
el('span', { text: (results.maxLabel ? results.maxLabel + ' · ' : '') + results.max })
])
]);
var average = Results.averageCard(results, total, ' / ' + results.max, gauge, '');
var donut = Results.donut(results, total, results.buckets, function (bucket) {
return String(bucket.value);
});
var comments = results.comments && results.comments.length ? Comments.render(results.comments, String) : null;
return Results.scaleLayout(results, average, donut, comments);
},
/**
* Star rating (scale with stars): average as partly filled stars, distribution as a
* donut from most to fewest stars.
*/
stars: function (results) {
var total = Results.scaleTotal(results);
var averageText = Results.averageText(results);
var row = Array(results.max + 1).join('★');
var meter = el('div', {
class: 'star-meter',
role: 'img',
'aria-label': 'Durchschnitt ' + averageText + ' von ' + results.max + ' Sternen'
}, [
// Same glyphs twice: the filled layer is clipped to the average.
el('span', { class: 'star-meter__base', 'aria-hidden': 'true', text: row }),
el('span', {
class: 'star-meter__fill',
'aria-hidden': 'true',
style: 'width:' + (results.average !== null ? results.average / results.max * 100 : 0) + '%',
text: row
})
]);
var average = Results.averageCard(results, total, ' von ' + results.max, meter, ' average--stars');
var donut = Results.donut(results, total, results.buckets.slice().reverse(), function (bucket) {
return bucket.value + (bucket.value === 1 ? ' Stern' : ' Sterne');
});
var comments = results.comments && results.comments.length
? Comments.render(results.comments, function (value) {
return row.slice(0, value) + Array(results.max - value + 1).join('☆')
+ ' (' + value + ' von ' + results.max + ')';
})
: null;
return Results.scaleLayout(results, average, donut, comments);
},
scaleTotal: function (results) {
return results.buckets.reduce(function (sum, b) { return sum + b.count; }, 0);
},
averageText: function (results) {
return results.average !== null
? Number(results.average).toLocaleString('de-DE', { minimumFractionDigits: 1, maximumFractionDigits: 1 })
: '–';
},
/** Card with the average as a big figure, its visual (gauge or stars) and the number of ratings. */
averageCard: function (results, total, ofText, visual, modifier) {
return el('div', { class: 'average' + modifier }, [
el('span', { class: 'average__label', text: 'Durchschnitt' }),
el('span', { class: 'average__value' }, [
el('strong', { text: Results.averageText(results) }),
el('span', { class: 'average__of', text: ofText })
]),
visual,
el('span', { class: 'average__count', text: total + (total === 1 ? ' Bewertung' : ' Bewertungen') })
]);
},
/**
* Distribution of a scale as a donut (conic-gradient) with a legend in the same order.
* Each value gets its own colour (fixed order along the scale, see palette); small
* transparent gaps separate the slices. The labels of both ends go into the legend,
* the number of ratings into the hole.
*/
donut: function (results, total, buckets, label) {
// Distinct theme colours in a fixed order along the scale; scales with more values
// than colours get mixed colours in between.
var palette = ['--c0', '--c4', '--c2', '--c3', '--c1', '--c5'];
var shade = function (bucket) {
var rank = (bucket.value - results.min) / Math.max(1, results.max - results.min);
var pos = rank * (palette.length - 1);
var i = Math.floor(pos);
var f = pos - i;
if (f < 0.01 || i >= palette.length - 1) {
return 'var(' + palette[Math.min(i, palette.length - 1)] + ')';
}
return 'color-mix(in oklab, var(' + palette[i] + ') ' + Math.round((1 - f) * 100) + '%, var(' + palette[i + 1] + '))';
};
var used = buckets.filter(function (b) { return b.count > 0; }).length;
var gap = used > 1 ? 0.8 : 0;
var stops = [];
var at = 0;
buckets.forEach(function (bucket) {
if (!bucket.count) {
return;
}
var end = at + bucket.count / total * 100;
stops.push(shade(bucket) + ' ' + at + '% ' + (end - gap) + '%');
stops.push('transparent ' + (end - gap) + '% ' + end + '%');
at = end;
});
var countText = total === 1 ? 'Bewertung' : 'Bewertungen';
var ring = el('div', { class: 'donut__chart' }, [
el('div', {
class: 'donut__ring' + (total ? '' : ' donut__ring--empty'),
'aria-hidden': 'true',
style: total ? 'background:conic-gradient(' + stops.join(',') + ')' : ''
}),
el('p', { class: 'donut__count' }, [
el('strong', { text: String(total) }),
el('span', { text: countText })
])
]);
var ends = {};
ends[results.min] = results.minLabel;
ends[results.max] = results.maxLabel;
var legend = el('ul', { class: 'donut__legend' + (buckets.length > 6 ? ' donut__legend--wide' : '') }, buckets.map(function (bucket) {
return el('li', { class: 'donut__item' + (bucket.count ? '' : ' is-empty') }, [
el('span', { class: 'donut__swatch', 'aria-hidden': 'true', style: 'background:' + shade(bucket) }),
el('span', { class: 'donut__label', text: label(bucket) + (ends[bucket.value] ? ' – ' + ends[bucket.value] : '') }),
el('span', { class: 'donut__value', text: formatNumber(bucket.percent) + ' % (' + bucket.count + ')' })
]);
}));
return el('div', { class: 'donut' }, [ring, legend]);
},
/**
* Average and distribution side by side; with the slide setting scale_view (results.view:
* both|average|chart) only one of them is shown, centred.
*/
scaleLayout: function (results, average, donut, comments) {
var view = results.view || 'both';
var parts = [view !== 'chart' ? average : null, view !== 'average' ? donut : null];
var row = el('div', { class: 'scale-results__row' + (view === 'both' ? '' : ' scale-results__row--single') }, parts);
return el('div', { class: 'scale-results' }, [row, 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 – die Antworten erscheinen, sobald das Quiz gestartet wird' }));
return el('div', { class: 'quiz-results quiz-results--' + results.phase }, children);
}
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.ranking) {
// Personal ranking: no solution, the average of all submitted orders (live, stage only).
if (results.participants === 0) {
return el('div', { class: 'order-results' }, [
el('p', { class: 'quiz-status', text: 'Die Teilnehmenden sortieren nach ihrer persönlichen Einschätzung' }),
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 });
}))
]);
}
return el('div', { class: 'order-results order-results--ranking' }, [
el('ol', { class: 'order-solution' }, results.items.map(function (item) {
return el('li', { class: 'bar order-solution__item' }, [
el('div', { class: 'bar__label' }, [
el('span', { class: 'order-solution__pos', text: item.position + '.' }),
document.createTextNode(' ' + item.label)
]),
el('div', { class: 'bar__track' }, [
el('div', { class: 'bar__fill', style: 'width:' + item.score + '%' })
]),
el('div', { class: 'bar__value', text: 'Ø Platz ' + formatNumber(item.average) })
]);
}))
]);
}
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 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') {
// The questions are voted on at the participants' devices: the stage only points there
// (no list, counts or ranking, so it can not sway the vote).
children.push(el('div', { class: 'qa-vote-hint' }, [
el('p', { class: 'qa-vote-hint__title', text: 'Jetzt abstimmen!' }),
el('p', { class: 'qa-vote-hint__text', text: 'Schau auf dein Gerät und gib deine Stimmen den Fragen, die dir wichtig sind.' }),
el('p', { class: 'qa-summary', text: questions.length + (questions.length === 1 ? ' Frage' : ' Fragen')
+ ' · jede Person hat ' + results.maxUpvotes + (results.maxUpvotes === 1 ? ' Stimme' : ' Stimmen')
+ (results.maxPerQuestion < results.maxUpvotes ? ' (höchstens ' + results.maxPerQuestion + ' pro Frage)' : '')
+ ' · bisher ' + results.upvotes + ' vergeben' })
]));
} 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(root) {
(root || document).querySelectorAll('[data-copy]').forEach(function (button) {
button.addEventListener('click', function () { copyFrom(button); });
});
}
// ------------------------------------------------------------------ QR download
/**
* [data-qr-download]: renders the SVG QR code (the sibling <img>) onto a canvas and saves it as PNG.
* data-filename sets the file name. Hidden without JS / canvas support.
*/
function initQrDownload() {
document.querySelectorAll('[data-qr-download]').forEach(function (button) {
var img = button.parentNode.querySelector('img');
if (!img || !document.createElement('canvas').toBlob) {
return;
}
button.hidden = false;
button.addEventListener('click', function () {
var size = 1024;
// The SVG has only a viewBox; an explicit size keeps Firefox from refusing to draw it.
var source = new Image(size, size);
source.onload = function () {
var canvas = document.createElement('canvas');
canvas.width = size;
canvas.height = size;
var ctx = canvas.getContext('2d');
ctx.fillStyle = '#fff';
ctx.fillRect(0, 0, size, size);
ctx.drawImage(source, 0, 0, size, size);
canvas.toBlob(function (blob) {
if (!blob) {
return;
}
var link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = button.getAttribute('data-filename') || 'qr-code.png';
document.body.appendChild(link);
link.click();
link.remove();
setTimeout(function () { URL.revokeObjectURL(link.href); }, 1000);
}, 'image/png');
};
source.src = img.currentSrc || img.src;
});
});
}
// ------------------------------------------------------------------ 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 && root.classList.contains('stage--speaker')) {
// Speaker view never loads the player: the video plays in the presentation window only (no double audio).
media.appendChild(el('p', {class: 'stage__media-note muted', text: 'Das Video wird nur im Präsentationsfenster abgespielt.'}));
} else if (video) {
media.appendChild(youtubeFrame(video.embedUrl, slide.question));
}
}
/** Shows the image of the slide (layout: top | side | full via stage--img-* classes); the <img> stays while the file stays. */
function renderImage(slide) {
var figure = q('[data-image]');
var image = slide && slide.image ? slide.image : null;
['top', 'side', 'full'].forEach(function (layout) {
root.classList.toggle('stage--img-' + layout, !!image && image.layout === layout);
});
figure.hidden = !image;
if (!image) {
figure.textContent = '';
return;
}
var img = figure.querySelector('img');
if (!img) {
img = document.createElement('img');
figure.appendChild(img);
}
if (img.getAttribute('src') !== image.url) {
img.setAttribute('src', image.url);
}
img.setAttribute('alt', image.alt || '');
if (image.width && image.height) {
img.setAttribute('width', image.width);
img.setAttribute('height', image.height);
}
}
/** Speaker view: preview of the slide that "next" will show (labels only, the server sends no solutions). */
function renderNext(next) {
var box = q('[data-next]');
if (!box) {
return;
}
var options = q('[data-next-options]');
options.textContent = '';
setText('[data-next-meta]', next ? '· ' + next.typeLabel : '');
setText('[data-next-question]', next ? next.question : 'Das war die letzte Folie');
Format.render(q('[data-next-description]'), next ? next.description : '');
(next ? next.options : []).forEach(function (label) {
options.appendChild(el('li', { text: label }));
});
setText('[data-next-note]', next && next.hasImage ? 'Die Folie enthält ein Bild.' : '');
box.classList.toggle('stage__next--end', !next);
}
function render(newState) {
var serialized = JSON.stringify(newState);
if (serialized === last) {
return;
}
last = serialized;
state = newState;
var slide = state.slide;
renderNext(state.next);
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-status]').textContent = state.poll.isPaused ? 'Pause' : '';
var allHidden = state.count === 0 && state.hiddenCount > 0;
q('[data-question]').textContent = state.count === 0
? (allHidden ? 'Alle Folien sind ausgeblendet' : 'Noch keine Folien angelegt')
: (state.poll.isPaused ? 'Gerade ist keine Frage aktiv' : state.poll.title);
q('[data-description]').textContent = state.count === 0
? (allHidden ? 'Blende in der Verwaltung mindestens eine Folie ein.' : 'Lege in der Verwaltung Fragen an.')
: (state.poll.isPaused ? '' : 'Drücke → um zu starten.');
q('[data-results]').innerHTML = '';
q('[data-stage-timer]').textContent = '';
renderMedia(null);
renderImage(null);
root.classList.remove('stage--video');
q('[data-voting]').hidden = true;
setText('[data-participants]', '');
StageAudio.stop();
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;
// Countdown of any slide that has one (a quiz shows its timer inside its results).
var timer = state.results && state.results.timer ? state.results.timer : null;
var phase = timer ? timer.phase : null;
var timed = phase && !quizPhase ? phase : null;
var closed = slide.isInteractive && !slide.isVotingOpen && !quizPhase && !qaStage && !orderRevealed && timed !== 'ready';
// Status line above the question: only what the room needs to know, not the slide type.
q('[data-status]').textContent = quizPhase
? { ready: 'Bereit', running: 'Läuft', finished: 'Auflösung' }[quizPhase]
: (qaStage ? Qa.labels[qaStage]
: (orderRevealed ? 'Auflösung'
: (timed === 'ready' ? 'Bereit' : (timed === 'running' ? 'Läuft' : (closed ? 'Abstimmung geschlossen' : '')))));
renderStageTimer(timed === 'running' && timer.remaining !== null ? timer.remaining : null);
q('[data-question]').textContent = slide.question;
Format.render(q('[data-description]'), slide.description);
root.classList.toggle('stage--content', !slide.isInteractive);
root.classList.toggle('stage--video', slide.type === 'youtube');
renderMedia(slide);
renderImage(slide);
root.classList.toggle('stage--closed', closed);
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]
: (timed
? { ready: 'Countdown starten', running: 'Abstimmung schließen', finished: 'Countdown erneut starten' }[timed]
: 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 || timed === 'ready' ? '' : (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();
StageAudio.sync(phase === 'running' ? state.poll.audioUrl : null);
}
/** Big countdown below the question for slides that are not a quiz; null removes it. */
function renderStageTimer(remaining) {
var box = q('[data-stage-timer]');
box.textContent = '';
if (remaining === null) {
return;
}
box.appendChild(el('p', {
class: 'quiz-timer',
role: 'timer',
'data-countdown': '',
'data-remaining': String(remaining)
}, [el('strong', { 'data-countdown-value': '', text: formatSeconds(remaining) })]));
}
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;
}
Comments.speed = state.poll && state.poll.commentSpeed;
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'
: (state.isHidden ? 'ausgeblendet' : (isLive ? '● live' : 'nicht live'));
indicator.classList.toggle('is-live', isLive);
q('[data-go-live]').hidden = isLive || !state.poll.isActive || !!state.isHidden;
}
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', 'ArrowUp', 'ArrowDown', 'PageUp', 'PageDown', ' ', 'b', 'B', 'p', 'P', 'f', 'F', 'q', 'Q'].indexOf(event.key) >= 0) {
return; // slide navigation belongs to the surrounding presentation
}
switch (event.key) {
case 'b':
case 'B':
case 'p':
case 'P':
control(state && !state.slide && state.poll.isPaused ? 'resume' : 'stop');
break;
case 'ArrowRight':
case 'ArrowDown':
case 'PageDown':
case ' ':
event.preventDefault();
control('next');
break;
case 'ArrowLeft':
case 'ArrowUp':
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;
// Own question being edited: polling must not re-render the list (and wipe the draft) meanwhile.
var qaEditing = null;
var qaLatest = null;
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;
}
if (response.ok && data.vote === 'edit') {
qaEditing = 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;
}
qaLatest = state;
if (qaEditing !== null) {
return; // rendered once the edit is saved or cancelled
}
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;
var item = 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
]);
if (mine) {
item.appendChild(qaOwnActions(item, question));
}
return item;
})));
restoreQaFocus(focused);
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
]);
})));
}
restoreQaFocus(focused);
}
function restoreQaFocus(focused) {
if (focused) {
var again = qaList.querySelector('[data-question-id="' + focused + '"]');
if (again && !again.disabled) {
again.focus();
}
}
}
/** Ends editing and shows the latest state, focus back on the question's edit button. */
function qaStopEditing(id) {
qaEditing = null;
qaRendered = '';
renderQa(qaLatest);
restoreQaFocus(id + '-edit');
}
/**
* Collect stage: edit and delete buttons for an own question. Editing swaps the item
* content for a small form in place.
*/
function qaOwnActions(item, question) {
var button = function (action, text, extraClass) {
return el('button', {
type: 'button',
class: 'button button--small button--ghost' + (extraClass || ''),
'aria-label': text + ': ' + question.text,
'data-question-id': question.id + '-' + action,
text: text
});
};
var edit = button('edit', 'Bearbeiten');
var remove = button('delete', 'Löschen', ' button--danger');
edit.addEventListener('click', function () {
qaEditing = question.id;
qaSay('', false);
var field = el('textarea', { name: 'question', rows: '3', maxlength: '500', required: '', 'aria-label': 'Deine Frage bearbeiten' });
field.value = question.text;
var form = el('form', { class: 'qa-edit' }, [
field,
el('div', { class: 'qa-edit__actions' }, [
el('button', { type: 'submit', class: 'button button--small button--primary', text: 'Speichern' }),
el('button', { type: 'button', class: 'button button--small', 'data-qa-cancel': '', text: 'Abbrechen' })
])
]);
form.addEventListener('submit', function (event) {
event.preventDefault();
var text = field.value.trim();
if (!text) {
qaSay('Bitte gib eine Frage ein.', true);
field.focus();
return;
}
if (text === question.text) {
qaStopEditing(question.id);
return;
}
sendQa({ vote: 'edit', question_id: question.id, question: text }).then(function (response) {
if (response && response.ok) {
restoreQaFocus(question.id + '-edit');
} else {
field.focus();
}
});
});
form.querySelector('[data-qa-cancel]').addEventListener('click', function () {
qaStopEditing(question.id);
});
field.addEventListener('keydown', function (event) {
if (event.key === 'Escape') {
qaStopEditing(question.id);
}
});
item.textContent = '';
item.classList.add('is-editing');
item.appendChild(form);
field.focus();
field.setSelectionRange(field.value.length, field.value.length);
});
remove.addEventListener('click', function () {
if (window.confirm('Deine Frage wirklich löschen?\n\n„' + question.text + '“')) {
sendQa({ vote: 'delete', question_id: question.id });
}
});
return el('span', { class: 'qa-own-actions' }, [edit, remove]);
}
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);
renderOwnWords(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) {
data.vote = vote;
}
postJson(voteUrl, data).then(function (response) {
var success = {
down: '✓ „' + text + '“ abgelehnt.',
remove: '✓ „' + text + '“ entfernt.'
}[vote] || '✓ „' + text + '“ ist angekommen.';
message.textContent = response.ok ? success : response.message;
message.classList.toggle('is-error', !response.ok);
if (response.ok && !vote) {
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;
});
}
// Own terms with a remove button (fix a typo by removing and entering again).
var ownWords = root.querySelector('[data-own-words]');
var ownWordsRendered = '';
function renderOwnWords(state) {
if (!ownWords || !state.words) {
return;
}
var own = state.words.own || [];
var key = JSON.stringify(own);
if (key === ownWordsRendered) {
return;
}
ownWordsRendered = key;
// Keep keyboard focus in the list after removing a term.
var hadFocus = ownWords.contains(document.activeElement);
var listNode = ownWords.querySelector('[data-own-words-list]');
listNode.textContent = '';
ownWords.hidden = own.length === 0;
own.forEach(function (word) {
var label = word.down ? 'Ablehnung von „' + word.text + '“ zurücknehmen' : '„' + word.text + '“ entfernen';
var remove = el('button', { type: 'button', class: 'own-words__remove', 'aria-label': label, title: label }, [
el('span', { 'aria-hidden': 'true', text: '×' })
]);
remove.addEventListener('click', function () {
sendWord(word.text, 'remove');
});
listNode.appendChild(el('li', { class: 'own-words__item' + (word.down ? ' is-down' : '') }, [
el('span', { text: (word.down ? '− ' : '') + word.text }),
remove
]));
});
if (hadFocus) {
var next = listNode.querySelector('button') || input;
if (next) {
next.focus();
}
}
}
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
/**
* Slide image section: dropzone (also drag and drop) while there is no image, otherwise a row with
* preview and replace/remove buttons. A newly chosen file is previewed right away. The placement
* question only shows with an image (existing and not marked for removal, or a chosen file).
* Without JavaScript the label opens the file dialog, the checkbox removes and the placement stays visible.
*/
function initImageFields(box) {
var file = box.querySelector('input[type="file"]');
var layout = box.querySelector('[data-image-layout]');
var drop = box.querySelector('[data-image-drop]');
var row = box.querySelector('[data-image-row]');
var img = box.querySelector('[data-image-figure] img');
var figure = box.querySelector('[data-image-figure]');
var info = box.querySelector('[data-image-info]');
var pick = box.querySelector('[data-image-pick]');
var button = box.querySelector('[data-image-remove-button]');
var checkbox = box.querySelector('input[name="remove_image"]');
if (!file || !layout || !drop || !row || !img || !button) {
return;
}
var hasImage = box.hasAttribute('data-has-image');
var original = img.getAttribute('data-image-original') || '';
var width = img.getAttribute('width');
var height = img.getAttribute('height');
var objectUrl = null;
// The checkbox is replaced by the button (it stays in the form and is toggled by it).
var removeBox = box.querySelector('[data-image-remove]');
if (removeBox) {
removeBox.hidden = true;
}
var extra = box.querySelector('[data-image-drop-extra]');
if (extra) {
extra.hidden = false;
}
button.hidden = false;
function formatSize(bytes) {
return bytes < 1048576 ? Math.max(1, Math.round(bytes / 1024)) + ' KB' : (bytes / 1048576).toFixed(1).replace('.', ',') + ' MB';
}
function update() {
var chosen = !!file.files && file.files.length > 0;
var removed = !!checkbox && checkbox.checked && !chosen;
if (objectUrl) {
URL.revokeObjectURL(objectUrl);
objectUrl = null;
}
if (chosen) {
objectUrl = URL.createObjectURL(file.files[0]);
img.src = objectUrl;
img.removeAttribute('width');
img.removeAttribute('height');
} else {
img.src = original;
if (width && height) {
img.setAttribute('width', width);
img.setAttribute('height', height);
}
}
var showRow = chosen || hasImage;
var focusLost = row.hidden === false && !showRow;
row.hidden = !showRow;
drop.hidden = showRow;
figure.classList.toggle('is-removed', removed);
if (info) {
info.textContent = chosen
? info.getAttribute('data-text-new') + ' ' + file.files[0].name + ' (' + formatSize(file.files[0].size) + ')'
: (removed ? info.getAttribute('data-text-removed') : (hasImage ? info.getAttribute('data-text-current') : ''));
}
if (pick) {
pick.textContent = pick.getAttribute(chosen || !hasImage ? 'data-label-choose' : 'data-label-replace');
}
button.querySelector('[data-label]').textContent = button.getAttribute(chosen ? 'data-label-discard' : (removed ? 'data-label-undo' : 'data-label-remove'));
if (!chosen && checkbox) {
button.setAttribute('aria-pressed', removed ? 'true' : 'false');
} else {
button.removeAttribute('aria-pressed');
}
layout.hidden = !chosen && !(hasImage && !removed);
if (focusLost) {
file.focus();
}
}
file.addEventListener('change', function () {
if (file.files && file.files.length > 0 && checkbox) {
// A new image replaces the old one, so "remove" no longer applies.
checkbox.checked = false;
}
update();
});
button.addEventListener('click', function () {
if (file.files && file.files.length > 0) {
file.value = '';
} else if (checkbox) {
checkbox.checked = !checkbox.checked;
}
update();
});
[drop, row].forEach(function (zone) {
zone.addEventListener('dragover', function (event) {
event.preventDefault();
zone.classList.add('is-dragover');
});
zone.addEventListener('dragleave', function () {
zone.classList.remove('is-dragover');
});
zone.addEventListener('drop', function (event) {
event.preventDefault();
zone.classList.remove('is-dragover');
var dropped = event.dataTransfer && event.dataTransfer.files;
if (!dropped || dropped.length === 0 || typeof DataTransfer === 'undefined') {
return;
}
try {
var transfer = new DataTransfer();
transfer.items.add(dropped[0]);
file.files = transfer.files;
file.dispatchEvent(new Event('change', {bubbles: true}));
} catch (e) {
// Browser without assignable file lists: the file dialog still works.
}
});
});
update();
}
/**
* Countdown music upload (admin menu): like the image dropzone, but the file is sent as soon as it is
* chosen or dropped. Without JavaScript the "Hochladen" button does it.
*/
function initAudioForm(form) {
var file = form.querySelector('input[type="file"]');
var zone = form.querySelector('[data-audio-drop]');
var submit = form.querySelector('[data-audio-submit]');
if (!file || !zone) {
return;
}
if (submit) {
submit.hidden = true;
}
var extra = form.querySelector('[data-audio-drop-extra]');
if (extra) {
extra.hidden = false;
}
function send() {
if (file.files && file.files.length > 0) {
if (form.requestSubmit) {
form.requestSubmit();
} else {
form.submit();
}
}
}
file.addEventListener('change', send);
zone.addEventListener('dragover', function (event) {
event.preventDefault();
zone.classList.add('is-dragover');
});
zone.addEventListener('dragleave', function () {
zone.classList.remove('is-dragover');
});
zone.addEventListener('drop', function (event) {
event.preventDefault();
zone.classList.remove('is-dragover');
var dropped = event.dataTransfer && event.dataTransfer.files;
if (!dropped || dropped.length === 0 || typeof DataTransfer === 'undefined') {
return;
}
try {
var transfer = new DataTransfer();
transfer.items.add(dropped[0]);
file.files = transfer.files;
send();
} catch (e) {
// Browser without assignable file lists: the file dialog still works.
}
});
}
/** 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 + '“';
});
}
// ------------------------------------------------------------------ scale style (slide form)
/**
* Stars always start at one star: hide "Von" and call "Bis" the number of stars.
* Without JS both fields stay visible and the server ignores "Von" for stars.
*/
function initScaleStyle(fieldset) {
var form = fieldset.form || fieldset.closest('form');
var min = form.querySelector('[data-scale-min]');
var max = form.querySelector('[data-label-stars]');
var maxLabel = max && form.querySelector('label[for="' + max.id + '"]');
function update() {
var checked = fieldset.querySelector('input[type=radio]:checked');
var stars = checked !== null && checked.value === 'stars';
if (min) {
min.hidden = stars;
}
if (maxLabel) {
maxLabel.textContent = max.getAttribute(stars ? 'data-label-stars' : 'data-label-numbers');
}
}
fieldset.addEventListener('change', update);
update();
}
// ------------------------------------------------------------------ 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;
}
// ------------------------------------------------------------------ admin dashboard without reloads
/**
* Loads server-rendered admin pages as fragments (layout "fragment": content + flash only)
* and merges them into the open page. The HTML comes from our own templates (escaped there);
* it is adopted as DOM nodes, never written with innerHTML.
*/
var Fragments = {
request: function (url, options) {
options = options || {};
return fetch(url, {
method: options.method || 'GET',
body: options.body,
credentials: 'same-origin',
cache: 'no-store',
headers: { Accept: 'text/html', 'X-Fragment': '1', 'X-CSRF-Token': csrfToken() }
}).then(function (response) {
if (!response.ok) {
throw new Error('HTTP ' + response.status);
}
return response.text();
}).then(function (html) {
return new DOMParser().parseFromString(html, 'text/html');
});
},
/** Replaces the [data-refresh] regions (all, or only `names`) with those of `doc`. */
apply: function (doc, names) {
doc.querySelectorAll('[data-refresh]').forEach(function (fresh) {
var name = fresh.getAttribute('data-refresh');
var old = document.querySelector('[data-refresh="' + name + '"]');
if (!old || (names && names.indexOf(name) < 0)) {
return;
}
var node = document.importNode(fresh, true);
old.replaceWith(node);
initWidgets(node);
});
},
/** Shows an error where the user is looking (dialog or flash area). */
fail: function (container, text) {
var message = el('div', { class: 'message error', role: 'alert', 'data-dismiss': '', text: text });
container.insertBefore(message, container.firstChild);
}
};
function initAdminDashboard() {
var dialog = document.querySelector('[data-modal-dialog]');
var body = dialog ? dialog.querySelector('[data-modal-body]') : null;
var dirty = false;
var focusId = null;
function flashArea() {
return document.querySelector('[data-refresh="flash"]') || document.body;
}
/** Keeps the keyboard position after a list refresh: same button, else the slide, else the next slide. */
function restoreFocus(target) {
if (!target) {
return;
}
var item = target.id ? document.querySelector('[data-slide-id="' + target.id + '"]') : null;
var node = null;
if (item) {
node = (target.action && item.querySelector('form[action="' + target.action + '"] button'))
|| item.querySelector('.slide-item__title');
} else if (target.nextId) {
node = document.querySelector('[data-slide-id="' + target.nextId + '"] .slide-item__title');
}
if (node) {
node.focus();
}
}
function currentSlideId() {
var current = document.querySelector('.slide-item--current');
return current ? current.getAttribute('data-slide-id') : null;
}
/** Scrolls the live slide into view if it is outside (no movement if it is already visible). */
function revealCurrent() {
var current = document.querySelector('.slide-item--current');
if (current) {
var calm = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
current.scrollIntoView({ block: 'nearest', behavior: calm ? 'auto' : 'smooth' });
}
}
function refreshList() {
return Fragments.request(window.location.href).then(function (doc) {
Fragments.apply(doc, ['head', 'slides']);
});
}
// The presenter (other window, clicker) moves the live marker: poll a cheap fingerprint
// and reload the lists when it changes. Own actions already refresh, so they skip one round.
var liveRoot = document.querySelector('[data-dashboard-live]');
var liveVersion = null;
if (liveRoot) {
poll(function () {
if ((dialog && dialog.open) || document.querySelector('[data-live] [aria-busy], .slide-item--dragging')) {
return null; // never replace the DOM under a dialog, a pending request or a drag
}
return getJson(liveRoot.getAttribute('data-dashboard-live')).then(function (state) {
var previous = liveVersion;
liveVersion = state.version;
if (previous === null || previous === state.version) {
return null;
}
var active = document.activeElement;
var item = active && active.closest ? active.closest('[data-slide-id]') : null;
var form = active && active.closest ? active.closest('form') : null;
var next = item ? item.nextElementSibling : null;
var target = item ? {
id: item.getAttribute('data-slide-id'),
action: form ? form.getAttribute('action') : null,
nextId: next ? next.getAttribute('data-slide-id') : null
} : null;
var liveBefore = currentSlideId();
return refreshList().then(function () {
restoreFocus(target);
// The presenter moved on: keep the live slide in view on long lists.
if (currentSlideId() !== liveBefore) {
revealCurrent();
}
});
});
}, Math.max(4000, parseInt(liveRoot.getAttribute('data-interval'), 10) * 2 || 4000));
}
function openModal(doc) {
var content = doc.querySelector('[data-modal-content]');
var flash = doc.querySelector('[data-refresh="flash"]');
body.replaceChildren();
if (flash && flash.childNodes.length) {
// Shown inside the dialog (validation errors), not as flash of the page behind it.
var notes = document.importNode(flash, true);
notes.removeAttribute('data-refresh');
body.appendChild(notes);
}
body.appendChild(document.importNode(content, true));
initWidgets(body);
dirty = false;
if (!dialog.open) {
dialog.showModal();
}
dialog.querySelector('[data-modal-panel]').scrollTop = 0;
}
function requestClose() {
if (dirty && !window.confirm('Änderungen verwerfen?')) {
return;
}
dialog.close();
}
/** Result of a POST: either the dashboard (done) or a form (open in the dialog). */
function handle(doc, source) {
if (doc.querySelector('[data-modal-content]')) {
// A form: validation errors (dialog stays open) or the copy of a duplicated slide.
var wasOpen = dialog.open;
openModal(doc);
return wasOpen ? null : refreshList();
}
Fragments.apply(doc);
liveVersion = null; // the next poll only takes the new fingerprint
if (dialog && dialog.open) {
dirty = false;
dialog.close();
}
restoreFocus(source);
return null;
}
document.addEventListener('submit', function (event) {
var form = event.target;
var submitter = event.submitter || form.querySelector('button[type=submit], button:not([type])');
var confirmText = submitter && submitter.getAttribute('data-confirm');
if (confirmText && !window.confirm(confirmText)) {
event.preventDefault();
return;
}
var inDialog = dialog !== null && dialog.contains(form);
if (!inDialog && !form.closest('[data-live]')) {
return; // plain form: normal navigation
}
event.preventDefault();
if (form.hasAttribute('aria-busy')) {
return;
}
var item = form.closest('[data-slide-id]');
var next = item ? item.nextElementSibling : null;
var source = inDialog ? { id: focusId } : {
id: item ? item.getAttribute('data-slide-id') : null,
action: form.getAttribute('action'),
nextId: next ? next.getAttribute('data-slide-id') : null
};
form.setAttribute('aria-busy', 'true');
if (submitter) {
submitter.disabled = true;
}
// getAttribute: forms with a field named "action" (play/pause buttons) shadow the form.action property.
Fragments.request(form.getAttribute('action'), { method: 'POST', body: new FormData(form) })
.then(function (doc) { return handle(doc, source); })
.catch(function () {
form.removeAttribute('aria-busy');
if (submitter) {
submitter.disabled = false;
}
Fragments.fail(inDialog ? body : flashArea(), 'Das hat nicht geklappt. Bitte lade die Seite neu und versuche es noch einmal.');
});
});
if (!dialog) {
return;
}
document.addEventListener('click', function (event) {
var link = event.target.closest ? event.target.closest('a[data-modal]') : null;
if (!link || event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) {
return;
}
event.preventDefault();
var item = link.closest('[data-slide-id]');
focusId = item ? item.getAttribute('data-slide-id') : null;
Fragments.request(link.href).then(openModal).catch(function () {
window.location.href = link.href; // no dialog possible: open the page as usual
});
});
dialog.addEventListener('click', function (event) {
if (event.target.closest('[data-modal-close]')) {
event.preventDefault();
requestClose();
}
});
// Only a click that starts and ends on the backdrop closes (not a text selection dragged outside).
var pressedOnBackdrop = false;
dialog.addEventListener('mousedown', function (event) { pressedOnBackdrop = event.target === dialog; });
dialog.addEventListener('click', function (event) {
if (event.target === dialog && pressedOnBackdrop) {
requestClose();
}
});
dialog.addEventListener('cancel', function (event) {
if (dirty && !window.confirm('Änderungen verwerfen?')) {
event.preventDefault();
}
});
dialog.addEventListener('close', function () {
body.replaceChildren();
dirty = false;
});
body.addEventListener('input', function () { dirty = true; });
body.addEventListener('change', function () { dirty = true; });
}
// ------------------------------------------------------------------ boot
/** Initialises the widgets inside `root` (the whole page at boot, or a freshly inserted fragment). */
function initWidgets(root) {
initCopy(root);
root.querySelectorAll('[data-youtube-form]').forEach(initYouTubeForm);
root.querySelectorAll('[data-quiz-options]').forEach(initQuizOptions);
root.querySelectorAll('[data-image-fields]').forEach(initImageFields);
root.querySelectorAll('[data-audio-form]').forEach(initAudioForm);
root.querySelectorAll('[data-sortable]').forEach(initSortable);
root.querySelectorAll('[data-order-options]').forEach(initOrderOptions);
root.querySelectorAll('[data-scale-style]').forEach(initScaleStyle);
}
// Flash messages: click hides them (delegated, no inline handlers because of the CSP).
document.addEventListener('click', function (event) {
var message = event.target.closest ? event.target.closest('[data-dismiss]') : null;
if (message) {
message.classList.add('hidden');
}
});
// Collapsible dashboard cards (<details class="collapsible">): in-page links like #export open their closed card.
function openCollapsible(hash) {
var target = hash && hash.length > 1 ? document.getElementById(decodeURIComponent(hash.slice(1))) : null;
var card = target && target.closest ? target.closest('details.collapsible') : null;
if (card && !card.open) {
card.open = true;
}
}
document.addEventListener('click', function (event) {
var link = event.target.closest ? event.target.closest('a[href^="#"]') : null;
if (link) {
openCollapsible(link.getAttribute('href'));
}
});
window.addEventListener('hashchange', function () { openCollapsible(window.location.hash); });
openCollapsible(window.location.hash);
// Split button menus ([data-menu-toggle] + [data-menu]). Delegated: the dashboard head is replaced on live refresh.
function closeMenus(except) {
document.querySelectorAll('[data-menu]').forEach(function (menu) {
var toggle = menu.parentNode.querySelector('[data-menu-toggle]');
if (!menu.hidden && menu !== except) {
menu.hidden = true;
toggle.setAttribute('aria-expanded', 'false');
}
});
}
document.addEventListener('click', function (event) {
var toggle = event.target.closest ? event.target.closest('[data-menu-toggle]') : null;
if (!toggle) {
closeMenus(null); // outside click or a click on a menu item
return;
}
var menu = toggle.parentNode.querySelector('[data-menu]');
closeMenus(menu);
menu.hidden = !menu.hidden;
toggle.setAttribute('aria-expanded', menu.hidden ? 'false' : 'true');
if (!menu.hidden) {
var first = menu.querySelector('a, button');
if (first) {
first.focus();
}
}
});
document.addEventListener('keydown', function (event) {
if (event.key !== 'Escape') {
return;
}
var open = document.querySelector('[data-menu]:not([hidden])');
if (open) {
closeMenus(null);
open.parentNode.querySelector('[data-menu-toggle]').focus();
}
});
// Admin menu drawer: below 900px the sidebar slides in from the right (CSS), opened by the header button.
// Without JS the button stays hidden and the sidebar remains a normal block below the slides.
function initDrawer() {
var toggle = document.querySelector('[data-drawer-toggle]');
var drawer = toggle ? document.getElementById(toggle.getAttribute('aria-controls')) : null;
if (!toggle || !drawer) {
return;
}
var root = document.body;
drawer.classList.add('sidebar--drawer');
toggle.hidden = false;
function setOpen(open) {
root.classList.toggle('drawer-open', open);
toggle.setAttribute('aria-expanded', open ? 'true' : 'false');
if (open) {
var close = drawer.querySelector('[data-drawer-close]');
if (close) {
close.focus();
}
}
}
toggle.addEventListener('click', function () {
setOpen(!root.classList.contains('drawer-open'));
});
document.addEventListener('click', function (event) {
var target = event.target.closest ? event.target.closest('[data-drawer-close], a[href^="#"]') : null;
if (target && root.classList.contains('drawer-open') && (target.hasAttribute('data-drawer-close') || drawer.contains(target))) {
setOpen(false);
}
});
document.addEventListener('keydown', function (event) {
if (event.key === 'Escape' && root.classList.contains('drawer-open') && !document.querySelector('dialog[open]')) {
setOpen(false);
toggle.focus();
}
});
// Back to a wide screen: the sidebar is a normal column again.
window.addEventListener('resize', function () {
if (window.innerWidth > 900 && root.classList.contains('drawer-open')) {
setOpen(false);
}
});
}
document.addEventListener('DOMContentLoaded', function () {
document.querySelectorAll('[data-theme-switch]').forEach(initThemeSwitch);
initWidgets(document);
initShare();
initDrawer();
initQrDownload();
initAdminDashboard();
document.querySelectorAll('[data-presenter]').forEach(initPresenter);
document.querySelectorAll('[data-participant]').forEach(initParticipant);
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 };
})();