Bugs fixes
[qomet.git] / public / javascripts / assessment.js
index c014b5a..9858643 100644 (file)
@@ -1,6 +1,3 @@
-// TODO: if display == "all", les envois devraient être non définitifs (possibilité de corriger)
-// Et, blur sur une (sous-)question devrait envoyer la version courante de la sous-question
-
 let socket = null; //monitor answers in real time
 
 if (assessment.mode == "secure" && !checkWindowSize())
@@ -15,21 +12,12 @@ function checkWindowSize()
        return window.innerWidth >= screen.width-3 && window.innerHeight >= screen.height-3;
 };
 
-function libsRefresh()
-{
-       // Run Prism + MathJax on questions text
-       $("#statements").find("code[class^=language-]").each( (i,elem) => {
-               Prism.highlightElement(elem);
-       });
-       MathJax.Hub.Queue(["Typeset",MathJax.Hub,"statements"]);
-}
-
-new Vue({
+let V = new Vue({
        el: "#assessment",
        data: {
                assessment: assessment,
-               inputs: [ ], //student's answers
-               student: { }, //filled later
+               answers: { }, //filled later with answering parameters
+               student: { }, //filled later (name, password)
                // Stage 0: unauthenticated (number),
                //       1: authenticated (got a name, unvalidated)
                //       2: locked: password set, exam started
@@ -39,220 +27,42 @@ new Vue({
                remainingTime: 0, //global, in seconds
                warnMsg: "",
        },
-       components: {
-               "statements": {
-                       props: ['assessment','inputs','student','stage'],
-                       // TODO: general render function for nested exercises
-                       // There should be a questions navigator below, or next (visible if display=='all')
-                       // Full questions tree is rendered, but some parts hidden depending on display settings
-                       render(h) {
-                               let self = this;
-                               let questions = (assessment.questions || [ ]).map( (q,i) => {
-                                       let questionContent = [ ];
-                                       questionContent.push(
-                                               h(
-                                                       "div",
-                                                       {
-                                                               "class": {
-                                                                       wording: true,
-                                                               },
-                                                               domProps: {
-                                                                       innerHTML: q.wording,
-                                                               },
-                                                       }
-                                               )
-                                       );
-                                       let optionsOrder = _.range(q.options.length);
-                                       if (!q.fixed)
-                                               optionsOrder = _.shuffle(optionsOrder);
-                                       let optionList = [ ];
-                                       optionsOrder.forEach( idx => {
-                                               let option = [ ];
-                                               option.push(
-                                                       h(
-                                                               "input",
-                                                               {
-                                                                       domProps: {
-                                                                               checked: this.inputs.length > 0 && this.inputs[i][idx],
-                                                                       },
-                                                                       attrs: {
-                                                                               id: this.inputId(i,idx),
-                                                                               type: "checkbox",
-                                                                       },
-                                                                       on: {
-                                                                               change: e => { this.inputs[i][idx] = e.target.checked; },
-                                                                       },
-                                                               },
-                                                       )
-                                               );
-                                               option.push(
-                                                       h(
-                                                               "label",
-                                                               {
-                                                                       domProps: {
-                                                                               innerHTML: q.options[idx],
-                                                                       },
-                                                                       attrs: {
-                                                                               "for": this.inputId(i,idx),
-                                                                       },
-                                                               }
-                                                       )
-                                               );
-                                               optionList.push(
-                                                       h(
-                                                               "div",
-                                                               {
-                                                                       "class": {
-                                                                               option: true,
-                                                                               choiceCorrect: this.stage == 4 && assessment.questions[i].answer.includes(idx),
-                                                                               choiceWrong: this.stage == 4 && this.inputs[i][idx] && !assessment.questions[i].answer.includes(idx),
-                                                                       },
-                                                               },
-                                                               option
-                                                       )
-                                               );
-                                       });
-                                       questionContent.push(
-                                               h(
-                                                       "div",
-                                                       {
-                                                               "class": {
-                                                                       optionList: true,
-                                                               },
-                                                       },
-                                                       optionList
-                                               )
-                                       );
-                                       return h(
-                                               "div",
-                                               {
-                                                       "class": {
-                                                               "question": true,
-                                                               "hide": this.stage == 2 && assessment.display == 'one' && assessment.indices[assessment.index] != i,
-                                                       },
-                                               },
-                                               questionContent
-                                       );
-                               });
-                               if (this.stage == 2)
-                               {
-                                       questions.unshift(
-                                               h(
-                                                       "button",
-                                                       {
-                                                               "class": {
-                                                                       "waves-effect": true,
-                                                                       "waves-light": true,
-                                                                       "btn": true,
-                                                               },
-                                                               style: {
-                                                                       "display": "block",
-                                                                       "margin-left": "auto",
-                                                                       "margin-right": "auto",
-                                                               },
-                                                               on: {
-                                                                       click: () => this.sendAnswer(assessment.indices[assessment.index]),
-                                                               },
-                                                       },
-                                                       "Send"
-                                               )
-                                       );
-                               }
-                               return h(
-                                       "div",
-                                       {
-                                               attrs: {
-                                                       id: "statements",
-                                               },
-                                       },
-                                       questions
-                               );
-                       },
-                       mounted: function() {
-                               if (assessment.mode != "secure")
-                                       return;
-                               window.addEventListener("keydown", e => {
-                                       // Ignore F12 (avoid accidental window resize due to devtools)
-                                       // NOTE: in Chromium at least, fullscreen mode exit with F11 cannot be prevented.
-                                       // Workaround: disable key at higher level. Possible xbindkey config:
-                                       // "false"
-                                       //   m:0x10 + c:95
-                                       //   Mod2 + F11
-                                       if (e.keyCode == 123)
-                                               e.preventDefault();
-                               }, false);
-                               window.addEventListener("blur", () => {
-                                       this.trySendCurrentAnswer();
-                                       document.location.href= "/noblur";
-                               }, false);
-                               window.addEventListener("resize", e => {
-                                       this.trySendCurrentAnswer();
-                                       document.location.href= "/fullscreen";
-                               }, false);
-                       },
-                       updated: function() {
-                               libsRefresh(); //TODO: shouldn't be required: "MathJax" strings on start and assign them to assessment.questions. ...
-                       },
-                       methods: {
-                               inputId: function(i,j) {
-                                       return "q" + i + "_" + "input" + j;
-                               },
-                               trySendCurrentAnswer: function() {
-                                       if (this.stage == 2)
-                                               this.sendAnswer(assessment.indices[assessment.index]);
-                               },
-                               // stage 2
-                               sendAnswer: function(realIndex) {
-                                       let gotoNext = () => {
-                                               if (assessment.index == assessment.questions.length - 1)
-                                                       this.$emit("gameover");
-                                               else
-                                                       assessment.index++;
-                                               this.$forceUpdate(); //TODO: shouldn't be required
-                                       };
-                                       if (assessment.mode == "open")
-                                               return gotoNext(); //only local
-                                       let answerData = {
-                                               aid: assessment._id,
-                                               answer: JSON.stringify({
-                                                       index:realIndex.toString(),
-                                                       input:this.inputs[realIndex]
-                                                               .map( (tf,i) => { return {val:tf,idx:i}; } )
-                                                               .filter( item => { return item.val; })
-                                                               .map( item => { return item.idx; })
-                                               }),
-                                               number: this.student.number,
-                                               password: this.student.password,
-                                       };
-                                       $.ajax("/send/answer", {
-                                               method: "GET",
-                                               data: answerData,
-                                               dataType: "json",
-                                               success: ret => {
-                                                       if (!!ret.errmsg)
-                                                               return this.$emit("warning", ret.errmsg);
-                                                       else
-                                                               gotoNext();
-                                                       socket.emit(message.newAnswer, answerData);
-                                               },
-                                       });
-                               },
-                       },
-               },
-       },
        computed: {
                countdown: function() {
                        let seconds = this.remainingTime % 60;
                        let minutes = Math.floor(this.remainingTime / 60);
                        return this.padWithZero(minutes) + ":" + this.padWithZero(seconds);
                },
+               showAnswers: function() {
+                       return this.stage == 4;
+               },
        },
        mounted: function() {
                $(".modal").modal();
+               if (assessment.mode != "secure")
+                       return;
+               window.addEventListener("keydown", e => {
+                       // Ignore F12 (avoid accidental window resize due to devtools)
+                       // NOTE: in Chromium at least, fullscreen mode exit with F11 cannot be prevented.
+                       // Workaround: disable key at higher level. Possible xbindkey config:
+                       // "false"
+                       //   m:0x10 + c:95
+                       //   Mod2 + F11
+                       if (e.keyCode == 123)
+                               e.preventDefault();
+               }, false);
+               window.addEventListener("blur", () => {
+                       this.trySendCurrentAnswer();
+                       document.location.href= "/noblur";
+               }, false);
+               window.addEventListener("resize", e => {
+                       this.trySendCurrentAnswer();
+                       document.location.href= "/fullscreen";
+               }, false);
        },
        methods: {
                // In case of AJAX errors
-               warning: function(message) {
+               showWarning: function(message) {
                        this.warnMsg = message;
                        $("#warning").modal("open");
                },
@@ -261,6 +71,10 @@ new Vue({
                                return "0" + x;
                        return x;
                },
+               trySendCurrentAnswer: function() {
+                       if (this.stage == 2)
+                               this.sendAnswer();
+               },
                // stage 0 --> 1
                getStudent: function(cb) {
                        $.ajax("/get/student", {
@@ -272,7 +86,7 @@ new Vue({
                                dataType: "json",
                                success: s => {
                                        if (!!s.errmsg)
-                                               return this.warning(s.errmsg);
+                                               return this.showWarning(s.errmsg);
                                        this.stage = 1;
                                        this.student = s.student;
                                        Vue.nextTick( () => { Materialize.updateTextFields(); });
@@ -298,11 +112,12 @@ new Vue({
                                // Initialize structured answer(s) based on questions type and nesting (TODO: more general)
                                if (!!questions)
                                        assessment.questions = questions;
+                               this.answers.inputs = [ ];
                                for (let q of assessment.questions)
-                                       this.inputs.push( _(q.options.length).times( _.constant(false) ) );
+                                       this.answers.inputs.push( _(q.options.length).times( _.constant(false) ) );
                                if (!paper)
                                {
-                                       assessment.indices = assessment.fixed
+                                       this.answers.indices = assessment.fixed
                                                ? _.range(assessment.questions.length)
                                                : _.shuffle( _.range(assessment.questions.length) );
                                }
@@ -311,10 +126,11 @@ new Vue({
                                        // Resuming
                                        let indices = paper.inputs.map( input => { return input.index; });
                                        let remainingIndices = _.difference( _.range(assessment.questions.length).map(String), indices );
-                                       assessment.indices = indices.concat( _.shuffle(remainingIndices) );
+                                       this.answers.indices = indices.concat( _.shuffle(remainingIndices) );
                                }
-                               assessment.index = !!paper ? paper.inputs.length : 0;
-                               Vue.nextTick(libsRefresh);
+                               this.answers.index = !!paper ? paper.inputs.length : 0;
+                               this.answers.displayAll = assessment.display == "all";
+                               this.answers.showSolution = false;
                                this.stage = 2;
                        };
                        if (assessment.mode == "open")
@@ -328,12 +144,12 @@ new Vue({
                                dataType: "json",
                                success: s => {
                                        if (!!s.errmsg)
-                                               return this.warning(s.errmsg);
+                                               return this.showWarning(s.errmsg);
                                        if (!!s.paper)
                                        {
                                                // Resuming: receive stored answers + startTime
                                                this.student.password = s.paper.password;
-                                               this.inputs = s.paper.inputs.map( inp => { return inp.input; });
+                                               this.answers.inputs = s.paper.inputs.map( inp => { return inp.input; });
                                        }
                                        else
                                        {
@@ -342,7 +158,7 @@ new Vue({
                                                // action (power failure, computer down, ...)
                                        }
                                        socket = io.connect("/" + assessment.name, {
-                                               query: "number=" + this.student.number + "&password=" + this.password
+                                               query: "aid=" + assessment._id + "&number=" + this.student.number + "&password=" + this.student.password
                                        });
                                        socket.on(message.allAnswers, this.setAnswers);
                                        initializeStage2(s.questions, s.paper);
@@ -356,11 +172,50 @@ new Vue({
                        let self = this;
                        setInterval( function() {
                                self.remainingTime--;
-                               if (self.remainingTime <= 0 || self.stage >= 4)
-                                       self.endAssessment();
+                               if (self.remainingTime <= 0)
+                               {
+                                       if (self.stage == 2)
+                                               self.endAssessment();
                                        clearInterval(this);
+                               }
                        }, 1000);
                },
+               // stage 2
+               sendAnswer: function() {
+                       const realIndex = this.answers.indices[this.answers.index];
+                       let gotoNext = () => {
+                               if (this.answers.index == assessment.questions.length - 1)
+                                       this.endAssessment();
+                               else
+                                       this.answers.index++;
+                               this.$children[0].$forceUpdate(); //TODO: bad HACK, and shouldn't be required...
+                       };
+                       if (assessment.mode == "open")
+                               return gotoNext(); //only local
+                       let answerData = {
+                               aid: assessment._id,
+                               answer: JSON.stringify({
+                                       index: realIndex.toString(),
+                                       input: this.answers.inputs[realIndex]
+                                               .map( (tf,i) => { return {val:tf,idx:i}; } )
+                                               .filter( item => { return item.val; })
+                                               .map( item => { return item.idx; })
+                               }),
+                               number: this.student.number,
+                               password: this.student.password,
+                       };
+                       $.ajax("/send/answer", {
+                               method: "GET",
+                               data: answerData,
+                               dataType: "json",
+                               success: ret => {
+                                       if (!!ret.errmsg)
+                                               return this.showWarning(ret.errmsg);
+                                       gotoNext();
+                                       socket.emit(message.newAnswer, answerData);
+                               },
+                       });
+               },
                // stage 2 --> 3 (or 4)
                // from a message by statements component, or time over
                endAssessment: function() {
@@ -369,6 +224,7 @@ new Vue({
                        if (assessment.mode == "open")
                        {
                                this.stage = 4;
+                               this.answers.showSolution = true;
                                return;
                        }
                        $.ajax("/end/assessment", {
@@ -381,7 +237,7 @@ new Vue({
                                dataType: "json",
                                success: ret => {
                                        if (!!ret.errmsg)
-                                               return this.warning(ret.errmsg);
+                                               return this.showWarning(ret.errmsg);
                                        assessment.conclusion = ret.conclusion;
                                        this.stage = 3;
                                        delete this.student["password"]; //unable to send new answers now
@@ -391,9 +247,10 @@ new Vue({
                        });
                },
                // stage 3 --> 4 (on socket message "feedback")
-               setAnswers: function(answers) {
-                       for (let i=0; i<answers.length; i++)
-                               assessment.questions[i].answer = answers[i];
+               setAnswers: function(m) {
+                       for (let i=0; i<m.answers.length; i++)
+                               assessment.questions[i].answer = m.answers[i];
+                       this.answers.showSolution = true;
                        this.stage = 4;
                },
        },