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) {
369 this.getRoot().find('.dropzone.group' + this.getGroup(drag)).each(function(i, dropNode) {
370 var drop = $(dropNode);
371 if (thisQ.isPointInDrop(pageX, pageY, drop) && !highlighted) {
373 drop.addClass('valid-drag-over-drop');
375 drop.removeClass('valid-drag-over-drop');
378 this.getRoot().find('.draghome.placed.group' + this.getGroup(drag)).not('.beingdragged').each(function(i, dropNode) {
379 var drop = $(dropNode);
380 if (thisQ.isPointInDrop(pageX, pageY, drop) && !highlighted && !thisQ.isDragSameAsDrop(drag, drop)) {
382 drop.addClass('valid-drag-over-drop');
384 drop.removeClass('valid-drag-over-drop');
390 * Called when user drops a drag item.
392 * @param {Number} pageX the x position.
393 * @param {Number} pageY the y position.
394 * @param {jQuery} drag the item being moved.
396 DragDropOntoImageQuestion.prototype.dragEnd = function(pageX, pageY, drag) {
398 root = this.getRoot(),
401 // Looking for drag that was dropped on a dropzone.
402 root.find('.dropzone.group' + this.getGroup(drag)).each(function(i, dropNode) {
403 var drop = $(dropNode);
404 if (!thisQ.isPointInDrop(pageX, pageY, drop)) {
409 // Now put this drag into the drop.
410 drop.removeClass('valid-drag-over-drop');
411 thisQ.sendDragToDrop(drag, drop);
413 return false; // Stop the each() here.
417 // Looking for drag that was dropped on a placed drag.
418 root.find('.draghome.placed.group' + this.getGroup(drag)).not('.beingdragged').each(function(i, placedNode) {
419 var placedDrag = $(placedNode);
420 if (!thisQ.isPointInDrop(pageX, pageY, placedDrag) || thisQ.isDragSameAsDrop(drag, placedDrag)) {
421 // Not this placed drag.
425 // Now put this drag into the drop.
426 placedDrag.removeClass('valid-drag-over-drop');
427 var currentPlace = thisQ.getClassnameNumericSuffix(placedDrag, 'inplace');
428 var drop = thisQ.getDrop(drag, currentPlace);
429 thisQ.sendDragToDrop(drag, drop);
431 return false; // Stop the each() here.
436 this.sendDragHome(drag);
441 * Animate a drag item into a given place (or back home).
443 * @param {jQuery|null} drag the item to place. If null, clear the place.
444 * @param {jQuery} drop the place to put it.
446 DragDropOntoImageQuestion.prototype.sendDragToDrop = function(drag, drop) {
447 // Is there already a drag in this drop? if so, evict it.
448 var oldDrag = this.getCurrentDragInPlace(this.getPlace(drop));
449 if (oldDrag.length !== 0) {
450 oldDrag.addClass('beingdragged');
451 oldDrag.offset(oldDrag.offset());
452 var currentPlace = this.getClassnameNumericSuffix(oldDrag, 'inplace');
453 var hiddenDrop = this.getDrop(oldDrag, currentPlace);
454 hiddenDrop.addClass('active');
455 this.sendDragHome(oldDrag);
458 if (drag.length === 0) {
459 this.setInputValue(this.getPlace(drop), 0);
460 if (drop.data('isfocus')) {
464 this.setInputValue(this.getPlace(drop), this.getChoice(drag));
465 drag.removeClass('unplaced')
466 .addClass('placed inplace' + this.getPlace(drop));
467 drag.attr('tabindex', 0);
468 this.animateTo(drag, drop);
473 * Animate a drag back to its home.
475 * @param {jQuery} drag the item being moved.
477 DragDropOntoImageQuestion.prototype.sendDragHome = function(drag) {
478 var currentPlace = this.getClassnameNumericSuffix(drag, 'inplace');
479 if (currentPlace !== null) {
480 drag.removeClass('inplace' + currentPlace);
482 drag.data('unplaced', true);
484 this.animateTo(drag, this.getDragHome(this.getGroup(drag), this.getChoice(drag)));
488 * Handles keyboard events on drops.
490 * Drops are focusable. Once focused, right/down/space switches to the next choice, and
491 * left/up switches to the previous. Escape clear.
493 * @param {KeyboardEvent} e
495 DragDropOntoImageQuestion.prototype.handleKeyPress = function(e) {
496 var drop = $(e.target).closest('.dropzone');
497 if (drop.length === 0) {
498 var placedDrag = $(e.target);
499 var currentPlace = this.getClassnameNumericSuffix(placedDrag, 'inplace');
500 if (currentPlace !== null) {
501 drop = this.getDrop(placedDrag, currentPlace);
504 var currentDrag = this.getCurrentDragInPlace(this.getPlace(drop)),
509 case keys.arrowRight:
511 nextDrag = this.getNextDrag(this.getGroup(drop), currentDrag);
516 nextDrag = this.getPreviousDrag(this.getGroup(drop), currentDrag);
520 questionManager.isKeyboardNavigation = false;
524 questionManager.isKeyboardNavigation = false;
525 return; // To avoid the preventDefault below.
528 if (nextDrag.length) {
529 nextDrag.data('isfocus', true);
530 nextDrag.addClass('beingdragged');
531 var hiddenDrag = this.getDragClone(nextDrag);
532 if (hiddenDrag.length) {
533 if (nextDrag.hasClass('infinite')) {
534 var noOfDrags = this.noOfDropsInGroup(this.getGroup(nextDrag));
535 var cloneDrags = this.getInfiniteDragClones(nextDrag, false);
536 if (cloneDrags.length < noOfDrags) {
537 var cloneDrag = nextDrag.clone();
538 cloneDrag.removeClass('beingdragged');
539 cloneDrag.removeAttr('tabindex');
540 hiddenDrag.after(cloneDrag);
541 questionManager.addEventHandlersToDrag(cloneDrag);
542 nextDrag.offset(cloneDrag.offset());
544 hiddenDrag.addClass('active');
545 nextDrag.offset(hiddenDrag.offset());
548 hiddenDrag.addClass('active');
549 nextDrag.offset(hiddenDrag.offset());
553 drop.data('isfocus', true);
557 this.sendDragToDrop(nextDrag, drop);
561 * Choose the next drag in a group.
563 * @param {int} group which group.
564 * @param {jQuery} drag current choice (empty jQuery if there isn't one).
565 * @return {jQuery} the next drag in that group, or null if there wasn't one.
567 DragDropOntoImageQuestion.prototype.getNextDrag = function(group, drag) {
569 numChoices = this.noOfChoicesInGroup(group);
571 if (drag.length === 0) {
572 choice = 1; // Was empty, so we want to select the first choice.
574 choice = this.getChoice(drag) + 1;
577 var next = this.getUnplacedChoice(group, choice);
578 while (next.length === 0 && choice < numChoices) {
580 next = this.getUnplacedChoice(group, choice);
587 * Choose the previous drag in a group.
589 * @param {int} group which group.
590 * @param {jQuery} drag current choice (empty jQuery if there isn't one).
591 * @return {jQuery} the next drag in that group, or null if there wasn't one.
593 DragDropOntoImageQuestion.prototype.getPreviousDrag = function(group, drag) {
596 if (drag.length === 0) {
597 choice = this.noOfChoicesInGroup(group);
599 choice = this.getChoice(drag) - 1;
602 var previous = this.getUnplacedChoice(group, choice);
603 while (previous.length === 0 && choice > 1) {
605 previous = this.getUnplacedChoice(group, choice);
608 // Does this choice exist?
613 * Animate an object to the given destination.
615 * @param {jQuery} drag the element to be animated.
616 * @param {jQuery} target element marking the place to move it to.
618 DragDropOntoImageQuestion.prototype.animateTo = function(drag, target) {
619 var currentPos = drag.offset(),
620 targetPos = target.offset(),
623 M.util.js_pending('qtype_ddimageortext-animate-' + thisQ.containerId);
624 // Animate works in terms of CSS position, whereas locating an object
625 // on the page works best with jQuery offset() function. So, to get
626 // the right target position, we work out the required change in
627 // offset() and then add that to the current CSS position.
630 left: parseInt(drag.css('left')) + targetPos.left - currentPos.left,
631 top: parseInt(drag.css('top')) + targetPos.top - currentPos.top
636 $('body').trigger('qtype_ddimageortext-dragmoved', [drag, target, thisQ]);
637 M.util.js_complete('qtype_ddimageortext-animate-' + thisQ.containerId);
644 * Detect if a point is inside a given DOM node.
646 * @param {Number} pageX the x position.
647 * @param {Number} pageY the y position.
648 * @param {jQuery} drop the node to check (typically a drop).
649 * @return {boolean} whether the point is inside the node.
651 DragDropOntoImageQuestion.prototype.isPointInDrop = function(pageX, pageY, drop) {
652 var position = drop.offset();
653 if (drop.hasClass('draghome')) {
654 return pageX >= position.left && pageX < position.left + drop.outerWidth()
655 && pageY >= position.top && pageY < position.top + drop.outerHeight();
657 return pageX >= position.left && pageX < position.left + drop.width()
658 && pageY >= position.top && pageY < position.top + drop.height();
662 * Set the value of the hidden input for a place, to record what is currently there.
664 * @param {int} place which place to set the input value for.
665 * @param {int} choice the value to set.
667 DragDropOntoImageQuestion.prototype.setInputValue = function(place, choice) {
668 this.getRoot().find('input.placeinput.place' + place).val(choice);
672 * Get the outer div for this question.
674 * @returns {jQuery} containing that div.
676 DragDropOntoImageQuestion.prototype.getRoot = function() {
677 return $(document.getElementById(this.containerId));
681 * Get the img that is the background image.
682 * @returns {jQuery} containing that img.
684 DragDropOntoImageQuestion.prototype.bgImage = function() {
685 return this.getRoot().find('img.dropbackground');
689 * Get drag home for a given choice.
691 * @param {int} group the group.
692 * @param {int} choice the choice number.
693 * @returns {jQuery} containing that div.
695 DragDropOntoImageQuestion.prototype.getDragHome = function(group, choice) {
696 if (!this.getRoot().find('.draghome.dragplaceholder.group' + group + '.choice' + choice).is(':visible')) {
697 return this.getRoot().find('.dragitemgroup' + group +
698 ' .draghome.infinite' +
702 return this.getRoot().find('.draghome.dragplaceholder.group' + group + '.choice' + choice);
706 * Get an unplaced choice for a particular group.
708 * @param {int} group the group.
709 * @param {int} choice the choice number.
710 * @returns {jQuery} jQuery wrapping the unplaced choice. If there isn't one, the jQuery will be empty.
712 DragDropOntoImageQuestion.prototype.getUnplacedChoice = function(group, choice) {
713 return this.getRoot().find('.ddarea .draghome.group' + group + '.choice' + choice + '.unplaced').slice(0, 1);
717 * Get the drag that is currently in a given place.
719 * @param {int} place the place number.
720 * @return {jQuery} the current drag (or an empty jQuery if none).
722 DragDropOntoImageQuestion.prototype.getCurrentDragInPlace = function(place) {
723 return this.getRoot().find('.ddarea .draghome.inplace' + place);
727 * Return the number of blanks in a given group.
729 * @param {int} group the group number.
730 * @returns {int} the number of drops.
732 DragDropOntoImageQuestion.prototype.noOfDropsInGroup = function(group) {
733 return this.getRoot().find('.dropzone.group' + group).length;
737 * Return the number of choices in a given group.
739 * @param {int} group the group number.
740 * @returns {int} the number of choices.
742 DragDropOntoImageQuestion.prototype.noOfChoicesInGroup = function(group) {
743 return this.getRoot().find('.dragitemgroup' + group + ' .draghome').length;
747 * Return the number at the end of the CSS class name with the given prefix.
749 * @param {jQuery} node
750 * @param {String} prefix name prefix
751 * @returns {Number|null} the suffix if found, else null.
753 DragDropOntoImageQuestion.prototype.getClassnameNumericSuffix = function(node, prefix) {
754 var classes = node.attr('class');
755 if (classes !== '') {
756 var classesArr = classes.split(' ');
757 for (var index = 0; index < classesArr.length; index++) {
758 var patt1 = new RegExp('^' + prefix + '([0-9])+$');
759 if (patt1.test(classesArr[index])) {
760 var patt2 = new RegExp('([0-9])+$');
761 var match = patt2.exec(classesArr[index]);
762 return Number(match[0]);
770 * Get the choice number of a drag.
772 * @param {jQuery} drag the drag.
773 * @returns {Number} the choice number.
775 DragDropOntoImageQuestion.prototype.getChoice = function(drag) {
776 return this.getClassnameNumericSuffix(drag, 'choice');
780 * Given a DOM node that is significant to this question
781 * (drag, drop, ...) get the group it belongs to.
783 * @param {jQuery} node a DOM node.
784 * @returns {Number} the group it belongs to.
786 DragDropOntoImageQuestion.prototype.getGroup = function(node) {
787 return this.getClassnameNumericSuffix(node, 'group');
791 * Get the place number of a drop, or its corresponding hidden input.
793 * @param {jQuery} node the DOM node.
794 * @returns {Number} the place number.
796 DragDropOntoImageQuestion.prototype.getPlace = function(node) {
797 return this.getClassnameNumericSuffix(node, 'place');
801 * Get drag clone for a given drag.
803 * @param {jQuery} drag the drag.
804 * @returns {jQuery} the drag's clone.
806 DragDropOntoImageQuestion.prototype.getDragClone = function(drag) {
807 return this.getRoot().find('.dragitemgroup' +
808 this.getGroup(drag) +
810 '.choice' + this.getChoice(drag) +
811 '.group' + this.getGroup(drag) +
816 * Get infinite drag clones for given drag.
818 * @param {jQuery} drag the drag.
819 * @param {Boolean} inHome in the home area or not.
820 * @returns {jQuery} the drag's clones.
822 DragDropOntoImageQuestion.prototype.getInfiniteDragClones = function(drag, inHome) {
824 return this.getRoot().find('.dragitemgroup' +
825 this.getGroup(drag) +
827 '.choice' + this.getChoice(drag) +
828 '.group' + this.getGroup(drag) +
829 '.infinite').not('.dragplaceholder');
831 return this.getRoot().find('.draghome' +
832 '.choice' + this.getChoice(drag) +
833 '.group' + this.getGroup(drag) +
834 '.infinite').not('.dragplaceholder');
838 * Get drop for a given drag and place.
840 * @param {jQuery} drag the drag.
841 * @param {Integer} currentPlace the current place of drag.
842 * @returns {jQuery} the drop's clone.
844 DragDropOntoImageQuestion.prototype.getDrop = function(drag, currentPlace) {
845 return this.getRoot().find('.dropzone.group' + this.getGroup(drag) + '.place' + currentPlace);
849 * Handle when the window is resized.
851 DragDropOntoImageQuestion.prototype.handleResize = function() {
853 bgRatio = this.bgRatio();
854 if (this.isPrinting) {
858 this.getRoot().find('.ddarea .dropzone').each(function(i, dropNode) {
860 .css('left', parseInt($(dropNode).data('originX')) * parseFloat(bgRatio))
861 .css('top', parseInt($(dropNode).data('originY')) * parseFloat(bgRatio));
862 thisQ.handleElementScale(dropNode, 'left top');
865 this.getRoot().find('div.droparea .draghome').not('.beingdragged').each(function(key, drag) {
867 .css('left', parseFloat($(drag).data('originX')) * parseFloat(bgRatio))
868 .css('top', parseFloat($(drag).data('originY')) * parseFloat(bgRatio));
869 thisQ.handleElementScale(drag, 'left top');
874 * Return the background ratio.
876 * @returns {number} Background ratio.
878 DragDropOntoImageQuestion.prototype.bgRatio = function() {
879 var bgImg = this.bgImage();
880 var bgImgNaturalWidth = bgImg.get(0).naturalWidth;
881 var bgImgClientWidth = bgImg.width();
883 return bgImgClientWidth / bgImgNaturalWidth;
887 * Scale the drag if needed.
889 * @param {jQuery} element the item to place.
890 * @param {String} type scaling type
892 DragDropOntoImageQuestion.prototype.handleElementScale = function(element, type) {
893 var bgRatio = parseFloat(this.bgRatio());
894 if (this.isPrinting) {
898 '-webkit-transform': 'scale(' + bgRatio + ')',
899 '-moz-transform': 'scale(' + bgRatio + ')',
900 '-ms-transform': 'scale(' + bgRatio + ')',
901 '-o-transform': 'scale(' + bgRatio + ')',
902 'transform': 'scale(' + bgRatio + ')',
903 'transform-origin': type
908 * Calculate z-index value.
910 * @returns {number} z-index value
912 DragDropOntoImageQuestion.prototype.calculateZIndex = function() {
914 this.getRoot().find('.ddarea .dropzone, div.droparea .draghome').each(function(i, dropNode) {
915 dropNode = $(dropNode);
916 // Note that webkit browsers won't return the z-index value from the CSS stylesheet
917 // if the element doesn't have a position specified. Instead it'll return "auto".
918 var itemZIndex = dropNode.css('z-index') ? parseInt(dropNode.css('z-index')) : 0;
920 if (itemZIndex > zIndex) {
929 * Check that the drag is drop to it's clone.
931 * @param {jQuery} drag The drag.
932 * @param {jQuery} drop The drop.
935 DragDropOntoImageQuestion.prototype.isDragSameAsDrop = function(drag, drop) {
936 return this.getChoice(drag) === this.getChoice(drop) && this.getGroup(drag) === this.getGroup(drop);
940 * Singleton object that handles all the DragDropOntoImageQuestions
941 * on the page, and deals with event dispatching.
944 var questionManager = {
947 * {boolean} ensures that the event handlers are only initialised once per page.
949 eventHandlersInitialised: false,
952 * {boolean} is printing or not.
957 * {boolean} is keyboard navigation or not.
959 isKeyboardNavigation: false,
962 * {Object} all the questions on this page, indexed by containerId (id on the .que div).
964 questions: {}, // An object containing all the information about each question on the page.
967 * Initialise one question.
969 * @param {String} containerId the id of the div.que that contains this question.
970 * @param {boolean} readOnly whether the question is read-only.
971 * @param {Array} places data.
973 init: function(containerId, readOnly, places) {
974 questionManager.questions[containerId] =
975 new DragDropOntoImageQuestion(containerId, readOnly, places);
976 if (!questionManager.eventHandlersInitialised) {
977 questionManager.setupEventHandlers();
978 questionManager.eventHandlersInitialised = true;
983 * Set up the event handlers that make this question type work. (Done once per page.)
985 setupEventHandlers: function() {
986 // We do not use the body event here to prevent the other event on Mobile device, such as scroll event.
987 questionManager.addEventHandlersToDrag($('.que.ddimageortext:not(.qtype_ddimageortext-readonly) .draghome'));
990 '.que.ddimageortext:not(.qtype_ddimageortext-readonly) .dropzones .dropzone',
991 questionManager.handleKeyPress)
993 '.que.ddimageortext:not(.qtype_ddimageortext-readonly) .draghome.placed:not(.beingdragged)',
994 questionManager.handleKeyPress)
995 .on('qtype_ddimageortext-dragmoved', questionManager.handleDragMoved);
996 $(window).on('resize', function() {
997 questionManager.handleWindowResize(false);
999 window.addEventListener('beforeprint', function() {
1000 questionManager.isPrinting = true;
1001 questionManager.handleWindowResize(questionManager.isPrinting);
1003 window.addEventListener('afterprint', function() {
1004 questionManager.isPrinting = false;
1005 questionManager.handleWindowResize(questionManager.isPrinting);
1007 setTimeout(function() {
1008 questionManager.fixLayoutIfThingsMoved();
1013 * Binding the drag/touch event again for newly created element.
1015 * @param {jQuery} element Element to bind the event
1017 addEventHandlersToDrag: function(element) {
1018 // Unbind all the mousedown and touchstart events to prevent double binding.
1019 element.unbind('mousedown touchstart');
1020 element.on('mousedown touchstart', questionManager.handleDragStart);
1024 * Handle mouse down / touch start events on drags.
1025 * @param {Event} e the DOM event.
1027 handleDragStart: function(e) {
1029 var question = questionManager.getQuestionForEvent(e);
1031 question.handleDragStart(e);
1036 * Handle key down / press events on drags.
1037 * @param {KeyboardEvent} e
1039 handleKeyPress: function(e) {
1040 if (questionManager.isKeyboardNavigation) {
1043 questionManager.isKeyboardNavigation = true;
1044 var question = questionManager.getQuestionForEvent(e);
1046 question.handleKeyPress(e);
1051 * Handle when the window is resized.
1052 * @param {boolean} isPrinting
1054 handleWindowResize: function(isPrinting) {
1055 for (var containerId in questionManager.questions) {
1056 if (questionManager.questions.hasOwnProperty(containerId)) {
1057 questionManager.questions[containerId].isPrinting = isPrinting;
1058 questionManager.questions[containerId].handleResize();
1064 * Sometimes, despite our best efforts, things change in a way that cannot
1065 * be specifically caught (e.g. dock expanding or collapsing in Boost).
1066 * Therefore, we need to periodically check everything is in the right position.
1068 fixLayoutIfThingsMoved: function() {
1069 this.handleWindowResize(questionManager.isPrinting);
1070 // We use setTimeout after finishing work, rather than setInterval,
1071 // in case positioning things is slow. We want 100 ms gap
1072 // between executions, not what setInterval does.
1073 setTimeout(function() {
1074 questionManager.fixLayoutIfThingsMoved(questionManager.isPrinting);
1079 * Handle when drag moved.
1081 * @param {Event} e the event.
1082 * @param {jQuery} drag the drag
1083 * @param {jQuery} target the target
1084 * @param {DragDropOntoImageQuestion} thisQ the question.
1086 handleDragMoved: function(e, drag, target, thisQ) {
1087 drag.removeClass('beingdragged').css('z-index', '');
1088 drag.css('top', target.position().top).css('left', target.position().left);
1090 target.removeClass('active');
1091 if (typeof drag.data('unplaced') !== 'undefined' && drag.data('unplaced') === true) {
1092 drag.removeClass('placed').addClass('unplaced');
1093 drag.removeAttr('tabindex');
1094 drag.removeData('unplaced');
1097 .css('transform', '');
1098 if (drag.hasClass('infinite') && thisQ.getInfiniteDragClones(drag, true).length > 1) {
1099 thisQ.getInfiniteDragClones(drag, true).first().remove();
1102 drag.data('originX', target.data('originX')).data('originY', target.data('originY'));
1103 thisQ.handleElementScale(drag, 'left top');
1105 if (typeof drag.data('isfocus') !== 'undefined' && drag.data('isfocus') === true) {
1107 drag.removeData('isfocus');
1109 if (typeof target.data('isfocus') !== 'undefined' && target.data('isfocus') === true) {
1110 target.removeData('isfocus');
1112 if (questionManager.isKeyboardNavigation) {
1113 questionManager.isKeyboardNavigation = false;
1118 * Given an event, work out which question it effects.
1119 * @param {Event} e the event.
1120 * @returns {DragDropOntoImageQuestion|undefined} The question, or undefined.
1122 getQuestionForEvent: function(e) {
1123 var containerId = $(e.currentTarget).closest('.que.ddimageortext').attr('id');
1124 return questionManager.questions[containerId];
1129 * @alias module:qtype_ddimageortext/question
1133 * Initialise one drag-drop onto image question.
1135 * @param {String} containerId id of the outer div for this question.
1136 * @param {boolean} readOnly whether the question is being displayed read-only.
1137 * @param {Array} Information about the drop places.
1139 init: questionManager.init