1 // This file is part of Moodle - http://moodle.org/
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.
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.
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/>.
17 * JavaScript to allow dragging options to slots (using mouse down or touch) or tab through slots using keyboard.
19 * @module qtype_ddimageortext/question
20 * @package qtype_ddimageortext
21 * @copyright 2018 The Open University
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 define(['jquery', 'core/dragdrop', 'core/key_codes'], function($, dragDrop, keys) {
29 * Initialise one drag-drop onto image question.
31 * @param {String} containerId id of the outer div for this question.
32 * @param {boolean} readOnly whether the question is being displayed read-only.
33 * @param {Array} places Information about the drop places.
36 function DragDropOntoImageQuestion(containerId, readOnly, places) {
37 this.containerId = containerId;
38 M.util.js_pending('qtype_ddimageortext-init-' + this.containerId);
40 this.allImagesLoaded = false;
41 this.imageLoadingTimeoutId = null;
42 this.isPrinting = false;
44 this.getRoot().addClass('qtype_ddimageortext-readonly');
48 this.getNotYetLoadedImages().one('load', function() {
49 thisQ.waitForAllImagesToBeLoaded();
51 this.waitForAllImagesToBeLoaded();
55 * Waits until all images are loaded before calling setupQuestion().
57 * This function is called from the onLoad of each image, and also polls with
58 * a time-out, because image on-loads are allegedly unreliable.
60 DragDropOntoImageQuestion.prototype.waitForAllImagesToBeLoaded = function() {
63 // This method may get called multiple times (via image on-loads or timeouts.
64 // If we are already done, don't do it again.
65 if (this.allImagesLoaded) {
69 // Clear any current timeout, if set.
70 if (this.imageLoadingTimeoutId !== null) {
71 clearTimeout(this.imageLoadingTimeoutId);
74 // If we have not yet loaded all images, set a timeout to
75 // call ourselves again, since apparently images on-load
77 if (this.getNotYetLoadedImages().length > 0) {
78 this.imageLoadingTimeoutId = setTimeout(function() {
79 thisQ.waitForAllImagesToBeLoaded();
84 // We now have all images. Carry on, but only after giving the layout a chance to settle down.
85 this.allImagesLoaded = true;
86 thisQ.setupQuestion();
90 * Get any of the images in the drag-drop area that are not yet fully loaded.
92 * @returns {jQuery} those images.
94 DragDropOntoImageQuestion.prototype.getNotYetLoadedImages = function() {
96 return this.getRoot().find('.ddarea img').not(function(i, imgNode) {
97 return thisQ.imageIsLoaded(imgNode);
102 * Check if an image has loaded without errors.
104 * @param {HTMLImageElement} imgElement an image.
105 * @returns {boolean} true if this image has loaded without errors.
107 DragDropOntoImageQuestion.prototype.imageIsLoaded = function(imgElement) {
108 return imgElement.complete && imgElement.naturalHeight !== 0;
112 * Set up the question, once all images have been loaded.
114 DragDropOntoImageQuestion.prototype.setupQuestion = function() {
115 this.resizeAllDragsAndDrops();
117 this.positionDragsAndDrops();
118 M.util.js_complete('qtype_ddimageortext-init-' + this.containerId);
122 * In each group, resize all the items to be the same size.
124 DragDropOntoImageQuestion.prototype.resizeAllDragsAndDrops = function() {
126 this.getRoot().find('.draghomes > div').each(function(i, node) {
127 thisQ.resizeAllDragsAndDropsInGroup(
128 thisQ.getClassnameNumericSuffix($(node), 'dragitemgroup'));
133 * In a given group, set all the drags and drops to be the same size.
135 * @param {int} group the group number.
137 DragDropOntoImageQuestion.prototype.resizeAllDragsAndDropsInGroup = function(group) {
138 var root = this.getRoot(),
139 dragHomes = root.find('.dragitemgroup' + group + ' .draghome'),
143 // Find the maximum size of any drag in this groups.
144 dragHomes.each(function(i, drag) {
145 maxWidth = Math.max(maxWidth, Math.ceil(drag.offsetWidth));
146 maxHeight = Math.max(maxHeight, Math.ceil(drag.offsetHeight));
149 // The size we will want to set is a bit bigger than this.
153 // Set each drag home to that size.
154 dragHomes.each(function(i, drag) {
155 var left = Math.round((maxWidth - drag.offsetWidth) / 2),
156 top = Math.floor((maxHeight - drag.offsetHeight) / 2);
157 // Set top and left padding so the item is centred.
159 'padding-left': left + 'px',
160 'padding-right': (maxWidth - drag.offsetWidth - left) + 'px',
161 'padding-top': top + 'px',
162 'padding-bottom': (maxHeight - drag.offsetHeight - top) + 'px'
166 // Create the drops and make them the right size.
167 for (var i in this.places) {
168 if (!this.places.hasOwnProperty((i))) {
171 var place = this.places[i],
173 if (parseInt(place.group) !== group) {
177 label = M.util.get_string('blank', 'qtype_ddimageortext');
179 root.find('.dropzones').append('<div class="dropzone active group' + place.group +
180 ' place' + i + '" tabindex="0">' +
181 '<span class="accesshide">' + label + '</span> </div>');
182 root.find('.dropzone.place' + i).width(maxWidth - 2).height(maxHeight - 2);
187 * Invisible 'drag homes' are output by the renderer. These have the same properties
188 * as the drag items but are invisible. We clone these invisible elements to make the
191 DragDropOntoImageQuestion.prototype.cloneDrags = function() {
193 thisQ.getRoot().find('.draghome').each(function(index, dragHome) {
194 var drag = $(dragHome);
195 var placeHolder = drag.clone();
196 placeHolder.removeClass();
197 placeHolder.addClass('draghome choice' +
198 thisQ.getChoice(drag) + ' group' +
199 thisQ.getGroup(drag) + ' dragplaceholder');
200 drag.before(placeHolder);
205 * Clone drag item for one choice.
207 * @param {jQuery} dragHome the drag home to clone.
209 DragDropOntoImageQuestion.prototype.cloneDragsForOneChoice = function(dragHome) {
210 if (dragHome.hasClass('infinite')) {
211 var noOfDrags = this.noOfDropsInGroup(this.getGroup(dragHome));
212 for (var i = 0; i < noOfDrags; i++) {
213 this.cloneDrag(dragHome);
216 this.cloneDrag(dragHome);
223 * @param {jQuery} dragHome
225 DragDropOntoImageQuestion.prototype.cloneDrag = function(dragHome) {
226 var drag = dragHome.clone();
227 drag.removeClass('draghome')
228 .addClass('drag unplaced moodle-has-zindex')
229 .offset(dragHome.offset());
230 this.getRoot().find('.dragitems').append(drag);
234 * Update the position of drags.
236 DragDropOntoImageQuestion.prototype.positionDragsAndDrops = function() {
238 root = this.getRoot(),
239 bgRatio = this.bgRatio();
241 // Move the drops into position.
242 root.find('.ddarea .dropzone').each(function(i, dropNode) {
243 var drop = $(dropNode),
244 place = thisQ.places[thisQ.getPlace(drop)];
245 // The xy values come from PHP as strings, so we need parseInt to stop JS doing string concatenation.
246 drop.css('left', parseInt(place.xy[0]) * bgRatio)
247 .css('top', parseInt(place.xy[1]) * bgRatio);
248 drop.data('originX', parseInt(place.xy[0]))
249 .data('originY', parseInt(place.xy[1]));
250 thisQ.handleElementScale(drop, 'left top');
253 // First move all items back home.
254 root.find('.draghome').not('.dragplaceholder').each(function(i, dragNode) {
255 var drag = $(dragNode),
256 currentPlace = thisQ.getClassnameNumericSuffix(drag, 'inplace');
257 drag.addClass('unplaced')
258 .removeClass('placed');
259 drag.removeAttr('tabindex');
260 if (currentPlace !== null) {
261 drag.removeClass('inplace' + currentPlace);
265 // Then place the ones that should be placed.
266 root.find('input.placeinput').each(function(i, inputNode) {
267 var input = $(inputNode),
268 choice = input.val();
269 if (choice.length === 0 || (choice.length > 0 && choice === '0')) {
270 // No item in this place.
274 var place = thisQ.getPlace(input);
275 // Get the unplaced drag.
276 var unplacedDrag = thisQ.getUnplacedChoice(thisQ.getGroup(input), choice);
277 // Get the clone of the drag.
278 var hiddenDrag = thisQ.getDragClone(unplacedDrag);
279 if (hiddenDrag.length) {
280 if (unplacedDrag.hasClass('infinite')) {
281 var noOfDrags = thisQ.noOfDropsInGroup(thisQ.getGroup(unplacedDrag));
282 var cloneDrags = thisQ.getInfiniteDragClones(unplacedDrag, false);
283 if (cloneDrags.length < noOfDrags) {
284 var cloneDrag = unplacedDrag.clone();
285 cloneDrag.removeClass('beingdragged');
286 cloneDrag.removeAttr('tabindex');
287 hiddenDrag.after(cloneDrag);
289 hiddenDrag.addClass('active');
292 hiddenDrag.addClass('active');
296 // Send the drag to drop.
297 var drop = root.find('.dropzone.place' + place);
298 thisQ.sendDragToDrop(unplacedDrag, drop);
303 * Handles the start of dragging an item.
305 * @param {Event} e the touch start or mouse down event.
307 DragDropOntoImageQuestion.prototype.handleDragStart = function(e) {
309 drag = $(e.target).closest('.draghome'),
310 currentIndex = this.calculateZIndex(),
311 newIndex = currentIndex + 2;
313 var info = dragDrop.prepare(e);
318 drag.addClass('beingdragged').css('transform', '').css('z-index', newIndex);
319 var currentPlace = this.getClassnameNumericSuffix(drag, 'inplace');
320 if (currentPlace !== null) {
321 this.setInputValue(currentPlace, 0);
322 drag.removeClass('inplace' + currentPlace);
323 var hiddenDrop = thisQ.getDrop(drag, currentPlace);
324 if (hiddenDrop.length) {
325 hiddenDrop.addClass('active');
326 drag.offset(hiddenDrop.offset());
329 var hiddenDrag = thisQ.getDragClone(drag);
330 if (hiddenDrag.length) {
331 if (drag.hasClass('infinite')) {
332 var noOfDrags = this.noOfDropsInGroup(thisQ.getGroup(drag));
333 var cloneDrags = this.getInfiniteDragClones(drag, false);
334 if (cloneDrags.length < noOfDrags) {
335 var cloneDrag = drag.clone();
336 cloneDrag.removeClass('beingdragged');
337 cloneDrag.removeAttr('tabindex');
338 hiddenDrag.after(cloneDrag);
339 questionManager.addEventHandlersToDrag(cloneDrag);
340 drag.offset(cloneDrag.offset());
342 hiddenDrag.addClass('active');
343 drag.offset(hiddenDrag.offset());
346 hiddenDrag.addClass('active');
347 drag.offset(hiddenDrag.offset());
352 dragDrop.start(e, drag, function(x, y, drag) {
353 thisQ.dragMove(x, y, drag);
354 }, function(x, y, drag) {
355 thisQ.dragEnd(x, y, drag);
360 * Called whenever the currently dragged items moves.
362 * @param {Number} pageX the x position.
363 * @param {Number} pageY the y position.
364 * @param {jQuery} drag the item being moved.
366 DragDropOntoImageQuestion.prototype.dragMove = function(pageX, pageY, drag) {
368 this.getRoot().find('.dropzone.group' + this.getGroup(drag)).each(function(i, dropNode) {
369 var drop = $(dropNode);
370 if (thisQ.isPointInDrop(pageX, pageY, drop)) {
371 drop.addClass('valid-drag-over-drop');
373 drop.removeClass('valid-drag-over-drop');
376 this.getRoot().find('.draghome.placed.group' + this.getGroup(drag)).not('.beingdragged').each(function(i, dropNode) {
377 var drop = $(dropNode);
378 if (thisQ.isPointInDrop(pageX, pageY, drop) && !thisQ.isDragSameAsDrop(drag, drop)) {
379 drop.addClass('valid-drag-over-drop');
381 drop.removeClass('valid-drag-over-drop');
387 * Called when user drops a drag item.
389 * @param {Number} pageX the x position.
390 * @param {Number} pageY the y position.
391 * @param {jQuery} drag the item being moved.
393 DragDropOntoImageQuestion.prototype.dragEnd = function(pageX, pageY, drag) {
395 root = this.getRoot(),
397 root.find('.dropzone.group' + this.getGroup(drag)).each(function(i, dropNode) {
398 var drop = $(dropNode);
399 if (!thisQ.isPointInDrop(pageX, pageY, drop)) {
404 // Now put this drag into the drop.
405 drop.removeClass('valid-drag-over-drop');
406 thisQ.sendDragToDrop(drag, drop);
408 return false; // Stop the each() here.
411 root.find('.draghome.placed.group' + this.getGroup(drag)).not('.beingdragged').each(function(i, placedNode) {
412 var placedDrag = $(placedNode);
413 if (!thisQ.isPointInDrop(pageX, pageY, placedDrag) || thisQ.isDragSameAsDrop(drag, placedDrag)) {
414 // Not this placed drag.
418 // Now put this drag into the drop.
419 placedDrag.removeClass('valid-drag-over-drop');
420 var currentPlace = thisQ.getClassnameNumericSuffix(placedDrag, 'inplace');
421 var drop = thisQ.getDrop(drag, currentPlace);
422 thisQ.sendDragToDrop(drag, drop);
424 return false; // Stop the each() here.
428 this.sendDragHome(drag);
433 * Animate a drag item into a given place (or back home).
435 * @param {jQuery|null} drag the item to place. If null, clear the place.
436 * @param {jQuery} drop the place to put it.
438 DragDropOntoImageQuestion.prototype.sendDragToDrop = function(drag, drop) {
439 // Is there already a drag in this drop? if so, evict it.
440 var oldDrag = this.getCurrentDragInPlace(this.getPlace(drop));
441 if (oldDrag.length !== 0) {
442 oldDrag.addClass('beingdragged');
443 oldDrag.offset(oldDrag.offset());
444 var currentPlace = this.getClassnameNumericSuffix(oldDrag, 'inplace');
445 var hiddenDrop = this.getDrop(oldDrag, currentPlace);
446 hiddenDrop.addClass('active');
447 this.sendDragHome(oldDrag);
450 if (drag.length === 0) {
451 this.setInputValue(this.getPlace(drop), 0);
452 if (drop.data('isfocus')) {
456 this.setInputValue(this.getPlace(drop), this.getChoice(drag));
457 drag.removeClass('unplaced')
458 .addClass('placed inplace' + this.getPlace(drop));
459 drag.attr('tabindex', 0);
460 this.animateTo(drag, drop);
465 * Animate a drag back to its home.
467 * @param {jQuery} drag the item being moved.
469 DragDropOntoImageQuestion.prototype.sendDragHome = function(drag) {
470 var currentPlace = this.getClassnameNumericSuffix(drag, 'inplace');
471 if (currentPlace !== null) {
472 drag.removeClass('inplace' + currentPlace);
474 drag.data('unplaced', true);
476 this.animateTo(drag, this.getDragHome(this.getGroup(drag), this.getChoice(drag)));
480 * Handles keyboard events on drops.
482 * Drops are focusable. Once focused, right/down/space switches to the next choice, and
483 * left/up switches to the previous. Escape clear.
485 * @param {KeyboardEvent} e
487 DragDropOntoImageQuestion.prototype.handleKeyPress = function(e) {
488 var drop = $(e.target).closest('.dropzone');
489 if (drop.length === 0) {
490 var placedDrag = $(e.target);
491 var currentPlace = this.getClassnameNumericSuffix(placedDrag, 'inplace');
492 if (currentPlace !== null) {
493 drop = this.getDrop(placedDrag, currentPlace);
496 var currentDrag = this.getCurrentDragInPlace(this.getPlace(drop)),
501 case keys.arrowRight:
503 nextDrag = this.getNextDrag(this.getGroup(drop), currentDrag);
508 nextDrag = this.getPreviousDrag(this.getGroup(drop), currentDrag);
512 questionManager.isKeyboardNavigation = false;
516 questionManager.isKeyboardNavigation = false;
517 return; // To avoid the preventDefault below.
520 if (nextDrag.length) {
521 nextDrag.data('isfocus', true);
522 nextDrag.addClass('beingdragged');
523 var hiddenDrag = this.getDragClone(nextDrag);
524 if (hiddenDrag.length) {
525 if (nextDrag.hasClass('infinite')) {
526 var noOfDrags = this.noOfDropsInGroup(this.getGroup(nextDrag));
527 var cloneDrags = this.getInfiniteDragClones(nextDrag, false);
528 if (cloneDrags.length < noOfDrags) {
529 var cloneDrag = nextDrag.clone();
530 cloneDrag.removeClass('beingdragged');
531 cloneDrag.removeAttr('tabindex');
532 hiddenDrag.after(cloneDrag);
533 questionManager.addEventHandlersToDrag(cloneDrag);
534 nextDrag.offset(cloneDrag.offset());
536 hiddenDrag.addClass('active');
537 nextDrag.offset(hiddenDrag.offset());
540 hiddenDrag.addClass('active');
541 nextDrag.offset(hiddenDrag.offset());
545 drop.data('isfocus', true);
549 this.sendDragToDrop(nextDrag, drop);
553 * Choose the next drag in a group.
555 * @param {int} group which group.
556 * @param {jQuery} drag current choice (empty jQuery if there isn't one).
557 * @return {jQuery} the next drag in that group, or null if there wasn't one.
559 DragDropOntoImageQuestion.prototype.getNextDrag = function(group, drag) {
561 numChoices = this.noOfChoicesInGroup(group);
563 if (drag.length === 0) {
564 choice = 1; // Was empty, so we want to select the first choice.
566 choice = this.getChoice(drag) + 1;
569 var next = this.getUnplacedChoice(group, choice);
570 while (next.length === 0 && choice < numChoices) {
572 next = this.getUnplacedChoice(group, choice);
579 * Choose the previous drag in a group.
581 * @param {int} group which group.
582 * @param {jQuery} drag current choice (empty jQuery if there isn't one).
583 * @return {jQuery} the next drag in that group, or null if there wasn't one.
585 DragDropOntoImageQuestion.prototype.getPreviousDrag = function(group, drag) {
588 if (drag.length === 0) {
589 choice = this.noOfChoicesInGroup(group);
591 choice = this.getChoice(drag) - 1;
594 var previous = this.getUnplacedChoice(group, choice);
595 while (previous.length === 0 && choice > 1) {
597 previous = this.getUnplacedChoice(group, choice);
600 // Does this choice exist?
605 * Animate an object to the given destination.
607 * @param {jQuery} drag the element to be animated.
608 * @param {jQuery} target element marking the place to move it to.
610 DragDropOntoImageQuestion.prototype.animateTo = function(drag, target) {
611 var currentPos = drag.offset(),
612 targetPos = target.offset(),
615 M.util.js_pending('qtype_ddimageortext-animate-' + thisQ.containerId);
616 // Animate works in terms of CSS position, whereas locating an object
617 // on the page works best with jQuery offset() function. So, to get
618 // the right target position, we work out the required change in
619 // offset() and then add that to the current CSS position.
622 left: parseInt(drag.css('left')) + targetPos.left - currentPos.left,
623 top: parseInt(drag.css('top')) + targetPos.top - currentPos.top
628 $('body').trigger('qtype_ddimageortext-dragmoved', [drag, target, thisQ]);
629 M.util.js_complete('qtype_ddimageortext-animate-' + thisQ.containerId);
636 * Detect if a point is inside a given DOM node.
638 * @param {Number} pageX the x position.
639 * @param {Number} pageY the y position.
640 * @param {jQuery} drop the node to check (typically a drop).
641 * @return {boolean} whether the point is inside the node.
643 DragDropOntoImageQuestion.prototype.isPointInDrop = function(pageX, pageY, drop) {
644 var position = drop.offset();
645 if (drop.hasClass('draghome')) {
646 return pageX >= position.left && pageX < position.left + drop.outerWidth()
647 && pageY >= position.top && pageY < position.top + drop.outerHeight();
649 return pageX >= position.left && pageX < position.left + drop.width()
650 && pageY >= position.top && pageY < position.top + drop.height();
654 * Set the value of the hidden input for a place, to record what is currently there.
656 * @param {int} place which place to set the input value for.
657 * @param {int} choice the value to set.
659 DragDropOntoImageQuestion.prototype.setInputValue = function(place, choice) {
660 this.getRoot().find('input.placeinput.place' + place).val(choice);
664 * Get the outer div for this question.
666 * @returns {jQuery} containing that div.
668 DragDropOntoImageQuestion.prototype.getRoot = function() {
669 return $(document.getElementById(this.containerId));
673 * Get the img that is the background image.
674 * @returns {jQuery} containing that img.
676 DragDropOntoImageQuestion.prototype.bgImage = function() {
677 return this.getRoot().find('img.dropbackground');
681 * Get drag home for a given choice.
683 * @param {int} group the group.
684 * @param {int} choice the choice number.
685 * @returns {jQuery} containing that div.
687 DragDropOntoImageQuestion.prototype.getDragHome = function(group, choice) {
688 if (!this.getRoot().find('.draghome.dragplaceholder.group' + group + '.choice' + choice).is(':visible')) {
689 return this.getRoot().find('.dragitemgroup' + group +
690 ' .draghome.infinite' +
694 return this.getRoot().find('.draghome.dragplaceholder.group' + group + '.choice' + choice);
698 * Get an unplaced choice for a particular group.
700 * @param {int} group the group.
701 * @param {int} choice the choice number.
702 * @returns {jQuery} jQuery wrapping the unplaced choice. If there isn't one, the jQuery will be empty.
704 DragDropOntoImageQuestion.prototype.getUnplacedChoice = function(group, choice) {
705 return this.getRoot().find('.ddarea .draghome.group' + group + '.choice' + choice + '.unplaced').slice(0, 1);
709 * Get the drag that is currently in a given place.
711 * @param {int} place the place number.
712 * @return {jQuery} the current drag (or an empty jQuery if none).
714 DragDropOntoImageQuestion.prototype.getCurrentDragInPlace = function(place) {
715 return this.getRoot().find('.ddarea .draghome.inplace' + place);
719 * Return the number of blanks in a given group.
721 * @param {int} group the group number.
722 * @returns {int} the number of drops.
724 DragDropOntoImageQuestion.prototype.noOfDropsInGroup = function(group) {
725 return this.getRoot().find('.dropzone.group' + group).length;
729 * Return the number of choices in a given group.
731 * @param {int} group the group number.
732 * @returns {int} the number of choices.
734 DragDropOntoImageQuestion.prototype.noOfChoicesInGroup = function(group) {
735 return this.getRoot().find('.dragitemgroup' + group + ' .draghome').length;
739 * Return the number at the end of the CSS class name with the given prefix.
741 * @param {jQuery} node
742 * @param {String} prefix name prefix
743 * @returns {Number|null} the suffix if found, else null.
745 DragDropOntoImageQuestion.prototype.getClassnameNumericSuffix = function(node, prefix) {
746 var classes = node.attr('class');
747 if (classes !== '') {
748 var classesArr = classes.split(' ');
749 for (var index = 0; index < classesArr.length; index++) {
750 var patt1 = new RegExp('^' + prefix + '([0-9])+$');
751 if (patt1.test(classesArr[index])) {
752 var patt2 = new RegExp('([0-9])+$');
753 var match = patt2.exec(classesArr[index]);
754 return Number(match[0]);
762 * Get the choice number of a drag.
764 * @param {jQuery} drag the drag.
765 * @returns {Number} the choice number.
767 DragDropOntoImageQuestion.prototype.getChoice = function(drag) {
768 return this.getClassnameNumericSuffix(drag, 'choice');
772 * Given a DOM node that is significant to this question
773 * (drag, drop, ...) get the group it belongs to.
775 * @param {jQuery} node a DOM node.
776 * @returns {Number} the group it belongs to.
778 DragDropOntoImageQuestion.prototype.getGroup = function(node) {
779 return this.getClassnameNumericSuffix(node, 'group');
783 * Get the place number of a drop, or its corresponding hidden input.
785 * @param {jQuery} node the DOM node.
786 * @returns {Number} the place number.
788 DragDropOntoImageQuestion.prototype.getPlace = function(node) {
789 return this.getClassnameNumericSuffix(node, 'place');
793 * Get drag clone for a given drag.
795 * @param {jQuery} drag the drag.
796 * @returns {jQuery} the drag's clone.
798 DragDropOntoImageQuestion.prototype.getDragClone = function(drag) {
799 return this.getRoot().find('.dragitemgroup' +
800 this.getGroup(drag) +
802 '.choice' + this.getChoice(drag) +
803 '.group' + this.getGroup(drag) +
808 * Get infinite drag clones for given drag.
810 * @param {jQuery} drag the drag.
811 * @param {Boolean} inHome in the home area or not.
812 * @returns {jQuery} the drag's clones.
814 DragDropOntoImageQuestion.prototype.getInfiniteDragClones = function(drag, inHome) {
816 return this.getRoot().find('.dragitemgroup' +
817 this.getGroup(drag) +
819 '.choice' + this.getChoice(drag) +
820 '.group' + this.getGroup(drag) +
821 '.infinite').not('.dragplaceholder');
823 return this.getRoot().find('.draghome' +
824 '.choice' + this.getChoice(drag) +
825 '.group' + this.getGroup(drag) +
826 '.infinite').not('.dragplaceholder');
830 * Get drop for a given drag and place.
832 * @param {jQuery} drag the drag.
833 * @param {Integer} currentPlace the current place of drag.
834 * @returns {jQuery} the drop's clone.
836 DragDropOntoImageQuestion.prototype.getDrop = function(drag, currentPlace) {
837 return this.getRoot().find('.dropzone.group' + this.getGroup(drag) + '.place' + currentPlace);
841 * Handle when the window is resized.
843 DragDropOntoImageQuestion.prototype.handleResize = function() {
845 bgRatio = this.bgRatio();
846 if (this.isPrinting) {
850 this.getRoot().find('.ddarea .dropzone').each(function(i, dropNode) {
852 .css('left', parseInt($(dropNode).data('originX')) * parseFloat(bgRatio))
853 .css('top', parseInt($(dropNode).data('originY')) * parseFloat(bgRatio));
854 thisQ.handleElementScale(dropNode, 'left top');
857 this.getRoot().find('div.droparea .draghome').not('.beingdragged').each(function(key, drag) {
859 .css('left', parseFloat($(drag).data('originX')) * parseFloat(bgRatio))
860 .css('top', parseFloat($(drag).data('originY')) * parseFloat(bgRatio));
861 thisQ.handleElementScale(drag, 'left top');
866 * Return the background ratio.
868 * @returns {number} Background ratio.
870 DragDropOntoImageQuestion.prototype.bgRatio = function() {
871 var bgImg = this.bgImage();
872 var bgImgNaturalWidth = bgImg.get(0).naturalWidth;
873 var bgImgClientWidth = bgImg.width();
875 return bgImgClientWidth / bgImgNaturalWidth;
879 * Scale the drag if needed.
881 * @param {jQuery} element the item to place.
882 * @param {String} type scaling type
884 DragDropOntoImageQuestion.prototype.handleElementScale = function(element, type) {
885 var bgRatio = parseFloat(this.bgRatio());
886 if (this.isPrinting) {
890 '-webkit-transform': 'scale(' + bgRatio + ')',
891 '-moz-transform': 'scale(' + bgRatio + ')',
892 '-ms-transform': 'scale(' + bgRatio + ')',
893 '-o-transform': 'scale(' + bgRatio + ')',
894 'transform': 'scale(' + bgRatio + ')',
895 'transform-origin': type
900 * Calculate z-index value.
902 * @returns {number} z-index value
904 DragDropOntoImageQuestion.prototype.calculateZIndex = function() {
906 this.getRoot().find('.ddarea .dropzone, div.droparea .draghome').each(function(i, dropNode) {
907 dropNode = $(dropNode);
908 // Note that webkit browsers won't return the z-index value from the CSS stylesheet
909 // if the element doesn't have a position specified. Instead it'll return "auto".
910 var itemZIndex = dropNode.css('z-index') ? parseInt(dropNode.css('z-index')) : 0;
912 if (itemZIndex > zIndex) {
921 * Check that the drag is drop to it's clone.
923 * @param {jQuery} drag The drag.
924 * @param {jQuery} drop The drop.
927 DragDropOntoImageQuestion.prototype.isDragSameAsDrop = function(drag, drop) {
928 return this.getChoice(drag) === this.getChoice(drop) && this.getGroup(drag) === this.getGroup(drop);
932 * Singleton object that handles all the DragDropOntoImageQuestions
933 * on the page, and deals with event dispatching.
936 var questionManager = {
939 * {boolean} ensures that the event handlers are only initialised once per page.
941 eventHandlersInitialised: false,
944 * {boolean} is printing or not.
949 * {boolean} is keyboard navigation or not.
951 isKeyboardNavigation: false,
954 * {Object} all the questions on this page, indexed by containerId (id on the .que div).
956 questions: {}, // An object containing all the information about each question on the page.
959 * Initialise one question.
961 * @param {String} containerId the id of the div.que that contains this question.
962 * @param {boolean} readOnly whether the question is read-only.
963 * @param {Array} places data.
965 init: function(containerId, readOnly, places) {
966 questionManager.questions[containerId] =
967 new DragDropOntoImageQuestion(containerId, readOnly, places);
968 if (!questionManager.eventHandlersInitialised) {
969 questionManager.setupEventHandlers();
970 questionManager.eventHandlersInitialised = true;
975 * Set up the event handlers that make this question type work. (Done once per page.)
977 setupEventHandlers: function() {
978 // We do not use the body event here to prevent the other event on Mobile device, such as scroll event.
979 questionManager.addEventHandlersToDrag($('.que.ddimageortext:not(.qtype_ddimageortext-readonly) .draghome'));
982 '.que.ddimageortext:not(.qtype_ddimageortext-readonly) .dropzones .dropzone',
983 questionManager.handleKeyPress)
985 '.que.ddimageortext:not(.qtype_ddimageortext-readonly) .draghome.placed:not(.beingdragged)',
986 questionManager.handleKeyPress)
987 .on('qtype_ddimageortext-dragmoved', questionManager.handleDragMoved);
988 $(window).on('resize', function() {
989 questionManager.handleWindowResize(false);
991 window.addEventListener('beforeprint', function() {
992 questionManager.isPrinting = true;
993 questionManager.handleWindowResize(questionManager.isPrinting);
995 window.addEventListener('afterprint', function() {
996 questionManager.isPrinting = false;
997 questionManager.handleWindowResize(questionManager.isPrinting);
999 setTimeout(function() {
1000 questionManager.fixLayoutIfThingsMoved();
1005 * Binding the drag/touch event again for newly created element.
1007 * @param {jQuery} element Element to bind the event
1009 addEventHandlersToDrag: function(element) {
1010 // Unbind all the mousedown and touchstart events to prevent double binding.
1011 element.unbind('mousedown touchstart');
1012 element.on('mousedown touchstart', questionManager.handleDragStart);
1016 * Handle mouse down / touch start events on drags.
1017 * @param {Event} e the DOM event.
1019 handleDragStart: function(e) {
1021 var question = questionManager.getQuestionForEvent(e);
1023 question.handleDragStart(e);
1028 * Handle key down / press events on drags.
1029 * @param {KeyboardEvent} e
1031 handleKeyPress: function(e) {
1032 if (questionManager.isKeyboardNavigation) {
1035 questionManager.isKeyboardNavigation = true;
1036 var question = questionManager.getQuestionForEvent(e);
1038 question.handleKeyPress(e);
1043 * Handle when the window is resized.
1044 * @param {boolean} isPrinting
1046 handleWindowResize: function(isPrinting) {
1047 for (var containerId in questionManager.questions) {
1048 if (questionManager.questions.hasOwnProperty(containerId)) {
1049 questionManager.questions[containerId].isPrinting = isPrinting;
1050 questionManager.questions[containerId].handleResize();
1056 * Sometimes, despite our best efforts, things change in a way that cannot
1057 * be specifically caught (e.g. dock expanding or collapsing in Boost).
1058 * Therefore, we need to periodically check everything is in the right position.
1060 fixLayoutIfThingsMoved: function() {
1061 this.handleWindowResize(questionManager.isPrinting);
1062 // We use setTimeout after finishing work, rather than setInterval,
1063 // in case positioning things is slow. We want 100 ms gap
1064 // between executions, not what setInterval does.
1065 setTimeout(function() {
1066 questionManager.fixLayoutIfThingsMoved(questionManager.isPrinting);
1071 * Handle when drag moved.
1073 * @param {Event} e the event.
1074 * @param {jQuery} drag the drag
1075 * @param {jQuery} target the target
1076 * @param {DragDropOntoImageQuestion} thisQ the question.
1078 handleDragMoved: function(e, drag, target, thisQ) {
1079 drag.removeClass('beingdragged').css('z-index', '');
1080 drag.css('top', target.position().top).css('left', target.position().left);
1082 target.removeClass('active');
1083 if (typeof drag.data('unplaced') !== 'undefined' && drag.data('unplaced') === true) {
1084 drag.removeClass('placed').addClass('unplaced');
1085 drag.removeAttr('tabindex');
1086 drag.removeData('unplaced');
1089 .css('transform', '');
1090 if (drag.hasClass('infinite') && thisQ.getInfiniteDragClones(drag, true).length > 1) {
1091 thisQ.getInfiniteDragClones(drag, true).first().remove();
1094 drag.data('originX', target.data('originX')).data('originY', target.data('originY'));
1095 thisQ.handleElementScale(drag, 'left top');
1097 if (typeof drag.data('isfocus') !== 'undefined' && drag.data('isfocus') === true) {
1099 drag.removeData('isfocus');
1101 if (typeof target.data('isfocus') !== 'undefined' && target.data('isfocus') === true) {
1102 target.removeData('isfocus');
1104 if (questionManager.isKeyboardNavigation) {
1105 questionManager.isKeyboardNavigation = false;
1110 * Given an event, work out which question it effects.
1111 * @param {Event} e the event.
1112 * @returns {DragDropOntoImageQuestion|undefined} The question, or undefined.
1114 getQuestionForEvent: function(e) {
1115 var containerId = $(e.currentTarget).closest('.que.ddimageortext').attr('id');
1116 return questionManager.questions[containerId];
1121 * @alias module:qtype_ddimageortext/question
1125 * Initialise one drag-drop onto image question.
1127 * @param {String} containerId id of the outer div for this question.
1128 * @param {boolean} readOnly whether the question is being displayed read-only.
1129 * @param {Array} Information about the drop places.
1131 init: questionManager.init