Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
// This file is part of Moodle - http://moodle.org/
2
//
3
// Moodle is free software: you can redistribute it and/or modify
4
// it under the terms of the GNU General Public License as published by
5
// the Free Software Foundation, either version 3 of the License, or
6
// (at your option) any later version.
7
//
8
// Moodle is distributed in the hope that it will be useful,
9
// but WITHOUT ANY WARRANTY; without even the implied warranty of
10
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
// GNU General Public License for more details.
12
//
13
// You should have received a copy of the GNU General Public License
14
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
15
 
16
/**
17
 * JavaScript to make drag-drop into text questions work.
18
 *
19
 * Some vocabulary to help understand this code:
20
 *
21
 * The question text contains 'drops' - blanks into which the 'drags', the missing
22
 * words, can be put.
23
 *
24
 * The thing that can be moved into the drops are called 'drags'. There may be
25
 * multiple copies of the 'same' drag which does not really cause problems.
26
 * Each drag has a 'choice' number which is the value set on the drop's hidden
27
 * input when this drag is placed in a drop.
28
 *
29
 * These may be in separate 'groups', distinguished by colour.
30
 * Things can only interact with other things in the same group.
31
 * The groups are numbered from 1.
32
 *
33
 * The place where a given drag started from is called its 'home'.
34
 *
35
 * @module     qtype_ddwtos/ddwtos
36
 * @copyright  2018 The Open University
37
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
38
 * @since      3.6
39
 */
