Show the average as a large figure with the number of ratings and a gauge marking its position between min and max; highlight the column closest to the average. Larger sizing on the presenter stage. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
809 lines
33 KiB
JavaScript
809 lines
33 KiB
JavaScript
/**
|
||
* Plenario frontend – plain JavaScript, no build step, no dependencies.
|
||
*
|
||
* Modules (auto-initialised by data attributes):
|
||
* - [data-copy] copy the value of the sibling [data-copy-source]
|
||
* - [data-presenter] presenter screen, polls /admin/{token}/state
|
||
* - [data-participant] participant page, polls /p/{code}/state
|
||
*
|
||
* Results JSON shape: see src/Service/ResultsService.php
|
||
*/
|
||
(function () {
|
||
'use strict';
|
||
|
||
// ------------------------------------------------------------------ helpers
|
||
|
||
function el(tag, attrs, children) {
|
||
var node = document.createElement(tag);
|
||
Object.keys(attrs || {}).forEach(function (key) {
|
||
if (key === 'text') {
|
||
node.textContent = attrs[key];
|
||
} else if (key === 'style') {
|
||
node.setAttribute('style', attrs[key]);
|
||
} else {
|
||
node.setAttribute(key, attrs[key]);
|
||
}
|
||
});
|
||
(children || []).forEach(function (child) {
|
||
if (child) {
|
||
node.appendChild(child);
|
||
}
|
||
});
|
||
return node;
|
||
}
|
||
|
||
function csrfToken() {
|
||
var meta = document.querySelector('meta[name="csrf-token"]');
|
||
return meta ? meta.getAttribute('content') : '';
|
||
}
|
||
|
||
function getJson(url) {
|
||
return fetch(url, {
|
||
headers: { Accept: 'application/json' },
|
||
credentials: 'same-origin',
|
||
cache: 'no-store'
|
||
}).then(function (response) {
|
||
if (!response.ok) {
|
||
throw new Error('HTTP ' + response.status);
|
||
}
|
||
return response.json();
|
||
});
|
||
}
|
||
|
||
function postJson(url, data) {
|
||
var body = new FormData();
|
||
Object.keys(data).forEach(function (key) {
|
||
body.append(key, data[key]);
|
||
});
|
||
return fetch(url, {
|
||
method: 'POST',
|
||
body: body,
|
||
credentials: 'same-origin',
|
||
headers: {
|
||
Accept: 'application/json',
|
||
'X-Requested-With': 'XMLHttpRequest',
|
||
'X-CSRF-Token': csrfToken()
|
||
}
|
||
}).then(function (response) {
|
||
if (!response.ok) {
|
||
throw new Error('HTTP ' + response.status);
|
||
}
|
||
return response.json();
|
||
});
|
||
}
|
||
|
||
/** Polls `fn` every `interval` ms, pauses while the tab is hidden. */
|
||
function poll(fn, interval) {
|
||
var timer = null;
|
||
function tick() {
|
||
Promise.resolve(fn()).catch(function () { /* retry next tick */ }).then(schedule);
|
||
}
|
||
function schedule() {
|
||
clearTimeout(timer);
|
||
timer = setTimeout(tick, document.hidden ? interval * 5 : interval);
|
||
}
|
||
document.addEventListener('visibilitychange', function () {
|
||
if (!document.hidden) {
|
||
tick();
|
||
}
|
||
});
|
||
tick();
|
||
return { now: tick };
|
||
}
|
||
|
||
function formatNumber(value) {
|
||
return Number(value).toLocaleString('de-DE');
|
||
}
|
||
|
||
// ------------------------------------------------------------------ word matching
|
||
|
||
/**
|
||
* Suggestions for the word cloud input: prefix/substring matches, small
|
||
* typos (Levenshtein) and similar sounding words (Kölner Phonetik).
|
||
*/
|
||
var Words = {
|
||
/** Lower case, umlauts folded, accents and non-alphanumerics removed. */
|
||
fold: function (text) {
|
||
return String(text).toLowerCase()
|
||
.replace(/ä/g, 'ae').replace(/ö/g, 'oe').replace(/ü/g, 'ue').replace(/ß/g, 'ss')
|
||
.normalize('NFD').replace(/[̀-ͯ]/g, '')
|
||
.replace(/[^a-z0-9]/g, '');
|
||
},
|
||
|
||
/** Kölner Phonetik – phonetic code for German words. */
|
||
phonetic: function (text) {
|
||
var s = String(text).toUpperCase()
|
||
.replace(/Ä/g, 'A').replace(/Ö/g, 'O').replace(/Ü/g, 'U').replace(/ß/g, 'S')
|
||
.normalize('NFD').replace(/[̀-ͯ]/g, '')
|
||
.replace(/[^A-Z]/g, '');
|
||
var codes = '';
|
||
for (var i = 0; i < s.length; i++) {
|
||
var c = s[i];
|
||
var prev = i > 0 ? s[i - 1] : '';
|
||
var next = s[i + 1] || '';
|
||
var code = '';
|
||
if ('AEIJOUY'.indexOf(c) >= 0) {
|
||
code = '0';
|
||
} else if (c === 'B') {
|
||
code = '1';
|
||
} else if (c === 'P') {
|
||
code = next === 'H' ? '3' : '1';
|
||
} else if (c === 'D' || c === 'T') {
|
||
code = next && 'CSZ'.indexOf(next) >= 0 ? '8' : '2';
|
||
} else if ('FVW'.indexOf(c) >= 0) {
|
||
code = '3';
|
||
} else if ('GKQ'.indexOf(c) >= 0) {
|
||
code = '4';
|
||
} else if (c === 'C') {
|
||
if (i === 0) {
|
||
code = next && 'AHKLOQRUX'.indexOf(next) >= 0 ? '4' : '8';
|
||
} else {
|
||
code = next && 'AHKOQUX'.indexOf(next) >= 0 && 'SZ'.indexOf(prev) < 0 ? '4' : '8';
|
||
}
|
||
} else if (c === 'X') {
|
||
code = prev && 'CKQ'.indexOf(prev) >= 0 ? '8' : '48';
|
||
} else if (c === 'L') {
|
||
code = '5';
|
||
} else if (c === 'M' || c === 'N') {
|
||
code = '6';
|
||
} else if (c === 'R') {
|
||
code = '7';
|
||
} else if (c === 'S' || c === 'Z') {
|
||
code = '8';
|
||
}
|
||
// H and anything else: no code
|
||
codes += code;
|
||
}
|
||
var collapsed = '';
|
||
for (var j = 0; j < codes.length; j++) {
|
||
if (codes[j] !== collapsed[collapsed.length - 1]) {
|
||
collapsed += codes[j];
|
||
}
|
||
}
|
||
return collapsed.charAt(0) + collapsed.slice(1).replace(/0/g, '');
|
||
},
|
||
|
||
levenshtein: function (a, b) {
|
||
if (a === b) {
|
||
return 0;
|
||
}
|
||
var row = [];
|
||
for (var j = 0; j <= b.length; j++) {
|
||
row.push(j);
|
||
}
|
||
for (var i = 1; i <= a.length; i++) {
|
||
var diag = row[0];
|
||
row[0] = i;
|
||
for (var k = 1; k <= b.length; k++) {
|
||
var tmp = row[k];
|
||
row[k] = Math.min(row[k] + 1, row[k - 1] + 1, diag + (a[i - 1] === b[k - 1] ? 0 : 1));
|
||
diag = tmp;
|
||
}
|
||
}
|
||
return row[b.length];
|
||
},
|
||
|
||
/** Score 0 (no match) .. 100 (same word). */
|
||
score: function (input, word) {
|
||
var a = Words.fold(input);
|
||
var b = Words.fold(word);
|
||
if (!a || !b) {
|
||
return 0;
|
||
}
|
||
if (a === b) {
|
||
return 100;
|
||
}
|
||
if (b.indexOf(a) === 0) {
|
||
return 90 - Math.min(20, b.length - a.length);
|
||
}
|
||
var pa = Words.phonetic(input);
|
||
var pb = Words.phonetic(word);
|
||
if (a.length >= 3 && pa && pa === pb) {
|
||
return 70;
|
||
}
|
||
var tolerance = a.length >= 8 ? 2 : (a.length >= 4 ? 1 : 0);
|
||
if (tolerance && Words.levenshtein(a, b) <= tolerance) {
|
||
return 65;
|
||
}
|
||
if (a.length >= 3 && b.indexOf(a) > 0) {
|
||
return 60;
|
||
}
|
||
// Typo within what has been typed so far ("Kafe" → "Kaffeemaschine").
|
||
if (tolerance && b.length > a.length && Words.levenshtein(a, b.slice(0, a.length)) <= tolerance) {
|
||
return 50;
|
||
}
|
||
if (a.length >= 4 && pa.length >= 3 && pb.indexOf(pa) === 0) {
|
||
return 45;
|
||
}
|
||
return 0;
|
||
},
|
||
|
||
/** Matching existing cloud words ({key, text, count}) for an input, best first; optional limit. */
|
||
suggest: function (input, words, limit) {
|
||
if (Words.fold(input).length < 2) {
|
||
return [];
|
||
}
|
||
return words
|
||
.map(function (word) { return { word: word, score: Words.score(input, word.text) }; })
|
||
.filter(function (item) { return item.score > 0; })
|
||
.sort(function (x, y) { return y.score - x.score || y.word.count - x.word.count; })
|
||
.slice(0, limit || undefined)
|
||
.map(function (item) { return item.word; });
|
||
}
|
||
};
|
||
|
||
// ------------------------------------------------------------------ results
|
||
|
||
var Results = {
|
||
/**
|
||
* @param {Object} [options] renderer specific; wordcloud: {mine: [keys], onUpvote: fn(word)|null}
|
||
*/
|
||
render: function (container, results, options) {
|
||
container.innerHTML = '';
|
||
if (!results) {
|
||
return;
|
||
}
|
||
var renderer = Results[results.type];
|
||
if (typeof renderer !== 'function') {
|
||
return;
|
||
}
|
||
if (results.participants === 0) {
|
||
container.appendChild(el('p', { class: 'results-empty', text: 'Noch keine Antworten' }));
|
||
return;
|
||
}
|
||
container.appendChild(renderer(results, options || {}));
|
||
},
|
||
|
||
choice: function (results) {
|
||
var max = Math.max.apply(null, results.options.map(function (o) { return o.count; }).concat([1]));
|
||
return el('div', { class: 'bars' }, results.options.map(function (option, index) {
|
||
return el('div', { class: 'bar bar--c' + (index % 6) }, [
|
||
el('div', { class: 'bar__label', text: option.label }),
|
||
el('div', { class: 'bar__track' }, [
|
||
el('div', { class: 'bar__fill', style: 'width:' + (option.count / max * 100) + '%' })
|
||
]),
|
||
el('div', { class: 'bar__value', text: formatNumber(option.percent) + ' % (' + option.count + ')' })
|
||
]);
|
||
}));
|
||
},
|
||
|
||
scale: function (results) {
|
||
var max = Math.max.apply(null, results.buckets.map(function (b) { return b.count; }).concat([1]));
|
||
var total = results.buckets.reduce(function (sum, b) { return sum + b.count; }, 0);
|
||
var hasAverage = results.average !== null;
|
||
var nearest = hasAverage ? Math.round(results.average) : null;
|
||
var columns = el('div', { class: 'columns' }, results.buckets.map(function (bucket) {
|
||
return el('div', { class: 'column' + (bucket.value === nearest ? ' column--avg' : '') }, [
|
||
el('div', { class: 'column__count', text: String(bucket.count) }),
|
||
el('div', { class: 'column__track' }, [
|
||
el('div', { class: 'column__fill', style: 'height:' + (bucket.count / max * 100) + '%' })
|
||
]),
|
||
el('div', { class: 'column__label', text: String(bucket.value) })
|
||
]);
|
||
}));
|
||
var labels = el('div', { class: 'scale__labels' }, [
|
||
el('span', { text: results.minLabel || '' }),
|
||
el('span', { text: results.maxLabel || '' })
|
||
]);
|
||
var averageText = hasAverage
|
||
? Number(results.average).toLocaleString('de-DE', { minimumFractionDigits: 1, maximumFractionDigits: 1 })
|
||
: '–';
|
||
var span = results.max - results.min;
|
||
var position = hasAverage && span > 0 ? (results.average - results.min) / span * 100 : 50;
|
||
var gauge = el('div', {
|
||
class: 'average__gauge',
|
||
role: 'img',
|
||
'aria-label': 'Durchschnitt ' + averageText + ' auf einer Skala von ' + results.min + ' bis ' + results.max
|
||
}, [
|
||
el('div', { class: 'average__track' }, [
|
||
hasAverage ? el('div', { class: 'average__marker', style: 'left:' + position + '%' }) : null
|
||
]),
|
||
el('div', { class: 'average__ends' }, [
|
||
el('span', { text: String(results.min) }),
|
||
el('span', { text: String(results.max) })
|
||
])
|
||
]);
|
||
var average = el('div', { class: 'average' }, [
|
||
el('div', { class: 'average__figure' }, [
|
||
el('span', { class: 'average__label', text: 'Durchschnitt' }),
|
||
el('span', { class: 'average__value' }, [
|
||
el('strong', { text: averageText }),
|
||
el('span', { class: 'average__of', text: ' / ' + results.max })
|
||
]),
|
||
el('span', { class: 'average__count', text: total + (total === 1 ? ' Bewertung' : ' Bewertungen') })
|
||
]),
|
||
gauge
|
||
]);
|
||
return el('div', { class: 'scale-results' }, [average, columns, labels]);
|
||
},
|
||
|
||
/**
|
||
* options: {mine: [keys], down: [keys], onUpvote: fn(word)|null, onDownvote: fn(word)|null}
|
||
* Counts are shown as "+up" and "−down" (down only when > 0 or clickable).
|
||
*/
|
||
wordcloud: function (results, options) {
|
||
var mine = (options && options.mine) || [];
|
||
var down = (options && options.down) || [];
|
||
var onUpvote = options && options.onUpvote;
|
||
var onDownvote = options && options.onDownvote;
|
||
// Interleave big and small words so the biggest ends up in the middle.
|
||
var words = results.words.slice();
|
||
var ordered = [];
|
||
words.forEach(function (word, index) {
|
||
if (index % 2 === 0) {
|
||
ordered.push(word);
|
||
} else {
|
||
ordered.unshift(word);
|
||
}
|
||
});
|
||
return el('div', { class: 'cloud' + (onUpvote ? ' cloud--interactive' : '') }, ordered.map(function (word, index) {
|
||
var size = 0.9 + word.weight * 2.6;
|
||
var isMine = mine.indexOf(word.key) >= 0;
|
||
var isDown = down.indexOf(word.key) >= 0;
|
||
var rated = isMine || isDown;
|
||
var downCount = word.down || 0;
|
||
var attrs = {
|
||
class: 'cloud__word cloud__word--c' + (index % 6) + (isMine ? ' is-mine' : '') + (isDown ? ' is-down' : ''),
|
||
style: 'font-size:' + size.toFixed(2) + 'em',
|
||
title: '+' + word.count + ' / −' + downCount
|
||
+ (isMine ? ' – von dir genannt' : (isDown ? ' – von dir abgelehnt' : ''))
|
||
};
|
||
if (!onUpvote) {
|
||
// Presenter (and participants without upvotes): show the counts next to the word.
|
||
return el('span', attrs, [
|
||
el('span', { text: word.text }),
|
||
el('span', { class: 'cloud__count cloud__count--up', text: '+' + word.count }),
|
||
downCount > 0 ? el('span', { class: 'cloud__count cloud__count--down', text: '−' + downCount }) : null
|
||
]);
|
||
}
|
||
|
||
var up = el('button', {
|
||
type: 'button',
|
||
class: 'cloud__vote cloud__vote--up',
|
||
'aria-pressed': isMine ? 'true' : 'false',
|
||
'aria-label': word.text + ', ' + word.count + ' Stimmen'
|
||
+ (isMine ? ', von dir genannt' : (isDown ? '' : ', unterstützen'))
|
||
}, [
|
||
el('span', { text: word.text }),
|
||
el('span', { class: 'cloud__count cloud__count--up', 'aria-hidden': 'true', text: (isMine ? '✓ ' : '+') + word.count })
|
||
]);
|
||
up.disabled = rated;
|
||
if (!rated) {
|
||
up.addEventListener('click', function () { onUpvote(word); });
|
||
}
|
||
|
||
var downEl = null;
|
||
if (onDownvote) {
|
||
downEl = el('button', {
|
||
type: 'button',
|
||
class: 'cloud__vote cloud__vote--down',
|
||
'aria-pressed': isDown ? 'true' : 'false',
|
||
'aria-label': word.text + ', ' + downCount + ' Ablehnungen'
|
||
+ (isDown ? ', von dir abgelehnt' : (isMine ? '' : ', ablehnen'))
|
||
}, [
|
||
el('span', { class: 'cloud__count cloud__count--down', 'aria-hidden': 'true', text: (isDown ? '✓ ' : '') + '−' + downCount })
|
||
]);
|
||
downEl.disabled = rated;
|
||
if (!rated) {
|
||
downEl.addEventListener('click', function () { onDownvote(word); });
|
||
}
|
||
} else if (downCount > 0) {
|
||
downEl = el('span', { class: 'cloud__count cloud__count--down', text: '−' + downCount });
|
||
}
|
||
return el('span', attrs, [up, downEl]);
|
||
}));
|
||
},
|
||
|
||
open: function (results) {
|
||
return el('ul', { class: 'answers' }, results.answers.map(function (answer) {
|
||
return el('li', { class: 'answer', text: answer.text });
|
||
}));
|
||
}
|
||
};
|
||
|
||
// ------------------------------------------------------------------ copy
|
||
|
||
function initCopy() {
|
||
document.querySelectorAll('[data-copy]').forEach(function (button) {
|
||
button.addEventListener('click', function () {
|
||
var source = button.parentNode.querySelector('[data-copy-source]');
|
||
if (!source) {
|
||
return;
|
||
}
|
||
source.select();
|
||
var done = function () {
|
||
var label = button.textContent;
|
||
button.textContent = 'Kopiert ✓';
|
||
setTimeout(function () { button.textContent = label; }, 1500);
|
||
};
|
||
if (navigator.clipboard) {
|
||
navigator.clipboard.writeText(source.value).then(done, function () {
|
||
document.execCommand('copy');
|
||
done();
|
||
});
|
||
} else {
|
||
document.execCommand('copy');
|
||
done();
|
||
}
|
||
});
|
||
});
|
||
}
|
||
|
||
// ------------------------------------------------------------------ presenter
|
||
|
||
function initPresenter(root) {
|
||
var stateUrl = root.getAttribute('data-state-url');
|
||
var controlUrl = root.getAttribute('data-control-url');
|
||
var interval = parseInt(root.getAttribute('data-interval'), 10) || 2000;
|
||
var q = function (selector) { return root.querySelector(selector); };
|
||
var last = '';
|
||
var hideResults = false;
|
||
var state = null;
|
||
|
||
function render(newState) {
|
||
var serialized = JSON.stringify(newState);
|
||
if (serialized === last) {
|
||
return;
|
||
}
|
||
last = serialized;
|
||
state = newState;
|
||
var slide = state.slide;
|
||
|
||
q('[data-counter]').textContent = state.count === 0
|
||
? '0 / 0'
|
||
: (state.index === null ? '–' : state.index + 1) + ' / ' + state.count;
|
||
|
||
if (!slide) {
|
||
q('[data-type]').textContent = '';
|
||
q('[data-question]').textContent = state.count === 0
|
||
? 'Noch keine Folien angelegt'
|
||
: state.poll.title;
|
||
q('[data-description]').textContent = state.count === 0
|
||
? 'Lege in der Verwaltung Fragen an.'
|
||
: 'Drücke → um zu starten.';
|
||
q('[data-results]').innerHTML = '';
|
||
q('[data-voting]').hidden = true;
|
||
q('[data-participants]').textContent = '';
|
||
return;
|
||
}
|
||
|
||
q('[data-type]').textContent = slide.typeLabel;
|
||
q('[data-question]').textContent = slide.question;
|
||
q('[data-description]').textContent = slide.description;
|
||
root.classList.toggle('stage--content', !slide.isInteractive);
|
||
root.classList.toggle('stage--closed', slide.isInteractive && !slide.isVotingOpen);
|
||
|
||
var voting = q('[data-voting]');
|
||
voting.hidden = !slide.isInteractive;
|
||
voting.textContent = slide.isVotingOpen ? 'Abstimmung schließen' : 'Abstimmung öffnen';
|
||
|
||
q('[data-participants]').textContent = slide.isInteractive
|
||
? state.results.participants + ' ' + (state.results.participants === 1 ? 'Antwort' : 'Antworten')
|
||
: '';
|
||
|
||
var container = q('[data-results]');
|
||
container.classList.toggle('is-hidden', hideResults);
|
||
Results.render(container, slide.isInteractive ? state.results : null);
|
||
}
|
||
|
||
function refresh() {
|
||
return getJson(stateUrl).then(render);
|
||
}
|
||
|
||
function control(action, extra) {
|
||
var data = Object.assign({ action: action }, extra || {});
|
||
return postJson(controlUrl, data).then(render).catch(function () { /* next poll fixes it */ });
|
||
}
|
||
|
||
root.querySelectorAll('[data-action]').forEach(function (button) {
|
||
button.addEventListener('click', function () {
|
||
control(button.getAttribute('data-action'));
|
||
});
|
||
});
|
||
|
||
function toggleHide() {
|
||
hideResults = !hideResults;
|
||
q('[data-results]').classList.toggle('is-hidden', hideResults);
|
||
q('[data-hide-results]').textContent = hideResults ? 'Ergebnisse zeigen' : 'Ergebnisse verbergen';
|
||
}
|
||
q('[data-hide-results]').addEventListener('click', toggleHide);
|
||
|
||
function toggleFullscreen() {
|
||
if (!document.fullscreenElement) {
|
||
(document.documentElement.requestFullscreen || function () {}).call(document.documentElement);
|
||
} else if (document.exitFullscreen) {
|
||
document.exitFullscreen();
|
||
}
|
||
}
|
||
q('[data-fullscreen]').addEventListener('click', toggleFullscreen);
|
||
|
||
var overlay = q('[data-qr-overlay]');
|
||
function toggleQr() {
|
||
overlay.hidden = !overlay.hidden;
|
||
}
|
||
q('[data-qr-toggle]').addEventListener('click', toggleQr);
|
||
overlay.addEventListener('click', toggleQr);
|
||
|
||
document.addEventListener('keydown', function (event) {
|
||
if (event.target.closest('input, textarea, select')) {
|
||
return;
|
||
}
|
||
switch (event.key) {
|
||
case 'ArrowRight':
|
||
case 'PageDown':
|
||
case ' ':
|
||
event.preventDefault();
|
||
control('next');
|
||
break;
|
||
case 'ArrowLeft':
|
||
case 'PageUp':
|
||
event.preventDefault();
|
||
control('prev');
|
||
break;
|
||
case 'v':
|
||
case 'V':
|
||
if (state && state.slide && state.slide.isInteractive) {
|
||
control('toggle');
|
||
}
|
||
break;
|
||
case 'h':
|
||
case 'H':
|
||
toggleHide();
|
||
break;
|
||
case 'f':
|
||
case 'F':
|
||
toggleFullscreen();
|
||
break;
|
||
case 'q':
|
||
case 'Q':
|
||
toggleQr();
|
||
break;
|
||
case 'Escape':
|
||
overlay.hidden = true;
|
||
break;
|
||
}
|
||
});
|
||
|
||
poll(refresh, interval);
|
||
}
|
||
|
||
// ------------------------------------------------------------------ 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 && !state.words.limitReached);
|
||
}
|
||
|
||
function renderResults(state) {
|
||
current = state;
|
||
if (!card || !container) {
|
||
return;
|
||
}
|
||
var upvote = canUpvote(state);
|
||
var key = JSON.stringify([state.results, state.words, upvote]);
|
||
if (key === lastRendered) {
|
||
return;
|
||
}
|
||
lastRendered = key;
|
||
card.hidden = !state.results;
|
||
var hint = root.querySelector('[data-upvote-hint]');
|
||
if (hint) {
|
||
hint.hidden = !upvote;
|
||
}
|
||
Results.render(container, state.results, {
|
||
mine: state.words ? state.words.mine : [],
|
||
down: state.words ? state.words.down : [],
|
||
onUpvote: upvote ? function (word) { sendWord(word.text); } : null,
|
||
onDownvote: upvote && state.words.allowDownvotes ? function (word) { sendWord(word.text, 'down'); } : null
|
||
});
|
||
}
|
||
|
||
// --- word cloud: one word per submit, suggestions, upvotes ----------
|
||
var input = wordForm ? wordForm.querySelector('[data-word-input]') : null;
|
||
var list = wordForm ? wordForm.querySelector('[data-suggestions]') : null;
|
||
var message = wordForm ? wordForm.querySelector('[data-word-message]') : null;
|
||
var matches = [];
|
||
var activeIndex = -1;
|
||
var sending = false;
|
||
|
||
function isMine(word) {
|
||
return !!(current && current.words && current.words.mine.indexOf(word.key) >= 0);
|
||
}
|
||
|
||
function isDown(word) {
|
||
return !!(current && current.words && current.words.down.indexOf(word.key) >= 0);
|
||
}
|
||
|
||
function sendWord(text, vote) {
|
||
if (!wordForm || sending) {
|
||
return;
|
||
}
|
||
sending = true;
|
||
var slideId = wordForm.querySelector('[name=slide_id]').value;
|
||
var data = { slide_id: slideId, word: text };
|
||
if (vote === 'down') {
|
||
data.vote = 'down';
|
||
}
|
||
postJson(voteUrl, data).then(function (response) {
|
||
var success = vote === 'down' ? '✓ „' + text + '“ abgelehnt.' : '✓ „' + text + '“ ist angekommen.';
|
||
message.textContent = response.ok ? success : response.message;
|
||
message.classList.toggle('is-error', !response.ok);
|
||
if (response.ok && vote !== 'down') {
|
||
input.value = '';
|
||
closeSuggestions();
|
||
}
|
||
applyWordState(response.state);
|
||
}).catch(function () {
|
||
message.textContent = 'Das hat nicht geklappt. Bitte versuche es noch einmal.';
|
||
message.classList.add('is-error');
|
||
}).then(function () {
|
||
sending = false;
|
||
});
|
||
}
|
||
|
||
function applyWordState(state) {
|
||
if (state.version !== version || !state.words) {
|
||
// Limit reached, slide changed or voting closed.
|
||
window.location.reload();
|
||
return;
|
||
}
|
||
var remaining = wordForm.querySelector('[data-words-remaining]');
|
||
if (state.words.remaining === null) {
|
||
remaining.textContent = 'Du kannst beliebig viele Begriffe abgeben.';
|
||
} else {
|
||
remaining.textContent = state.words.remaining === 1
|
||
? 'Du kannst noch einen Begriff abgeben.'
|
||
: 'Du kannst noch ' + state.words.remaining + ' Begriffe abgeben.';
|
||
}
|
||
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 */ }
|
||
}
|
||
|
||
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);
|
||
}
|
||
|
||
// ------------------------------------------------------------------ boot
|
||
|
||
document.addEventListener('DOMContentLoaded', function () {
|
||
initCopy();
|
||
document.querySelectorAll('[data-presenter]').forEach(initPresenter);
|
||
document.querySelectorAll('[data-participant]').forEach(initParticipant);
|
||
|
||
// 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 };
|
||
})();
|