fs-quiz-tool/web/quiz.js

470 lines
9.1 KiB
JavaScript
Raw Normal View History

2020-01-15 18:02:00 +01:00
function updateTotalTimer() {
var timerEls = document.querySelectorAll('.totaltimer')
var minutes = Math.floor(state.totalTimer / 60)
var seconds = state.totalTimer % 60
var text = minutes + ':' + ('0' + seconds).slice(-2)
for (timerEl of timerEls)
timerEl.innerHTML = text
state.totalTimer++
localStorage.setItem('state', JSON.stringify(state))
}
function startTotalTimer() {
console.log('Setting totalTimer to ' + state.totalTimer + ' seconds.')
updateTotalTimer()
state.totalInterval = setInterval(updateTotalTimer, 1000)
}
2021-01-11 18:50:32 +01:00
function updateSubmitButton() {
var button = document.getElementById('quizSubmitButton')
var lastQuestion = (state.currentQuestion == (state.questions.length - 1))
button.value = lastQuestion || !getRule('sequential') ? 'Submit Answers' : 'Next Question'
}
function resetSubmitButton() {
updateSubmitButton()
document.getElementById('quizSubmitButton').disabled = false
2021-01-11 18:50:32 +01:00
}
2020-01-15 18:02:00 +01:00
function updateSubmitTimer() {
2020-01-12 15:25:31 +01:00
var button = document.getElementById('quizSubmitButton')
2020-01-15 18:02:00 +01:00
if (state.submitTimer > 0) {
2020-01-12 15:25:31 +01:00
timetext = state.submitTimer > 60 ?
Math.floor(state.submitTimer/60)+':'+(('0' + (state.submitTimer%60)).slice(-2)) :
state.submitTimer + 's'
button.value = 'Wait ' + timetext
2020-01-12 15:25:31 +01:00
button.disabled = true
2020-01-15 18:02:00 +01:00
state.submitTimer -= 1
2020-01-12 15:25:31 +01:00
} else {
resetSubmitButton()
2020-01-15 18:02:00 +01:00
clearInterval(state.submitInterval)
2020-01-12 15:25:31 +01:00
if (getRule('sequential') && !getRule('allowQOvertime'))
submitQuiz()
2020-01-12 15:25:31 +01:00
}
}
2020-01-15 18:02:00 +01:00
function startSubmitTimer(time) {
2020-01-12 15:25:31 +01:00
2021-01-05 23:31:58 +01:00
state.submitTimer = time || state.submitTime
if (state.submitTimer == null)
return
2020-01-12 15:25:31 +01:00
2020-01-15 18:02:00 +01:00
console.log('Setting submitTimer to ' + state.submitTimer + ' seconds.')
2020-01-12 15:25:31 +01:00
2020-01-15 18:02:00 +01:00
updateSubmitTimer()
2020-01-12 15:25:31 +01:00
2020-01-15 18:02:00 +01:00
state.submitInterval = setInterval(updateSubmitTimer, 1000)
2020-01-12 15:25:31 +01:00
}
2021-01-11 18:50:32 +01:00
function showSequentialQuestion() {
var questions = document.querySelectorAll('.question')
for (q of questions)
q.style.display = null
updateSubmitButton()
if (state.currentQuestion !== null) {
var q = document.querySelector('#quiz form #question' + state.currentQuestion)
q.style.display = 'block'
}
}
function nextQuestion() {
state.currentQuestion++
if (state.currentQuestion == state.questions.length)
state.currentQuestion = null
showSequentialQuestion()
if (state.currentQuestion !== null && getRule('questionTimeout'))
startSubmitTimer()
2021-01-11 18:50:32 +01:00
return state.currentQuestion
}
2020-01-15 15:26:20 +01:00
function renderQuiz() {
2020-01-12 15:25:31 +01:00
var quizForm = document.querySelector('#quiz form')
2021-01-11 18:50:32 +01:00
quizForm.className = ''
if (getRule('sequential'))
quizForm.classList.add('sequential')
2020-01-15 15:26:20 +01:00
quizForm.innerHTML = ''
2020-01-12 15:25:31 +01:00
for (const [i, q] of state.questions.entries()) {
2021-01-11 18:50:32 +01:00
var html = `<div class="question" id="question${i}">`
2020-01-12 15:25:31 +01:00
html += `<h3>Question #${i+1}</h3>`
html += `<h4>${q.question}</h4>`
if (q.picture)
html += `<img src="${q.picture}">`
if (q.type == 'ChooseOne' || q.type == 'ChooseAny') {
var choices = Array.from(q.choices.entries())
var shuffled = choices.sort(() => Math.random() - 0.5)
for ([ci, c] of shuffled)
html += (q.type == 'ChooseOne')
? `<label><input type="radio" name="q${i}" value="${ci+1}"> <p>${c}</p></label><br>`
: `<label><input type="checkbox" name="q${i}" value="${ci+1}"> <p>${c}</p></label><br>`
} else if (q.type == 'Text') {
2020-01-12 15:25:31 +01:00
// If choices were given, use them as labels, otherwise use generic label
for ([ai, a] of q.answers.entries())
html += `<label>${q.choices[ai] ? q.choices[ai] : 'Answer'}<input type="text" name="q${i}"></label>`
2020-01-12 15:25:31 +01:00
}
2021-01-11 18:50:32 +01:00
html += '</div>'
2020-01-12 15:25:31 +01:00
quizForm.innerHTML += html
}
2020-01-15 15:26:20 +01:00
}
function startQuiz() {
state.success = false
console.log('Starting/Resuming quiz. State:')
console.log(state)
renderQuiz()
2020-01-12 15:25:31 +01:00
changeView('quiz')
2021-01-11 18:50:32 +01:00
if (getRule('sequential'))
showSequentialQuestion(state.currentQuestion)
2020-01-15 18:02:00 +01:00
if (state.submitTimer > 0)
startSubmitTimer(state.submitTimer)
else if (getRule('questionTimeout'))
startSubmitTimer()
2020-01-12 15:25:31 +01:00
else
resetSubmitButton()
2020-01-15 18:02:00 +01:00
startTotalTimer()
state.running = true
2020-01-12 15:25:31 +01:00
console.log('Quiz started/resumed')
}
2020-01-15 18:02:00 +01:00
function reStartQuiz() {
console.log('Restarting quiz');
state.responses = defaultState.responses
state.currentQuestion = defaultState.currentQuestion
state.success = defaultState.success
state.submitTry = defaultState.submitTry
state.submitTimer = defaultState.submitTimer
state.submitInterval = defaultState.submitInterval
state.totalTimer = defaultState.totalTimer
state.totalInterval = defaultState.totalInterval
2020-01-15 18:02:00 +01:00
changeView('prescreen')
2020-01-15 18:02:00 +01:00
}
2021-01-05 23:31:58 +01:00
function createQuiz(e) {
2020-01-12 15:25:31 +01:00
2021-01-05 23:31:58 +01:00
e.preventDefault()
2020-01-12 15:25:31 +01:00
2021-01-05 23:31:58 +01:00
console.log('Creating new quiz')
2020-01-13 00:52:30 +01:00
clearState()
removeLink()
2021-01-05 23:31:58 +01:00
state.title = document.getElementById('titleField').value
state.style = document.getElementById('styleField').value
2021-01-06 00:01:06 +01:00
// After state.style is set
applyRuleSettingsFromForm()
if (parseSpreadsheet().success == false) {
2021-01-05 23:31:58 +01:00
alert('Quiz creation failed.')
2020-01-12 15:25:31 +01:00
return
}
2020-01-12 15:25:31 +01:00
console.log('Spreadsheet parsing successful')
updateTitles()
changeView('prescreen')
2021-01-06 00:01:06 +01:00
console.log('Quiz created:')
console.log(state)
2020-01-12 15:25:31 +01:00
2021-01-05 23:31:58 +01:00
return false
2020-01-12 15:25:31 +01:00
}
function endQuiz() {
console.log('Ending quiz')
state.running = false
2020-01-12 15:25:31 +01:00
localStorage.removeItem('state')
//document.querySelector('#quiz form').innerHTML = ''
2020-01-12 15:25:31 +01:00
changeView('postscreen')
2020-01-15 18:02:00 +01:00
if (state.submitInterval)
clearInterval(state.submitInterval)
clearInterval(state.totalInterval)
2020-01-12 15:25:31 +01:00
console.log('Quiz ended')
}
function showQuizResults() {
var quizForm = document.querySelector('#quiz form')
quizForm.className = ''
for (var [idx, value] of state.responses.entries()) {
console.log(idx+':', value)
var el = document.getElementById('question' + idx)
console.log(el)
var a = value.answers
if (value.correct) {
el.classList.add('correct')
} else {
el.classList.add('incorrect')
}
}
changeView('quiz')
}
2020-01-12 15:25:31 +01:00
function mergeKeyReducer(acc, entry) {
if (!acc[entry[0]])
acc[entry[0]] = {answers: [], correct: false}
2020-01-12 15:25:31 +01:00
acc[entry[0]].answers.push(entry[1])
2020-01-12 15:25:31 +01:00
return acc
}
function submitQuiz() {
2021-01-11 18:50:32 +01:00
if (getRule('sequential')) {
var n = nextQuestion()
if (n !== null)
return
}
2020-01-12 15:25:31 +01:00
console.log('Submitting quiz. State:')
console.log(state)
var quizForm = document.querySelector('#quiz form')
var data = new FormData(quizForm)
var responses = Array.from(data.entries()).reduce(mergeKeyReducer, {})
console.log(responses)
var correct = 0
state.responses = []
2020-01-12 15:25:31 +01:00
for (var idx = 0; idx < state.questions.length; idx++) {
2020-01-12 15:25:31 +01:00
var value = responses['q'+idx] || {answers: [], correct: false}
2020-01-12 15:25:31 +01:00
console.log(idx + ": " + value)
2020-01-12 15:25:31 +01:00
if (state.questions[idx].type == 'ChooseOne' || state.questions[idx].type == 'ChooseAny') {
state.questions[idx].answers.sort()
value.answers.sort()
2020-01-12 15:25:31 +01:00
}
2020-01-15 23:17:04 +01:00
var correctAnswer = JSON.stringify(state.questions[idx].answers)
var givenAnswer = JSON.stringify(value.answers)
2020-01-15 23:17:04 +01:00
console.log('Comparing: ' + givenAnswer + ' == ' + correctAnswer + '?: ' + (givenAnswer == correctAnswer))
if (givenAnswer == correctAnswer) {
value.correct = true
2020-01-12 15:25:31 +01:00
correct++
}
state.responses.push(value)
2020-01-12 15:25:31 +01:00
}
console.log(state.responses)
var text = '' + correct + '/' + state.questions.length + ' questions answered correctly.'
2020-01-12 15:25:31 +01:00
state.success = (correct == state.questions.length)
if (!state.success) {
state.submitTry++
if (getRule('submitTries') && state.submitTry < state.submitTries) {
alert(text + `\nThis was try ${state.submitTry}/${state.submitTries}\nClick OK to Try Again`)
renderQuiz()
if (getRule('sequential')) {
state.currentQuestion = 0
showSequentialQuestion(state.currentQuestion)
}
if (getRule('submitTimeout'))
startSubmitTimer()
} else {
document.querySelector('#postscreen h1').innerHTML = (text + '<br>Maybe next time :)')
endQuiz()
}
2020-01-12 15:25:31 +01:00
}
if (state.success) {
document.querySelector('#postscreen h1').innerHTML = (text + '<br>Yay you did it!')
2020-01-12 15:25:31 +01:00
endQuiz()
}
console.log('Quiz submitted')
}
function abortQuiz() {
console.log('Aborting quiz')
if (!confirm('You sure you want to abort this quiz? Your progress will be lost.'))
return
document.querySelector('#postscreen h1').innerHTML = `Quiz cancelled.`
endQuiz()
console.log('Quiz cancelled')
}
function deleteQuiz() {
clearState()
removeLink()
changeView('spreadsheet')
}
2020-01-12 15:25:31 +01:00
window.onload = async function() {
2020-01-15 19:00:51 +01:00
var browserWarning = document.getElementById('browserwarning')
2021-01-05 18:32:02 +01:00
// If arrow functions are supported, it's modern enough :P
2020-01-15 19:00:51 +01:00
browserWarning.style.display = (() => 'none')()
2020-01-12 15:25:31 +01:00
var stateString = localStorage.getItem('state')
var urlId = idFromUrl()
console.log('URL ID:', urlId)
2020-01-12 15:25:31 +01:00
if (stateString) {
console.log('Loading local state')
state = JSON.parse(stateString)
}
// only fetch if it's a different one
var useUrl = (urlId && urlId != state.id)
if (useUrl) {
console.log('Using remote quiz from url')
var quiz = await fetchQuiz(urlId)
state.style = quiz.style
2020-01-12 15:25:31 +01:00
state.title = quiz.title
state.questions = quiz.questions
state.submitTries = quiz.submitTries
state.submitTime = quiz.submitTime
2020-01-12 15:25:31 +01:00
state.id = urlId
changeView('prescreen')
}
updateTitles()
2021-01-05 18:32:02 +01:00
var meme = memes[Math.floor(Math.random()*memes.length)]
document.getElementById('meme').innerHTML = meme
2020-01-12 15:25:31 +01:00
if (stateString && !useUrl)
if (state.running)
startQuiz()
else
changeView('prescreen')
2020-01-12 15:25:31 +01:00
if (!stateString && !useUrl)
changeView('spreadsheet')
console.log('onload complete')
}