40
define([
41
    'jquery',
42
    'core/dragdrop',
43
    'core/key_codes',
1441 ariadna 44
    'core_form/changechecker',
45
    'core_filters/events',
1 efrain 46
], function(
47
    $,
48
    dragDrop,
49
    keys,
1441 ariadna 50
    FormChangeChecker,
51
    filterEvent
1 efrain 52
) {
53
 
54
    "use strict";
55
 
56
    /**
57
     * Object to handle one drag-drop into text question.
58
     *
59
     * @param {String} containerId id of the outer div for this question.
60
     * @param {boolean} readOnly whether the question is being displayed read-only.
61
     * @constructor
62
     */
63
    function DragDropToTextQuestion(containerId, readOnly) {
1441 ariadna 64
        const thisQ = this;
1 efrain 65
        this.containerId = containerId;
66
        this.questionAnswer = {};
1441 ariadna 67
        this.questionDragDropWidthHeight = [];
1 efrain 68
        if (readOnly) {
69
            this.getRoot().addClass('qtype_ddwtos-readonly');
70
        }
71
        this.resizeAllDragsAndDrops();
72
        this.cloneDrags();
73
        this.positionDrags();
1441 ariadna 74
        // Wait for all dynamic content loaded by filter to be completed.
75
        document.addEventListener(filterEvent.eventTypes.filterContentRenderingComplete, (elements) => {
76
            elements.detail.nodes.forEach((element) => {
77
                thisQ.changeAllDragsAndDropsToFilteredContent(element);
78
            });
79
        });
1 efrain 80
    }
81
 
82
    /**
83
     * In each group, resize all the items to be the same size.
84
     */
85
    DragDropToTextQuestion.prototype.resizeAllDragsAndDrops = function() {
86
        var thisQ = this;
87
        this.getRoot().find('.answercontainer > div').each(function(i, node) {
88
            thisQ.resizeAllDragsAndDropsInGroup(
89
                thisQ.getClassnameNumericSuffix($(node), 'draggrouphomes'));
90
        });
91
    };
92
 
93
    /**
94
     * In a given group, set all the drags and drops to be the same size.
95
     *
96
     * @param {int} group the group number.
97
     */
98
    DragDropToTextQuestion.prototype.resizeAllDragsAndDropsInGroup = function(group) {
99
        var thisQ = this,
1441 ariadna 100
            dragDropItems = this.getRoot().find('span.group' + group),
1 efrain 101
            maxWidth = 0,
102
            maxHeight = 0;
103
 
104
        // Find the maximum size of any drag in this groups.
1441 ariadna 105
        dragDropItems.each(function(i, drag) {
1 efrain 106
            maxWidth = Math.max(maxWidth, Math.ceil(drag.offsetWidth));
107
            maxHeight = Math.max(maxHeight, Math.ceil(0 + drag.offsetHeight));
108
        });
109
 
110
        // The size we will want to set is a bit bigger than this.
111
        maxWidth += 8;
112
        maxHeight += 2;
1441 ariadna 113
        thisQ.questionDragDropWidthHeight[group] = {maxWidth: maxWidth, maxHeight: maxHeight};
1 efrain 114
        // Set each drag home to that size.
1441 ariadna 115
        dragDropItems.each(function(i, drag) {
1 efrain 116
            thisQ.setElementSize(drag, maxWidth, maxHeight);
117
        });
1441 ariadna 118
    };
1 efrain 119
 
1441 ariadna 120
    /**
121
     * Change all the drags and drops related to the item that has been changed by filter to correct size and content.
122
     *
123
     *  @param {object} filteredElement the element has been modified by filter.
124
     */
125
    DragDropToTextQuestion.prototype.changeAllDragsAndDropsToFilteredContent = function(filteredElement) {
126
        let currentFilteredItem = $(filteredElement);
127
        const parentIsDD = currentFilteredItem.parent().closest('span').hasClass('placed') ||
128
            currentFilteredItem.parent().closest('span').hasClass('draghome');
129
        const isDD = currentFilteredItem.hasClass('placed') || currentFilteredItem.hasClass('draghome');
130
        // The filtered element or parent element should a drag or drop item.
131
        if (!parentIsDD && !isDD) {
132
            return;
133
        }
134
        if (parentIsDD) {
135
            currentFilteredItem = currentFilteredItem.parent().closest('span');
136
        }
137
        const thisQ = this;
138
        if (thisQ.getRoot().find(currentFilteredItem).length <= 0) {
139
            // If the DD item doesn't belong to this question
140
            // In case we have multiple questions in the same page.
141
            return;
142
        }
143
        const group = thisQ.getGroup(currentFilteredItem),
144
              choice = thisQ.getChoice(currentFilteredItem);
145
        let listOfModifiedDragDrop = [];
146
        // Get the list of drag and drop item within the same group and choice.
147
        this.getRoot().find('.group' + group + '.choice' + choice).each(function(i, node) {
148
            // Same modified item, skip it.
149
            if ($(node).get(0) === currentFilteredItem.get(0)) {
150
                return;
151
            }
152
            const originalClass = $(node).attr('class');
153
            const originalStyle = $(node).attr('style');
154
            // We want to keep all the handler and event for filtered item, so using clone is the only choice.
155
            const filteredDragDropClone = currentFilteredItem.clone();
156
            // Replace the class and style of the drag drop item we want to replace for the clone.
157
            filteredDragDropClone.attr('class', originalClass);
158
            filteredDragDropClone.attr('style', originalStyle);
159
            // Insert into DOM.
160
            $(node).before(filteredDragDropClone);
161
            // Add the item has been replaced to a list so we can remove it later.
162
            listOfModifiedDragDrop.push(node);
1 efrain 163
        });
1441 ariadna 164
 
165
        listOfModifiedDragDrop.forEach(function(node) {
166
            $(node).remove();
167
        });
168
        // Save the current height and width.
169
        const currentHeight = currentFilteredItem.height();
170
        const currentWidth = currentFilteredItem.width();
171
        // Set to auto so we can get the real height and width of the filtered item.
172
        currentFilteredItem.height('auto');
173
        currentFilteredItem.width('auto');
174
        // We need to set display block so we can get height and width.
175
        // Some browser can't get the offsetWidth/Height if they are an inline element like span tag.
176
        if (!filteredElement.offsetWidth || !filteredElement.offsetHeight) {
177
            filteredElement.classList.add('d-block');
178
        }
179
        if (thisQ.questionDragDropWidthHeight[group].maxWidth < Math.ceil(filteredElement.offsetWidth) ||
180
            thisQ.questionDragDropWidthHeight[group].maxHeight < Math.ceil(0 + filteredElement.offsetHeight)) {
181
            // Remove the d-block class before calculation.
182
            filteredElement.classList.remove('d-block');
183
            // Now resize all the items in the same group if we have new maximum width or height.
184
            thisQ.resizeAllDragsAndDropsInGroup(group);
185
        } else {
186
            // Return the original height and width in case the real height and width is not the maximum.
187
            currentFilteredItem.height(currentHeight);
188
            currentFilteredItem.width(currentWidth);
189
        }
190
        // Remove the d-block class after resize.
191
        filteredElement.classList.remove('d-block');
1 efrain 192
    };
193
 
194
    /**
195
     * Set a given DOM element to be a particular size.
196
     *
197
     * @param {HTMLElement} element
198
     * @param {int} width
199
     * @param {int} height
200
     */
201
    DragDropToTextQuestion.prototype.setElementSize = function(element, width, height) {
202
        $(element).width(width).height(height).css('lineHeight', height + 'px');
203
    };
204
 
205
    /**
206
     * Invisible 'drag homes' are output by the renderer. These have the same properties
207
     * as the drag items but are invisible. We clone these invisible elements to make the
208
     * actual drag items.
209
     */
210
    DragDropToTextQuestion.prototype.cloneDrags = function() {
211
        var thisQ = this;
212
        thisQ.getRoot().find('span.draghome').each(function(index, draghome) {
213
            var drag = $(draghome);
214
            var placeHolder = drag.clone();
215
            placeHolder.removeClass();
216
            placeHolder.addClass('draghome choice' +
217
                thisQ.getChoice(drag) + ' group' +
218
                thisQ.getGroup(drag) + ' dragplaceholder');
219
            drag.before(placeHolder);
220
        });
221
    };
222
 
223
    /**
224
     * Update the position of drags.
225
     */
226
    DragDropToTextQuestion.prototype.positionDrags = function() {
227
        var thisQ = this,
228
            root = this.getRoot();
229
 
230
        // First move all items back home.
231
        root.find('span.draghome').not('.dragplaceholder').each(function(i, dragNode) {
232
            var drag = $(dragNode),
233
                currentPlace = thisQ.getClassnameNumericSuffix(drag, 'inplace');
234
            drag.addClass('unplaced')
235
                .removeClass('placed');
236
            drag.removeAttr('tabindex');
237
            if (currentPlace !== null) {
238
                drag.removeClass('inplace' + currentPlace);
239
            }
240
        });
241
 
242
        // Then place the once that should be placed.
243
        root.find('input.placeinput').each(function(i, inputNode) {
244
            var input = $(inputNode),
245
                choice = input.val(),
246
                place = thisQ.getPlace(input);
247
 
248
            // Record the last known position of the drop.
249
            var drop = root.find('.drop.place' + place),
250
                dropPosition = drop.offset();
251
            drop.data('prev-top', dropPosition.top).data('prev-left', dropPosition.left);
252
 
253
            if (choice === '0') {
254
                // No item in this place.
255
                return;
256
            }
257
 
258
            // Get the unplaced drag.
259
            var unplacedDrag = thisQ.getUnplacedChoice(thisQ.getGroup(input), choice);
260
            // Get the clone of the drag.
261
            var hiddenDrag = thisQ.getDragClone(unplacedDrag);
262
            if (hiddenDrag.length) {
263
                if (unplacedDrag.hasClass('infinite')) {
264
                    var noOfDrags = thisQ.noOfDropsInGroup(thisQ.getGroup(unplacedDrag));
265
                    var cloneDrags = thisQ.getInfiniteDragClones(unplacedDrag, false);
266
                    if (cloneDrags.length < noOfDrags) {
267
                        var cloneDrag = unplacedDrag.clone();
268
                        hiddenDrag.after(cloneDrag);
269
                        questionManager.addEventHandlersToDrag(cloneDrag);
270
                    } else {
271
                        hiddenDrag.addClass('active');
272
                    }
273
                } else {
274
                    hiddenDrag.addClass('active');
275
                }
276
            }
277
            // Send the drag to drop.
278
            thisQ.sendDragToDrop(thisQ.getUnplacedChoice(thisQ.getGroup(input), choice), drop);
279
        });
280
 
281
        // Save the question answer.
282
        thisQ.questionAnswer = thisQ.getQuestionAnsweredValues();
283
    };
284
 
285
    /**
286
     * Get the question answered values.
287
     *
288
     * @return {Object} Contain key-value with key is the input id and value is the input value.
289
     */
290
    DragDropToTextQuestion.prototype.getQuestionAnsweredValues = function() {
291
        let result = {};
292
        this.getRoot().find('input.placeinput').each((i, inputNode) => {
293
            result[inputNode.id] = inputNode.value;
294
        });
295
 
296
        return result;
297
    };
298
 
299
    /**
300
     * Check if the question is being interacted or not.
301
     *
302
     * @return {boolean} Return true if the user has changed the question-answer.
303
     */
304
    DragDropToTextQuestion.prototype.isQuestionInteracted = function() {
305
        const oldAnswer = this.questionAnswer;
306
        const newAnswer = this.getQuestionAnsweredValues();
307
        let isInteracted = false;
308
 
309
        // First, check both answers have the same structure or not.
310
        if (JSON.stringify(newAnswer) !== JSON.stringify(oldAnswer)) {
311
            isInteracted = true;
312
            return isInteracted;
313
        }
314
        // Check the values.
315
        Object.keys(newAnswer).forEach(key => {
316
            if (newAnswer[key] !== oldAnswer[key]) {
317
                isInteracted = true;
318
            }
319
        });
320
 
321
        return isInteracted;
322
    };
323
 
324
    /**
325
     * Handles the start of dragging an item.
326
     *
327
     * @param {Event} e the touch start or mouse down event.
328
     */
329
    DragDropToTextQuestion.prototype.handleDragStart = function(e) {
330
        var thisQ = this,
331
            drag = $(e.target).closest('.draghome');
332
 
333
        var info = dragDrop.prepare(e);
334
        if (!info.start || drag.hasClass('beingdragged')) {
335
            return;
336
        }
337
 
338
        drag.addClass('beingdragged');
339
        var currentPlace = this.getClassnameNumericSuffix(drag, 'inplace');
340
        if (currentPlace !== null) {
341
            this.setInputValue(currentPlace, 0);
342
            drag.removeClass('inplace' + currentPlace);
343
            var hiddenDrop = thisQ.getDrop(drag, currentPlace);
344
            if (hiddenDrop.length) {
345
                hiddenDrop.addClass('active');
346
                drag.offset(hiddenDrop.offset());
347
            }
348
        } else {
349
            var hiddenDrag = thisQ.getDragClone(drag);
350
            if (hiddenDrag.length) {
351
                if (drag.hasClass('infinite')) {
352
                    var noOfDrags = this.noOfDropsInGroup(this.getGroup(drag));
353
                    var cloneDrags = this.getInfiniteDragClones(drag, false);
354
                    if (cloneDrags.length < noOfDrags) {
355
                        var cloneDrag = drag.clone();
356
                        cloneDrag.removeClass('beingdragged');
357
                        hiddenDrag.after(cloneDrag);
358
                        questionManager.addEventHandlersToDrag(cloneDrag);
359
                        drag.offset(cloneDrag.offset());
360
                    } else {
361
                        hiddenDrag.addClass('active');
362
                        drag.offset(hiddenDrag.offset());
363
                    }
364
                } else {
365
                    hiddenDrag.addClass('active');
366
                    drag.offset(hiddenDrag.offset());
367
                }
368
            }
369
        }
370
 
371
        dragDrop.start(e, drag, function(x, y, drag) {
372
            thisQ.dragMove(x, y, drag);
373
        }, function(x, y, drag) {
374
            thisQ.dragEnd(x, y, drag);
375
        });
376
    };
377
 
378
    /**
379
     * Called whenever the currently dragged items moves.
380
     *
381
     * @param {Number} pageX the x position.
382
     * @param {Number} pageY the y position.
383
     * @param {jQuery} drag the item being moved.
384
     */
385
    DragDropToTextQuestion.prototype.dragMove = function(pageX, pageY, drag) {
386
        var thisQ = this;
387
        this.getRoot().find('span.group' + this.getGroup(drag)).not('.beingdragged').each(function(i, dropNode) {
388
            var drop = $(dropNode);
389
            if (thisQ.isPointInDrop(pageX, pageY, drop)) {
390
                drop.addClass('valid-drag-over-drop');
391
            } else {
392
                drop.removeClass('valid-drag-over-drop');
393
            }
394
        });
395
    };
396
 
397
    /**
398
     * Called when user drops a drag item.
399
     *
400
     * @param {Number} pageX the x position.
401
     * @param {Number} pageY the y position.
402
     * @param {jQuery} drag the item being moved.
403
     */
404
    DragDropToTextQuestion.prototype.dragEnd = function(pageX, pageY, drag) {
405
        var thisQ = this,
406
            root = this.getRoot(),
407
            placed = false;
408
        root.find('span.group' + this.getGroup(drag)).not('.beingdragged').each(function(i, dropNode) {
409
            if (placed) {
410
                return false;
411
            }
412
            const dropZone = $(dropNode);
413
            if (!thisQ.isPointInDrop(pageX, pageY, dropZone)) {
414
                // Not this drop zone.
415
                return true;
416
            }
417
            let drop = null;
418
            if (dropZone.hasClass('placed')) {
419
                // This is an placed drag item in a drop.
420
                dropZone.removeClass('valid-drag-over-drop');
421
                // Get the correct drop.
422
                drop = thisQ.getDrop(drag, thisQ.getClassnameNumericSuffix(dropZone, 'inplace'));
423
            } else {
424
                // Empty drop.
425
                drop = dropZone;
426
            }
427
            // Now put this drag into the drop.
428
            drop.removeClass('valid-drag-over-drop');
429
            thisQ.sendDragToDrop(drag, drop);
430
            placed = true;
431
            return false; // Stop the each() here.
432
        });
433
        if (!placed) {
434
            this.sendDragHome(drag);
435
        }
436
    };
437
 
438
    /**
439
     * Animate a drag item into a given place (or back home).
440
     *
441
     * @param {jQuery|null} drag the item to place. If null, clear the place.
442
     * @param {jQuery} drop the place to put it.
443
     */
444
    DragDropToTextQuestion.prototype.sendDragToDrop = function(drag, drop) {
445
        // Send drag home if there is no place in drop.
446
        if (this.getPlace(drop) === null) {
447
            this.sendDragHome(drag);
448
            return;
449
        }
450
 
451
        // Is there already a drag in this drop? if so, evict it.
452
        var oldDrag = this.getCurrentDragInPlace(this.getPlace(drop));
453
        if (oldDrag.length !== 0) {
454
            var currentPlace = this.getClassnameNumericSuffix(oldDrag, 'inplace');
455
            // When infinite group and there is already a drag in a drop, reject the exact clone in the same drop.
456
            if (this.hasDropSameDrag(currentPlace, drop, oldDrag, drag)) {
457
                this.sendDragHome(drag);
458
                return;
459
            }
460
            var hiddenDrop = this.getDrop(oldDrag, currentPlace);
461
            hiddenDrop.addClass('active');
462
            oldDrag.addClass('beingdragged');
463
            oldDrag.offset(hiddenDrop.offset());
464
            this.sendDragHome(oldDrag);
465
        }
466
 
467
        if (drag.length === 0) {
468
            this.setInputValue(this.getPlace(drop), 0);
469
            if (drop.data('isfocus')) {
470
                drop.focus();
471
            }
472
        } else {
473
            // Prevent the drag item drop into two drop-zone.
474
            if (this.getClassnameNumericSuffix(drag, 'inplace')) {
475
                return;
476
            }
477
 
478
            this.setInputValue(this.getPlace(drop), this.getChoice(drag));
479
            drag.removeClass('unplaced')
480
                .addClass('placed inplace' + this.getPlace(drop));
481
            drag.attr('tabindex', 0);
482
            this.animateTo(drag, drop);
483
        }
484
    };
485
 
486
    /**
487
     * When infinite group and there is already a drag in a drop, reject the exact clone in the same drop.
488
     *
489
     * @param {int} currentPlace  the position of the current drop.
490
     * @param {jQuery} drop the drop containing a drag.
491
     * @param {jQuery} oldDrag the drag already placed in drop.
492
     * @param {jQuery} drag the new drag which is exactly the same (clone) as oldDrag .
493
     * @returns {boolean}
494
     */
495
    DragDropToTextQuestion.prototype.hasDropSameDrag = function(currentPlace, drop, oldDrag, drag) {
496
        if (drag.hasClass('infinite')) {
497
            return drop.hasClass('place' + currentPlace) &&
498
                this.getGroup(drag) === this.getGroup(drop) &&
499
                this.getChoice(drag) === this.getChoice(oldDrag) &&
500
                this.getGroup(drag) === this.getGroup(oldDrag);
501
        }
502
        return false;
503
    };
504
 
505
    /**
506
     * Animate a drag back to its home.
507
     *
508
     * @param {jQuery} drag the item being moved.
509
     */
510
    DragDropToTextQuestion.prototype.sendDragHome = function(drag) {
511
        var currentPlace = this.getClassnameNumericSuffix(drag, 'inplace');
512
        if (currentPlace !== null) {
513
            drag.removeClass('inplace' + currentPlace);
514
        }
515
        drag.data('unplaced', true);
516
 
517
        this.animateTo(drag, this.getDragHome(this.getGroup(drag), this.getChoice(drag)));
518
    };
519
 
520
    /**
521
     * Handles keyboard events on drops.
522
     *
523
     * Drops are focusable. Once focused, right/down/space switches to the next choice, and
524
     * left/up switches to the previous. Escape clear.
525
     *
526
     * @param {KeyboardEvent} e
527
     */
528
    DragDropToTextQuestion.prototype.handleKeyPress = function(e) {
529
        var drop = $(e.target).closest('.drop');
530
        if (drop.length === 0) {
531
            var placedDrag = $(e.target);
532
            var currentPlace = this.getClassnameNumericSuffix(placedDrag, 'inplace');
533
            if (currentPlace !== null) {
534
                drop = this.getDrop(placedDrag, currentPlace);
535
            }
536
        }
537
        var currentDrag = this.getCurrentDragInPlace(this.getPlace(drop)),
538
            nextDrag = $();
539
 
540
        switch (e.keyCode) {
541
            case keys.space:
542
            case keys.arrowRight:
543
            case keys.arrowDown:
544
                nextDrag = this.getNextDrag(this.getGroup(drop), currentDrag);
545
                break;
546
 
547
            case keys.arrowLeft:
548
            case keys.arrowUp:
549
                nextDrag = this.getPreviousDrag(this.getGroup(drop), currentDrag);
550
                break;
551
 
552
            case keys.escape:
553
                break;
554
 
555
            default:
556
                questionManager.isKeyboardNavigation = false;
557
                return; // To avoid the preventDefault below.
558
        }
559
 
560
        if (nextDrag.length) {
561
            nextDrag.data('isfocus', true);
562
            nextDrag.addClass('beingdragged');
563
            var hiddenDrag = this.getDragClone(nextDrag);
564
            if (hiddenDrag.length) {
565
                if (nextDrag.hasClass('infinite')) {
566
                    var noOfDrags = this.noOfDropsInGroup(this.getGroup(nextDrag));
567
                    var cloneDrags = this.getInfiniteDragClones(nextDrag, false);
568
                    if (cloneDrags.length < noOfDrags) {
569
                        var cloneDrag = nextDrag.clone();
570
                        cloneDrag.removeClass('beingdragged');
571
                        cloneDrag.removeAttr('tabindex');
572
                        hiddenDrag.after(cloneDrag);
573
                        questionManager.addEventHandlersToDrag(cloneDrag);
574
                        nextDrag.offset(cloneDrag.offset());
575
                    } else {
576
                        hiddenDrag.addClass('active');
577
                        nextDrag.offset(hiddenDrag.offset());
578
                    }
579
                } else {
580
                    hiddenDrag.addClass('active');
581
                    nextDrag.offset(hiddenDrag.offset());
582
                }
583
            }
584
        } else {
585
            drop.data('isfocus', true);
586
        }
587
 
588
        e.preventDefault();
589
        this.sendDragToDrop(nextDrag, drop);
590
    };
591
 
592
    /**
593
     * Choose the next drag in a group.
594
     *
595
     * @param {int} group which group.
596
     * @param {jQuery} drag current choice (empty jQuery if there isn't one).
597
     * @return {jQuery} the next drag in that group, or null if there wasn't one.
598
     */
599
    DragDropToTextQuestion.prototype.getNextDrag = function(group, drag) {
600
        var choice,
601
            numChoices = this.noOfChoicesInGroup(group);
602
 
603
        if (drag.length === 0) {
604
            choice = 1; // Was empty, so we want to select the first choice.
605
        } else {
606
            choice = this.getChoice(drag) + 1;
607
        }
608
 
609
        var next = this.getUnplacedChoice(group, choice);
610
        while (next.length === 0 && choice < numChoices) {
611
            choice++;
612
            next = this.getUnplacedChoice(group, choice);
613
        }
614
 
615
        return next;
616
    };
617
 
618
    /**
619
     * Choose the previous drag in a group.
620
     *
621
     * @param {int} group which group.
622
     * @param {jQuery} drag current choice (empty jQuery if there isn't one).
623
     * @return {jQuery} the next drag in that group, or null if there wasn't one.
624
     */
625
    DragDropToTextQuestion.prototype.getPreviousDrag = function(group, drag) {
626
        var choice;
627
 
628
        if (drag.length === 0) {
629
            choice = this.noOfChoicesInGroup(group);
630
        } else {
631
            choice = this.getChoice(drag) - 1;
632
        }
633
 
634
        var previous = this.getUnplacedChoice(group, choice);
635
        while (previous.length === 0 && choice > 1) {
636
            choice--;
637
            previous = this.getUnplacedChoice(group, choice);
638
        }
639
 
640
        // Does this choice exist?
641
        return previous;
642
    };
643
 
644
    /**
645
     * Animate an object to the given destination.
646
     *
647
     * @param {jQuery} drag the element to be animated.
648
     * @param {jQuery} target element marking the place to move it to.
649
     */
650
    DragDropToTextQuestion.prototype.animateTo = function(drag, target) {
651
        var currentPos = drag.offset(),
652
            targetPos = target.offset(),
653
            thisQ = this;
654
 
655
        M.util.js_pending('qtype_ddwtos-animate-' + thisQ.containerId);
656
        // Animate works in terms of CSS position, whereas locating an object
657
        // on the page works best with jQuery offset() function. So, to get
658
        // the right target position, we work out the required change in
659
        // offset() and then add that to the current CSS position.
660
        drag.animate(
661
            {
662
                left: parseInt(drag.css('left')) + targetPos.left - currentPos.left,
663
                top: parseInt(drag.css('top')) + targetPos.top - currentPos.top
664
            },
665
            {
666
                duration: 'fast',
667
                done: function() {
668
                    $('body').trigger('qtype_ddwtos-dragmoved', [drag, target, thisQ]);
669
                    M.util.js_complete('qtype_ddwtos-animate-' + thisQ.containerId);
670
                }
671
            }
672
        );
673
    };
674
 
675
    /**
676
     * Detect if a point is inside a given DOM node.
677
     *
678
     * @param {Number} pageX the x position.
679
     * @param {Number} pageY the y position.
680
     * @param {jQuery} drop the node to check (typically a drop).
681
     * @return {boolean} whether the point is inside the node.
682
     */
683
    DragDropToTextQuestion.prototype.isPointInDrop = function(pageX, pageY, drop) {
684
        var position = drop.offset();
685
        return pageX >= position.left && pageX < position.left + drop.width()
686
                && pageY >= position.top && pageY < position.top + drop.height();
687
    };
688
 
689
    /**
690
     * Set the value of the hidden input for a place, to record what is currently there.
691
     *
692
     * @param {int} place which place to set the input value for.
693
     * @param {int} choice the value to set.
694
     */
695
    DragDropToTextQuestion.prototype.setInputValue = function(place, choice) {
696
        this.getRoot().find('input.placeinput.place' + place).val(choice);
697
    };
698
 
699
    /**
700
     * Get the outer div for this question.
701
     *
702
     * @returns {jQuery} containing that div.
703
     */
704
    DragDropToTextQuestion.prototype.getRoot = function() {
705
        return $(document.getElementById(this.containerId));
706
    };
707
 
708
    /**
709
     * Get drag home for a given choice.
710
     *
711
     * @param {int} group the group.
712
     * @param {int} choice the choice number.
713
     * @returns {jQuery} containing that div.
714
     */
715
    DragDropToTextQuestion.prototype.getDragHome = function(group, choice) {
716
        if (!this.getRoot().find('.draghome.dragplaceholder.group' + group + '.choice' + choice).is(':visible')) {
717
            return this.getRoot().find('.draggrouphomes' + group +
718
                ' span.draghome.infinite' +
719
                '.choice' + choice +
720
                '.group' + group);
721
        }
722
        return this.getRoot().find('.draghome.dragplaceholder.group' + group + '.choice' + choice);
723
    };
724
 
725
    /**
726
     * Get an unplaced choice for a particular group.
727
     *
728
     * @param {int} group the group.
729
     * @param {int} choice the choice number.
730
     * @returns {jQuery} jQuery wrapping the unplaced choice. If there isn't one, the jQuery will be empty.
731
     */
732
    DragDropToTextQuestion.prototype.getUnplacedChoice = function(group, choice) {
733
        return this.getRoot().find('.draghome.group' + group + '.choice' + choice + '.unplaced').slice(0, 1);
734
    };
735
 
736
    /**
737
     * Get the drag that is currently in a given place.
738
     *
739
     * @param {int} place the place number.
740
     * @return {jQuery} the current drag (or an empty jQuery if none).
741
     */
742
    DragDropToTextQuestion.prototype.getCurrentDragInPlace = function(place) {
743
        return this.getRoot().find('span.draghome.inplace' + place);
744
    };
745
 
746
    /**
747
     * Return the number of blanks in a given group.
748
     *
749
     * @param {int} group the group number.
750
     * @returns {int} the number of drops.
751
     */
752
    DragDropToTextQuestion.prototype.noOfDropsInGroup = function(group) {
753
        return this.getRoot().find('.drop.group' + group).length;
754
    };
755
 
756
    /**
757
     * Return the number of choices in a given group.
758
     *
759
     * @param {int} group the group number.
760
     * @returns {int} the number of choices.
761
     */
762
    DragDropToTextQuestion.prototype.noOfChoicesInGroup = function(group) {
763
        return this.getRoot().find('.draghome.group' + group).length;
764
    };
765
 
766
    /**
767
     * Return the number at the end of the CSS class name with the given prefix.
768
     *
769
     * @param {jQuery} node
770
     * @param {String} prefix name prefix
771
     * @returns {Number|null} the suffix if found, else null.
772
     */
773
    DragDropToTextQuestion.prototype.getClassnameNumericSuffix = function(node, prefix) {
774
        var classes = node.attr('class');
775
        if (classes !== undefined && classes !== '') {
776
            var classesArr = classes.split(' ');
777
            for (var index = 0; index < classesArr.length; index++) {
778
                var patt1 = new RegExp('^' + prefix + '([0-9])+$');
779
                if (patt1.test(classesArr[index])) {
780
                    var patt2 = new RegExp('([0-9])+$');
781
                    var match = patt2.exec(classesArr[index]);
782
                    return Number(match[0]);
783
                }
784
            }
785
        }
786
        return null;
787
    };
788
 
789
    /**
790
     * Get the choice number of a drag.
791
     *
792
     * @param {jQuery} drag the drag.
793
     * @returns {Number} the choice number.
794
     */
795
    DragDropToTextQuestion.prototype.getChoice = function(drag) {
796
        return this.getClassnameNumericSuffix(drag, 'choice');
797
    };
798
 
799
    /**
800
     * Given a DOM node that is significant to this question
801
     * (drag, drop, ...) get the group it belongs to.
802
     *
803
     * @param {jQuery} node a DOM node.
804
     * @returns {Number} the group it belongs to.
805
     */
806
    DragDropToTextQuestion.prototype.getGroup = function(node) {
807
        return this.getClassnameNumericSuffix(node, 'group');
808
    };
809
 
810
    /**
811
     * Get the place number of a drop, or its corresponding hidden input.
812
     *
813
     * @param {jQuery} node the DOM node.
814
     * @returns {Number} the place number.
815
     */
816
    DragDropToTextQuestion.prototype.getPlace = function(node) {
817
        return this.getClassnameNumericSuffix(node, 'place');
818
    };
819
 
820
    /**
821
     * Get drag clone for a given drag.
822
     *
823
     * @param {jQuery} drag the drag.
824
     * @returns {jQuery} the drag's clone.
825
     */
826
    DragDropToTextQuestion.prototype.getDragClone = function(drag) {
827
        return this.getRoot().find('.draggrouphomes' +
828
            this.getGroup(drag) +
829
            ' span.draghome' +
830
            '.choice' + this.getChoice(drag) +
831
            '.group' + this.getGroup(drag) +
832
            '.dragplaceholder');
833
    };
834
 
835
    /**
836
     * Get infinite drag clones for given drag.
837
     *
838
     * @param {jQuery} drag the drag.
839
     * @param {Boolean} inHome in the home area or not.
840
     * @returns {jQuery} the drag's clones.
841
     */
842
    DragDropToTextQuestion.prototype.getInfiniteDragClones = function(drag, inHome) {
843
        if (inHome) {
844
            return this.getRoot().find('.draggrouphomes' +
845
                this.getGroup(drag) +
846
                ' span.draghome' +
847
                '.choice' + this.getChoice(drag) +
848
                '.group' + this.getGroup(drag) +
849
                '.infinite').not('.dragplaceholder');
850
        }
851
        return this.getRoot().find('span.draghome' +
852
            '.choice' + this.getChoice(drag) +
853
            '.group' + this.getGroup(drag) +
854
            '.infinite').not('.dragplaceholder');
855
    };
856
 
857
    /**
858
     * Get drop for a given drag and place.
859
     *
860
     * @param {jQuery} drag the drag.
861
     * @param {Integer} currentPlace the current place of drag.
862
     * @returns {jQuery} the drop's clone.
863
     */
864
    DragDropToTextQuestion.prototype.getDrop = function(drag, currentPlace) {
865
        return this.getRoot().find('.drop.group' + this.getGroup(drag) + '.place' + currentPlace);
866
    };
867
 
868
    /**
869
     * Singleton that tracks all the DragDropToTextQuestions on this page, and deals
870
     * with event dispatching.
871
     *
872
     * @type {Object}
873
     */
874
    var questionManager = {
875
        /**
876
         * {boolean} used to ensure the event handlers are only initialised once per page.
877
         */
878
        eventHandlersInitialised: false,
879
 
880
        /**
881
         * {Object} ensures that the drag event handlers are only initialised once per question,
882
         * indexed by containerId (id on the .que div).
883
         */
884
        dragEventHandlersInitialised: {},
885
 
886
        /**
887
         * {boolean} is keyboard navigation or not.
888
         */
889
        isKeyboardNavigation: false,
890
 
891
        /**
892
         * {DragDropToTextQuestion[]} all the questions on this page, indexed by containerId (id on the .que div).
893
         */
894
        questions: {},
895
 
896
        /**
897
         * Initialise questions.
898
         *
899
         * @param {String} containerId id of the outer div for this question.
900
         * @param {boolean} readOnly whether the question is being displayed read-only.
901
         */
902
        init: function(containerId, readOnly) {
903
            questionManager.questions[containerId] = new DragDropToTextQuestion(containerId, readOnly);
904
            if (!questionManager.eventHandlersInitialised) {
905
                questionManager.setupEventHandlers();
906
                questionManager.eventHandlersInitialised = true;
907
            }
908
            if (!questionManager.dragEventHandlersInitialised.hasOwnProperty(containerId)) {
909
                questionManager.dragEventHandlersInitialised[containerId] = true;
910
                // We do not use the body event here to prevent the other event on Mobile device, such as scroll event.
911
                var questionContainer = document.getElementById(containerId);
912
                if (questionContainer.classList.contains('ddwtos') &&
913
                    !questionContainer.classList.contains('qtype_ddwtos-readonly')) {
914
                    // TODO: Convert all the jQuery selectors and events to native Javascript.
915
                    questionManager.addEventHandlersToDrag($(questionContainer).find('span.draghome'));
916
                }
917
            }
918
        },
919
 
920
        /**
921
         * Set up the event handlers that make this question type work. (Done once per page.)
922
         */
923
        setupEventHandlers: function() {
924
            $('body')
925
                .on('keydown',
926
                    '.que.ddwtos:not(.qtype_ddwtos-readonly) span.drop',
927
                    questionManager.handleKeyPress)
928
                .on('keydown',
929
                    '.que.ddwtos:not(.qtype_ddwtos-readonly) span.draghome.placed:not(.beingdragged)',
930
                    questionManager.handleKeyPress)
931
                .on('qtype_ddwtos-dragmoved', questionManager.handleDragMoved);
932
        },
933
 
934
        /**
935
         * Binding the drag/touch event again for newly created element.
936
         *
937
         * @param {jQuery} element Element to bind the event
938
         */
939
        addEventHandlersToDrag: function(element) {
940
            // Unbind all the mousedown and touchstart events to prevent double binding.
941
            element.unbind('mousedown touchstart');
942
            element.on('mousedown touchstart', questionManager.handleDragStart);
943
        },
944
 
945
        /**
946
         * Handle mouse down / touch start on drags.
947
         * @param {Event} e the DOM event.
948
         */
949
        handleDragStart: function(e) {
950
            e.preventDefault();
951
            var question = questionManager.getQuestionForEvent(e);
952
            if (question) {
953
                question.handleDragStart(e);
954
            }
955
        },
956
 
957
        /**
958
         * Handle key down / press on drops.
959
         * @param {KeyboardEvent} e
960
         */
961
        handleKeyPress: function(e) {
962
            if (questionManager.isKeyboardNavigation) {
963
                return;
964
            }
965
            questionManager.isKeyboardNavigation = true;
966
            var question = questionManager.getQuestionForEvent(e);
967
            if (question) {
968
                question.handleKeyPress(e);
969
            }
970
        },
971
 
972
        /**
973
         * Given an event, work out which question it affects.
974
         *
975
         * @param {Event} e the event.
976
         * @returns {DragDropToTextQuestion|undefined} The question, or undefined.
977
         */
978
        getQuestionForEvent: function(e) {
979
            var containerId = $(e.currentTarget).closest('.que.ddwtos').attr('id');
980
            return questionManager.questions[containerId];
981
        },
982
 
983
        /**
984
         * Handle when drag moved.
985
         *
986
         * @param {Event} e the event.
987
         * @param {jQuery} drag the drag
988
         * @param {jQuery} target the target
989
         * @param {DragDropToTextQuestion} thisQ the question.
990
         */
991
        handleDragMoved: function(e, drag, target, thisQ) {
992
            drag.removeClass('beingdragged');
993
            drag.css('top', '').css('left', '');
994
            target.after(drag);
995
            target.removeClass('active');
996
            if (typeof drag.data('unplaced') !== 'undefined' && drag.data('unplaced') === true) {
997
                drag.removeClass('placed').addClass('unplaced');
998
                drag.removeAttr('tabindex');
999
                drag.removeData('unplaced');
1000
                if (drag.hasClass('infinite') && thisQ.getInfiniteDragClones(drag, true).length > 1) {
1001
                    thisQ.getInfiniteDragClones(drag, true).first().remove();
1002
                }
1003
            }
1004
            if (typeof drag.data('isfocus') !== 'undefined' && drag.data('isfocus') === true) {
1005
                drag.focus();
1006
                drag.removeData('isfocus');
1007
            }
1008
            if (typeof target.data('isfocus') !== 'undefined' && target.data('isfocus') === true) {
1009
                target.removeData('isfocus');
1010
            }
1011
            if (questionManager.isKeyboardNavigation) {
1012
                questionManager.isKeyboardNavigation = false;
1013
            }
1014
            if (thisQ.isQuestionInteracted()) {
1015
                // The user has interacted with the draggable items. We need to mark the form as dirty.
1016
                questionManager.handleFormDirty();
1017
                // Save the new answered value.
1018
                thisQ.questionAnswer = thisQ.getQuestionAnsweredValues();
1019
            }
1020
        },
1021
 
1022
        /**
1023
         * Handle when the form is dirty.
1024
         */
1025
        handleFormDirty: function() {
1026
            const responseForm = document.getElementById('responseform');
1027
            FormChangeChecker.markFormAsDirty(responseForm);
1028
        }
1029
    };
1030
 
1031
    /**
1032
     * @alias module:qtype_ddwtos/ddwtos
1033
     */
1034
    return {
1035
        /**
1036
         * Initialise one drag-drop into text question.
1037
         *
1038
         * @param {String} containerId id of the outer div for this question.
1039
         * @param {boolean} readOnly whether the question is being displayed read-only.
1040
         */
1041
        init: questionManager.init
1042
    };
1043
});