h5p-question-set/js/questionset.js

430 lines
14 KiB
JavaScript
Raw Normal View History

2013-04-04 15:44:06 +02:00
var H5P = H5P || {};
2013-04-26 17:27:35 +02:00
/**
* Will render a Question with multiple choices for answers.
*
* Events provided:
* - h5pQuestionSetFinished: Triggered when a question is finished. (User presses Finish-button)
*
* @param {Array} options
* @param {int} contentId
* @returns {H5P.QuestionSet} Instance
*/
2013-04-04 15:44:06 +02:00
H5P.QuestionSet = function (options, contentId) {
2013-04-26 17:27:35 +02:00
if (!(this instanceof H5P.QuestionSet)) {
2013-04-04 15:44:06 +02:00
return new H5P.QuestionSet(options, contentId);
2013-04-26 17:27:35 +02:00
}
2013-04-04 15:44:06 +02:00
var $ = H5P.jQuery;
2013-04-26 17:27:35 +02:00
var texttemplate =
'<% if (introPage.showIntroPage) { %>' +
'<div class="intro-page">' +
' <% if (introPage.title) { %>' +
' <div class="title"><span><%= introPage.title %></span></div>' +
' <% } %>' +
' <% if (introPage.introduction) { %>' +
' <div class="introduction"><%= introPage.introduction %></div>' +
' <% } %>' +
2013-05-03 10:05:49 +02:00
' <div class="buttons"><a class="qs-startbutton button"><%= introPage.startButtonText %></a></div>' +
2013-04-26 17:27:35 +02:00
'</div>' +
2013-05-03 10:05:49 +02:00
'<% } %>' +
'<div class="questionset<% if (introPage.showIntroPage) { %> hidden<% } %>">' +
2013-04-26 17:27:35 +02:00
' <% for (var i=0; i<questions.length; i++) { %>' +
' <div class="question-container"></div>' +
2013-04-26 17:27:35 +02:00
' <% } %>' +
' <div class="qs-footer">' +
' <div class="qs-progress">' +
' <% if (progressType == "dots") { %>' +
' <div class="dots-container">' +
' <% for (var i=0; i<questions.length; i++) { %>' +
' <span class="progress-dot unanswered"></span>' +
2013-04-26 17:27:35 +02:00
' <%} %>' +
' </div>' +
' <% } else if (progressType == "textual") { %>' +
' <span class="progress-text"></span>' +
' <% } %>' +
' </div>' +
2014-06-26 16:23:12 +02:00
' <a class="prev button" title="<%= texts.prevButton %>"></a>' +
' <a class="next button" title="<%= texts.nextButton %>"></a>' +
' <a class="finish button" title="<%= texts.finishButton %>"></a>' +
2013-04-26 17:27:35 +02:00
' </div>' +
'</div>';
var resulttemplate =
'<div class="questionset-results">' +
' <div class="greeting"><%= message %></div>' +
' <div class="score <%= scoreclass %>">' +
' <div class="emoticon"></div>' +
' <div class="resulttext <%= scoreclass %>"><% if (comment) { %><h2><%= comment %></h2><% } %><%= score %><br><%= resulttext %></div>' +
' </div>' +
2013-05-03 10:05:49 +02:00
' <div class="buttons"><a class="button qs-finishbutton"><%= finishButtonText %></a><a class="button qs-solutionbutton"><%= solutionButtonText %></a></div>' +
2013-04-26 17:27:35 +02:00
'</div>';
2013-04-04 15:44:06 +02:00
var defaults = {
randomOrder: false,
initialQuestion: 0,
progressType: 'dots',
passPercentage: 50,
questions: [],
introPage: {
showIntroPage: false,
title: '',
introduction: '',
2013-04-26 17:27:35 +02:00
startButtonText: 'Start'
2013-04-04 15:44:06 +02:00
},
texts: {
2013-04-26 17:27:35 +02:00
prevButton: 'Previous',
nextButton: 'Next',
finishButton: 'Finish',
textualProgress: 'Question: @current of @total questions'
2013-04-04 15:44:06 +02:00
},
endGame: {
showResultPage: true,
message: 'Your result:',
successGreeting: 'Congratulations!',
successComment: 'You have enough correct answers to pass the test.',
failGreeting: 'Sorry!',
failComment: "You don't have enough correct answers to pass this test.",
scoreString: 'You got @score points of @total possible.',
finishButtonText: 'Finish',
2013-05-03 10:05:49 +02:00
solutionButtonText: 'Show solution',
showAnimations: false
},
postUserStatistics: (H5P.postUserStatistics === true)
2013-04-04 15:44:06 +02:00
};
var template = new EJS({text: texttemplate});
var endTemplate = new EJS({text: resulttemplate});
2013-04-26 17:27:35 +02:00
var params = $.extend(true, {}, defaults, options);
2013-04-04 15:44:06 +02:00
var currentQuestion = 0;
var questionInstances = new Array();
var $myDom;
2013-05-03 10:05:49 +02:00
renderSolutions = false;
2013-04-04 15:44:06 +02:00
// Instantiate question instances
2013-04-26 17:27:35 +02:00
for (var i = 0; i < params.questions.length; i++) {
2013-04-04 15:44:06 +02:00
var question = params.questions[i];
// TODO: Render on init, inject in template.
$.extend(question.params, {
displaySolutionsButton: false,
postUserStatistics: false
});
questionInstances.push(H5P.newRunnable(question, contentId));
2013-04-04 15:44:06 +02:00
}
// Update button state.
var _updateButtons = function () {
var answered = true;
for (var i = questionInstances.length - 1; i >= 0; i--) {
answered = answered && (questionInstances[i]).getAnswerGiven();
}
if (currentQuestion === 0) {
$('.prev.button', $myDom).hide();
} else {
$('.prev.button', $myDom).show();
}
2013-04-26 17:27:35 +02:00
if (currentQuestion === (params.questions.length - 1)) {
2013-04-04 15:44:06 +02:00
$('.next.button', $myDom).hide();
if (answered) {
$('.finish.button', $myDom).show();
}
} else {
$('.next.button', $myDom).show();
$('.finish.button', $myDom).hide();
}
};
var _showQuestion = function (questionNumber) {
// Sanitize input.
2013-04-26 17:27:35 +02:00
if (questionNumber < 0) {
questionNumber = 0;
}
if (questionNumber >= params.questions.length) {
questionNumber = params.questions.length - 1;
}
2013-04-04 15:44:06 +02:00
// Hide all questions
$('.question-container', $myDom).hide().eq(questionNumber).show();
2013-04-04 15:44:06 +02:00
// Trigger resize on question in case the size of the QS has changed.
var instance = questionInstances[questionNumber];
if (instance.$ !== undefined) {
instance.$.trigger('resize');
}
2013-04-04 15:44:06 +02:00
// Update progress indicator
// Test if current has been answered.
2013-04-26 17:27:35 +02:00
if (params.progressType === 'textual') {
2013-04-04 15:44:06 +02:00
$('.progress-text', $myDom).text(params.texts.textualProgress.replace("@current", questionNumber+1).replace("@total", params.questions.length));
2013-04-26 17:27:35 +02:00
}
else {
2013-04-04 15:44:06 +02:00
// Set currentNess
$('.progress-dot.current', $myDom).removeClass('current');
$('.progress-dot:eq(' + questionNumber +')', $myDom).addClass('current');
2013-04-04 15:44:06 +02:00
}
// Remember where we are
currentQuestion = questionNumber;
_updateButtons();
return currentQuestion;
};
2013-05-03 10:05:49 +02:00
var showSolutions = function () {
for (var i = 0; i < questionInstances.length; i++) {
questionInstances[i].showSolutions();
}
};
var rendered = false;
var reRender = function () {
rendered = false;
};
2013-04-04 15:44:06 +02:00
var _displayEndGame = function () {
2013-05-03 10:05:49 +02:00
if (rendered) {
$myDom.children().hide().filter('.questionset-results').show();
return;
}
rendered = true;
2013-04-04 15:44:06 +02:00
// Get total score.
var finals = getScore();
var totals = totalScore();
var scoreString = params.endGame.scoreString.replace("@score", finals).replace("@total", totals);
2013-04-04 15:44:06 +02:00
var success = ((100 * finals / totals) >= params.passPercentage);
var eventData = {
score: scoreString,
passed: success
};
var displayResults = function () {
if (params.postUserStatistics === true) {
H5P.setFinished(contentId, getScore(), totalScore());
}
2013-04-04 15:44:06 +02:00
if (!params.endGame.showResultPage) {
$(returnObject).trigger('h5pQuestionSetFinished', eventData);
return;
}
var eparams = {
message: params.endGame.message,
comment: (success ? params.endGame.successGreeting : params.endGame.failGreeting),
2013-04-04 15:44:06 +02:00
score: scoreString,
scoreclass: (success ? 'success' : 'fail'),
resulttext: (success ? params.endGame.successComment : params.endGame.failComment),
2013-05-03 10:05:49 +02:00
finishButtonText: params.endGame.finishButtonText,
solutionButtonText: params.endGame.solutionButtonText
2013-04-04 15:44:06 +02:00
};
// Show result page.
$myDom.children().hide();
$myDom.append(endTemplate.render(eparams));
2013-04-26 17:27:35 +02:00
$('.qs-finishbutton').click(function () {
2013-04-04 15:44:06 +02:00
$(returnObject).trigger('h5pQuestionSetFinished', eventData);
});
2013-05-03 10:05:49 +02:00
$('.qs-solutionbutton', $myDom).click(function () {
showSolutions();
$myDom.children().hide().filter('.questionset').show();
_showQuestion(params.initialQuestion);
});
2013-04-04 15:44:06 +02:00
};
if (params.endGame.showAnimations) {
var videoData = success ? params.endGame.successVideo : params.endGame.failVideo;
2013-04-04 15:44:06 +02:00
if (videoData) {
$myDom.children().hide();
2013-04-26 17:27:35 +02:00
var $videoContainer = $('<div class="video-container"></div>').appendTo($myDom);
var video = new H5P.Video({
files: videoData,
fitToWrapper: true,
controls: false,
autoplay: false
}, contentId);
2013-04-26 17:27:35 +02:00
video.endedCallback = function () {
2013-04-04 15:44:06 +02:00
displayResults();
2013-04-26 17:27:35 +02:00
$videoContainer.hide();
};
video.attach($videoContainer);
video.play();
2013-04-26 17:27:35 +02:00
if (params.endGame.skipButtonText) {
$('<a class="button skip">' + params.endGame.skipButtonText + '</a>').click(function () {
2013-04-26 17:27:35 +02:00
video.stop();
$videoContainer.hide();
displayResults();
}).appendTo($videoContainer);
}
2013-04-04 15:44:06 +02:00
return;
}
}
// Trigger finished event.
displayResults();
};
// Function for attaching the multichoice to a DOM element.
var attach = function (target) {
2013-04-26 17:27:35 +02:00
if (typeof(target) === "string") {
$myDom = $('#' + target);
}
else {
2013-04-04 15:44:06 +02:00
$myDom = $(target);
}
// Render own DOM into target.
$myDom.html(template.render(params));
if (params.backgroundImage !== undefined) {
$myDom.css({
overflow: 'hidden',
background: '#000 url("' + H5P.getPath(params.backgroundImage.path, contentId) + '") no-repeat 50% 50%',
backgroundSize: '100% auto'
});
}
if (params.introPage.backgroundImage !== undefined) {
var $intro = $myDom.find('.intro-page');
if ($intro.length) {
$intro.css({
background: '#000 url("' + H5P.getPath(params.introPage.backgroundImage.path, contentId) + '") no-repeat 50% 50%',
backgroundSize: '100% auto'
});
}
}
2013-04-04 15:44:06 +02:00
// Attach questions
2013-04-26 17:27:35 +02:00
for (var i = 0; i < questionInstances.length; i++) {
2013-04-04 15:44:06 +02:00
var question = questionInstances[i];
question.attach($('.question-container:eq(' + i + ')', $myDom));
2013-04-26 17:27:35 +02:00
$(question).on('h5pQuestionAnswered', function () {
$('.progress-dot:eq(' + currentQuestion +')', $myDom).removeClass('unanswered').addClass('answered');
2013-04-04 15:44:06 +02:00
_updateButtons();
});
if (question.getAnswerGiven()) {
$('.progress-dot:eq(' + i +')'
, $myDom).removeClass('unanswered').addClass('answered');
2013-04-04 15:44:06 +02:00
}
}
// Allow other libraries to add transitions after the questions have been inited
$('.questionset', $myDom).addClass('started');
2013-04-04 15:44:06 +02:00
2013-05-03 10:05:49 +02:00
$('.qs-startbutton', $myDom).click(function () {
2013-04-04 15:44:06 +02:00
$(this).parents('.intro-page').hide();
$('.questionset', $myDom).removeClass('hidden');
_showQuestion(currentQuestion);
2013-04-04 15:44:06 +02:00
});
// Set event listeners.
2013-04-26 17:27:35 +02:00
$('.progress-dot', $myDom).click(function () {
_showQuestion($(this).index());
2013-04-04 15:44:06 +02:00
});
2013-04-26 17:27:35 +02:00
$('.next.button', $myDom).click(function () {
2013-04-04 15:44:06 +02:00
_showQuestion(currentQuestion + 1);
});
2013-04-26 17:27:35 +02:00
$('.prev.button', $myDom).click(function () {
2013-04-04 15:44:06 +02:00
_showQuestion(currentQuestion - 1);
});
2013-04-26 17:27:35 +02:00
$('.finish.button', $myDom).click(function () {
2013-04-04 15:44:06 +02:00
_displayEndGame();
});
// Hide all but initial Question.
_showQuestion(params.initialQuestion);
_updateButtons();
2013-05-03 10:05:49 +02:00
if (renderSolutions) {
showSolutions();
}
2014-03-21 13:49:38 +01:00
this.$.trigger('resize');
2013-04-04 15:44:06 +02:00
return this;
};
// Get current score for questionset.
var getScore = function () {
var score = 0;
for (var i = questionInstances.length - 1; i >= 0; i--) {
score += questionInstances[i].getScore();
}
return score;
};
// Get total score possible for questionset.
var totalScore = function () {
var score = 0;
for (var i = questionInstances.length - 1; i >= 0; i--) {
2013-04-26 17:27:35 +02:00
score += questionInstances[i].getMaxScore();
2013-04-04 15:44:06 +02:00
}
return score;
};
/**
* Gather copyright information for the current content.
*
* @returns {H5P.ContentCopyrights}
*/
var getCopyrights = function () {
var info = new H5P.ContentCopyrights();
// Background
if (params.backgroundImage !== undefined && params.backgroundImage.copyright !== undefined) {
var background = new H5P.MediaCopyright(params.backgroundImage.copyright);
background.setThumbnail(new H5P.Thumbnail(H5P.getPath(params.backgroundImage.path, contentId), params.backgroundImage.width, params.backgroundImage.height));
info.addMedia(background);
}
// Questions
for (var i = 0; i < questionInstances.length; i++) {
var questionInstance = questionInstances[i];
if (questionInstance.getCopyrights !== undefined) {
var rights = questionInstance.getCopyrights();
if (rights !== undefined) {
rights.setLabel('Question '+(i+1));
info.addContent(rights);
}
}
}
// Success video
if (params.endGame.successVideo !== undefined && params.endGame.successVideo.length > 0) {
var video = params.endGame.successVideo[0];
if (video.copyright !== undefined) {
info.addMedia(new H5P.MediaCopyright(video.copyright));
}
}
// Fail video
if (params.endGame.failVideo !== undefined && params.endGame.failVideo.length > 0) {
video = params.endGame.failVideo[0];
if (video.copyright !== undefined) {
info.addMedia(new H5P.MediaCopyright(video.copyright));
}
}
return info;
2014-06-26 16:23:12 +02:00
};
2013-04-04 15:44:06 +02:00
// Masquerade the main object to hide inner properties and functions.
var returnObject = {
2014-03-21 13:49:38 +01:00
$: $(this),
2013-04-04 15:44:06 +02:00
attach: attach, // Attach to DOM object
getQuestions: function () {return questionInstances;},
getScore: getScore,
2013-05-03 10:05:49 +02:00
showSolutions: function () {
renderSolutions = true;
},
2013-04-04 15:44:06 +02:00
totalScore: totalScore,
2013-05-03 10:05:49 +02:00
reRender: reRender,
defaults: defaults, // Provide defaults for inspection
getCopyrights: getCopyrights
2013-04-04 15:44:06 +02:00
};
return returnObject;
};