MDL-69104 Questions: Drag and drop question family don't work with iOS
[moodle.git] / question / type / ddimageortext / amd / src / question.js
CommitLineData
ebf91776
TH
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 allow dragging options to slots (using mouse down or touch) or tab through slots using keyboard.
18 *
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
23 */
24define(['jquery', 'core/dragdrop', 'core/key_codes'], function($, dragDrop, keys) {
25
26 "use strict";
27
28 /**
29 * Initialise one drag-drop onto image question.
30 *
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.
34 * @constructor
35 */
36 function DragDropOntoImageQuestion(containerId, readOnly, places) {
37 this.containerId = containerId;
38 M.util.js_pending('qtype_ddimageortext-init-' + this.containerId);
39 this.places = places;
40 this.allImagesLoaded = false;
41 this.imageLoadingTimeoutId = null;
a05ef130 42 this.isPrinting = false;
ebf91776
TH
43 if (readOnly) {
44 this.getRoot().addClass('qtype_ddimageortext-readonly');
45 }
46
47 var thisQ = this;
48 this.getNotYetLoadedImages().one('load', function() {
49 thisQ.waitForAllImagesToBeLoaded();
50 });
51 this.waitForAllImagesToBeLoaded();
52 }
53
54 /**
55 * Waits until all images are loaded before calling setupQuestion().
56 *
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.
59 */
60 DragDropOntoImageQuestion.prototype.waitForAllImagesToBeLoaded = function() {
61 var thisQ = this;
62
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) {
66 return;
67 }
68
69 // Clear any current timeout, if set.
70 if (this.imageLoadingTimeoutId !== null) {
71 clearTimeout(this.imageLoadingTimeoutId);
72 }
73
74 // If we have not yet loaded all images, set a timeout to
75 // call ourselves again, since apparently images on-load
76 // events are flakey.
77 if (this.getNotYetLoadedImages().length > 0) {
78 this.imageLoadingTimeoutId = setTimeout(function() {
79 thisQ.waitForAllImagesToBeLoaded();
80 }, 100);
81 return;
82 }
83
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();
87 };
88
89 /**
90 * Get any of the images in the drag-drop area that are not yet fully loaded.
91 *
92 * @returns {jQuery} those images.
93 */
94 DragDropOntoImageQuestion.prototype.getNotYetLoadedImages = function() {
95 var thisQ = this;
96 return this.getRoot().find('.ddarea img').not(function(i, imgNode) {
97 return thisQ.imageIsLoaded(imgNode);
98 });
99 };
100
101 /**
102 * Check if an image has loaded without errors.
103 *
104 * @param {HTMLImageElement} imgElement an image.
105 * @returns {boolean} true if this image has loaded without errors.
106 */
107 DragDropOntoImageQuestion.prototype.imageIsLoaded = function(imgElement) {
108 return imgElement.complete && imgElement.naturalHeight !== 0;
109 };
110
111 /**
112 * Set up the question, once all images have been loaded.
113 */
114 DragDropOntoImageQuestion.prototype.setupQuestion = function() {
115 this.resizeAllDragsAndDrops();
116 this.cloneDrags();
117 this.positionDragsAndDrops();
118 M.util.js_complete('qtype_ddimageortext-init-' + this.containerId);
ebf91776
TH
119 };
120
121 /**
122 * In each group, resize all the items to be the same size.
123 */
124 DragDropOntoImageQuestion.prototype.resizeAllDragsAndDrops = function() {
125 var thisQ = this;
d434dd7a
TH
126 this.getRoot().find('.draghomes > div').each(function(i, node) {
127 thisQ.resizeAllDragsAndDropsInGroup(
128 thisQ.getClassnameNumericSuffix($(node), 'dragitemgroup'));
ebf91776
TH
129 });
130 };
131
132 /**
133 * In a given group, set all the drags and drops to be the same size.
134 *
135 * @param {int} group the group number.
136 */
137 DragDropOntoImageQuestion.prototype.resizeAllDragsAndDropsInGroup = function(group) {
138 var root = this.getRoot(),
139 dragHomes = root.find('.dragitemgroup' + group + ' .draghome'),
140 maxWidth = 0,
141 maxHeight = 0;
142
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));
147 });
148
149 // The size we will want to set is a bit bigger than this.
150 maxWidth += 10;
151 maxHeight += 10;
152
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.
158 $(drag).css({
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'
163 });
164 });
165
166 // Create the drops and make them the right size.
167 for (var i in this.places) {
168 if (!this.places.hasOwnProperty((i))) {
169 continue;
170 }
171 var place = this.places[i],
172 label = place.text;
173 if (parseInt(place.group) !== group) {
174 continue;
175 }
176 if (label === '') {
177 label = M.util.get_string('blank', 'qtype_ddimageortext');
178 }
a05ef130 179 root.find('.dropzones').append('<div class="dropzone active group' + place.group +
ebf91776
TH
180 ' place' + i + '" tabindex="0">' +
181 '<span class="accesshide">' + label + '</span>&nbsp;</div>');
182 root.find('.dropzone.place' + i).width(maxWidth - 2).height(maxHeight - 2);
183 }
184 };
185
186 /**
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
189 * actual drag items.
190 */
191 DragDropOntoImageQuestion.prototype.cloneDrags = function() {
192 var thisQ = this;
a05ef130
HN
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);
ebf91776
TH
201 });
202 };
203
204 /**
205 * Clone drag item for one choice.
206 *
207 * @param {jQuery} dragHome the drag home to clone.
208 */
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);
214 }
215 } else {
216 this.cloneDrag(dragHome);
217 }
218 };
219
220 /**
221 * Clone drag item.
222 *
223 * @param {jQuery} dragHome
224 */
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);
231 };
232
233 /**
234 * Update the position of drags.
235 */
236 DragDropOntoImageQuestion.prototype.positionDragsAndDrops = function() {
237 var thisQ = this,
238 root = this.getRoot(),
a05ef130 239 bgRatio = this.bgRatio();
ebf91776
TH
240
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.
a05ef130
HN
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');
ebf91776
TH
251 });
252
253 // First move all items back home.
a05ef130 254 root.find('.draghome').not('.dragplaceholder').each(function(i, dragNode) {
ebf91776
TH
255 var drag = $(dragNode),
256 currentPlace = thisQ.getClassnameNumericSuffix(drag, 'inplace');
257 drag.addClass('unplaced')
a05ef130
HN
258 .removeClass('placed');
259 drag.removeAttr('tabindex');
ebf91776
TH
260 if (currentPlace !== null) {
261 drag.removeClass('inplace' + currentPlace);
262 }
263 });
264
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();
a05ef130 269 if (choice.length === 0 || (choice.length > 0 && choice === '0')) {
ebf91776
TH
270 // No item in this place.
271 return;
272 }
273
274 var place = thisQ.getPlace(input);
a05ef130
HN
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);
288 } else {
289 hiddenDrag.addClass('active');
290 }
291 } else {
292 hiddenDrag.addClass('active');
293 }
294 }
e5153d93 295
a05ef130
HN
296 // Send the drag to drop.
297 var drop = root.find('.dropzone.place' + place);
298 thisQ.sendDragToDrop(unplacedDrag, drop);
299 });
ebf91776
TH
300 };
301
302 /**
303 * Handles the start of dragging an item.
304 *
305 * @param {Event} e the touch start or mouse down event.
306 */
307 DragDropOntoImageQuestion.prototype.handleDragStart = function(e) {
308 var thisQ = this,
a05ef130
HN
309 drag = $(e.target).closest('.draghome'),
310 currentIndex = this.calculateZIndex(),
311 newIndex = currentIndex + 2;
ebf91776
TH
312
313 var info = dragDrop.prepare(e);
314 if (!info.start) {
315 return;
316 }
317
a05ef130 318 drag.addClass('beingdragged').css('transform', '').css('z-index', newIndex);
ebf91776
TH
319 var currentPlace = this.getClassnameNumericSuffix(drag, 'inplace');
320 if (currentPlace !== null) {
321 this.setInputValue(currentPlace, 0);
322 drag.removeClass('inplace' + currentPlace);
a05ef130
HN
323 var hiddenDrop = thisQ.getDrop(drag, currentPlace);
324 if (hiddenDrop.length) {
325 hiddenDrop.addClass('active');
326 drag.offset(hiddenDrop.offset());
327 }
328 } else {
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);
5fa8f1c8 339 questionManager.addEventHandlersToDrag(cloneDrag);
a05ef130
HN
340 drag.offset(cloneDrag.offset());
341 } else {
342 hiddenDrag.addClass('active');
343 drag.offset(hiddenDrag.offset());
344 }
345 } else {
346 hiddenDrag.addClass('active');
347 drag.offset(hiddenDrag.offset());
348 }
349 }
ebf91776
TH
350 }
351
ebf91776
TH
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);
356 });
357 };
358
359 /**
360 * Called whenever the currently dragged items moves.
361 *
362 * @param {Number} pageX the x position.
363 * @param {Number} pageY the y position.
364 * @param {jQuery} drag the item being moved.
365 */
366 DragDropOntoImageQuestion.prototype.dragMove = function(pageX, pageY, drag) {
367 var thisQ = this;
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');
372 } else {
373 drop.removeClass('valid-drag-over-drop');
374 }
375 });
a05ef130
HN
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)) {
379 drop.addClass('valid-drag-over-drop');
380 } else {
381 drop.removeClass('valid-drag-over-drop');
382 }
383 });
ebf91776
TH
384 };
385
386 /**
387 * Called when user drops a drag item.
388 *
389 * @param {Number} pageX the x position.
390 * @param {Number} pageY the y position.
391 * @param {jQuery} drag the item being moved.
392 */
393 DragDropOntoImageQuestion.prototype.dragEnd = function(pageX, pageY, drag) {
394 var thisQ = this,
395 root = this.getRoot(),
396 placed = false;
397 root.find('.dropzone.group' + this.getGroup(drag)).each(function(i, dropNode) {
398 var drop = $(dropNode);
399 if (!thisQ.isPointInDrop(pageX, pageY, drop)) {
400 // Not this drop.
401 return true;
402 }
403
404 // Now put this drag into the drop.
405 drop.removeClass('valid-drag-over-drop');
406 thisQ.sendDragToDrop(drag, drop);
407 placed = true;
408 return false; // Stop the each() here.
409 });
410
a05ef130
HN
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)) {
414 // Not this placed drag.
415 return true;
416 }
417
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);
423 placed = true;
424 return false; // Stop the each() here.
425 });
426
ebf91776
TH
427 if (!placed) {
428 this.sendDragHome(drag);
429 }
430 };
431
432 /**
433 * Animate a drag item into a given place (or back home).
434 *
435 * @param {jQuery|null} drag the item to place. If null, clear the place.
436 * @param {jQuery} drop the place to put it.
437 */
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) {
a05ef130
HN
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');
ebf91776
TH
447 this.sendDragHome(oldDrag);
448 }
449
450 if (drag.length === 0) {
451 this.setInputValue(this.getPlace(drop), 0);
a05ef130
HN
452 if (drop.data('isfocus')) {
453 drop.focus();
454 }
ebf91776
TH
455 } else {
456 this.setInputValue(this.getPlace(drop), this.getChoice(drag));
457 drag.removeClass('unplaced')
458 .addClass('placed inplace' + this.getPlace(drop));
a05ef130 459 drag.attr('tabindex', 0);
ebf91776
TH
460 this.animateTo(drag, drop);
461 }
462 };
463
464 /**
465 * Animate a drag back to its home.
466 *
467 * @param {jQuery} drag the item being moved.
468 */
469 DragDropOntoImageQuestion.prototype.sendDragHome = function(drag) {
ebf91776
TH
470 var currentPlace = this.getClassnameNumericSuffix(drag, 'inplace');
471 if (currentPlace !== null) {
472 drag.removeClass('inplace' + currentPlace);
473 }
a05ef130 474 drag.data('unplaced', true);
ebf91776
TH
475
476 this.animateTo(drag, this.getDragHome(this.getGroup(drag), this.getChoice(drag)));
477 };
478
479 /**
480 * Handles keyboard events on drops.
481 *
482 * Drops are focusable. Once focused, right/down/space switches to the next choice, and
483 * left/up switches to the previous. Escape clear.
484 *
485 * @param {KeyboardEvent} e
486 */
487 DragDropOntoImageQuestion.prototype.handleKeyPress = function(e) {
a05ef130
HN
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);
494 }
495 }
496 var currentDrag = this.getCurrentDragInPlace(this.getPlace(drop)),
ebf91776
TH
497 nextDrag = $();
498
499 switch (e.keyCode) {
500 case keys.space:
501 case keys.arrowRight:
502 case keys.arrowDown:
503 nextDrag = this.getNextDrag(this.getGroup(drop), currentDrag);
504 break;
505
506 case keys.arrowLeft:
507 case keys.arrowUp:
508 nextDrag = this.getPreviousDrag(this.getGroup(drop), currentDrag);
509 break;
510
511 case keys.escape:
81d7fd7a 512 questionManager.isKeyboardNavigation = false;
ebf91776
TH
513 break;
514
515 default:
a05ef130 516 questionManager.isKeyboardNavigation = false;
ebf91776
TH
517 return; // To avoid the preventDefault below.
518 }
519
a05ef130
HN
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);
5fa8f1c8 533 questionManager.addEventHandlersToDrag(cloneDrag);
a05ef130
HN
534 nextDrag.offset(cloneDrag.offset());
535 } else {
536 hiddenDrag.addClass('active');
537 nextDrag.offset(hiddenDrag.offset());
538 }
539 } else {
540 hiddenDrag.addClass('active');
541 nextDrag.offset(hiddenDrag.offset());
542 }
543 }
544 } else {
545 drop.data('isfocus', true);
546 }
547
ebf91776
TH
548 e.preventDefault();
549 this.sendDragToDrop(nextDrag, drop);
550 };
551
552 /**
553 * Choose the next drag in a group.
554 *
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.
558 */
559 DragDropOntoImageQuestion.prototype.getNextDrag = function(group, drag) {
560 var choice,
561 numChoices = this.noOfChoicesInGroup(group);
562
563 if (drag.length === 0) {
564 choice = 1; // Was empty, so we want to select the first choice.
565 } else {
566 choice = this.getChoice(drag) + 1;
567 }
568
569 var next = this.getUnplacedChoice(group, choice);
570 while (next.length === 0 && choice < numChoices) {
571 choice++;
572 next = this.getUnplacedChoice(group, choice);
573 }
574
575 return next;
576 };
577
578 /**
579 * Choose the previous drag in a group.
580 *
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.
584 */
585 DragDropOntoImageQuestion.prototype.getPreviousDrag = function(group, drag) {
586 var choice;
587
588 if (drag.length === 0) {
589 choice = this.noOfChoicesInGroup(group);
590 } else {
591 choice = this.getChoice(drag) - 1;
592 }
593
594 var previous = this.getUnplacedChoice(group, choice);
595 while (previous.length === 0 && choice > 1) {
596 choice--;
597 previous = this.getUnplacedChoice(group, choice);
598 }
599
600 // Does this choice exist?
601 return previous;
602 };
603
604 /**
605 * Animate an object to the given destination.
606 *
607 * @param {jQuery} drag the element to be animated.
608 * @param {jQuery} target element marking the place to move it to.
609 */
610 DragDropOntoImageQuestion.prototype.animateTo = function(drag, target) {
611 var currentPos = drag.offset(),
a05ef130
HN
612 targetPos = target.offset(),
613 thisQ = this;
ebf91776 614
a05ef130 615 M.util.js_pending('qtype_ddimageortext-animate-' + thisQ.containerId);
ebf91776
TH
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.
620 drag.animate(
621 {
622 left: parseInt(drag.css('left')) + targetPos.left - currentPos.left,
623 top: parseInt(drag.css('top')) + targetPos.top - currentPos.top
624 },
625 {
626 duration: 'fast',
627 done: function() {
5fa8f1c8 628 $('body').trigger('qtype_ddimageortext-dragmoved', [drag, target, thisQ]);
a05ef130 629 M.util.js_complete('qtype_ddimageortext-animate-' + thisQ.containerId);
ebf91776
TH
630 }
631 }
632 );
633 };
634
635 /**
636 * Detect if a point is inside a given DOM node.
637 *
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.
642 */
643 DragDropOntoImageQuestion.prototype.isPointInDrop = function(pageX, pageY, drop) {
644 var position = drop.offset();
a05ef130
HN
645 if (drop.hasClass('draghome')) {
646 return pageX >= position.left && pageX < position.left + drop.outerWidth()
647 && pageY >= position.top && pageY < position.top + drop.outerHeight();
648 }
ebf91776
TH
649 return pageX >= position.left && pageX < position.left + drop.width()
650 && pageY >= position.top && pageY < position.top + drop.height();
651 };
652
653 /**
654 * Set the value of the hidden input for a place, to record what is currently there.
655 *
656 * @param {int} place which place to set the input value for.
657 * @param {int} choice the value to set.
658 */
659 DragDropOntoImageQuestion.prototype.setInputValue = function(place, choice) {
660 this.getRoot().find('input.placeinput.place' + place).val(choice);
661 };
662
663 /**
664 * Get the outer div for this question.
665 *
666 * @returns {jQuery} containing that div.
667 */
668 DragDropOntoImageQuestion.prototype.getRoot = function() {
669 return $(document.getElementById(this.containerId));
670 };
671
672 /**
673 * Get the img that is the background image.
674 * @returns {jQuery} containing that img.
675 */
676 DragDropOntoImageQuestion.prototype.bgImage = function() {
677 return this.getRoot().find('img.dropbackground');
678 };
679
680 /**
681 * Get drag home for a given choice.
682 *
683 * @param {int} group the group.
684 * @param {int} choice the choice number.
685 * @returns {jQuery} containing that div.
686 */
687 DragDropOntoImageQuestion.prototype.getDragHome = function(group, choice) {
a05ef130
HN
688 if (!this.getRoot().find('.draghome.dragplaceholder.group' + group + '.choice' + choice).is(':visible')) {
689 return this.getRoot().find('.dragitemgroup' + group +
690 ' .draghome.infinite' +
691 '.choice' + choice +
692 '.group' + group);
693 }
694 return this.getRoot().find('.draghome.dragplaceholder.group' + group + '.choice' + choice);
ebf91776
TH
695 };
696
697 /**
698 * Get an unplaced choice for a particular group.
699 *
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.
703 */
704 DragDropOntoImageQuestion.prototype.getUnplacedChoice = function(group, choice) {
a05ef130 705 return this.getRoot().find('.ddarea .draghome.group' + group + '.choice' + choice + '.unplaced').slice(0, 1);
ebf91776
TH
706 };
707
708 /**
709 * Get the drag that is currently in a given place.
710 *
711 * @param {int} place the place number.
712 * @return {jQuery} the current drag (or an empty jQuery if none).
713 */
714 DragDropOntoImageQuestion.prototype.getCurrentDragInPlace = function(place) {
a05ef130 715 return this.getRoot().find('.ddarea .draghome.inplace' + place);
ebf91776
TH
716 };
717
718 /**
719 * Return the number of blanks in a given group.
720 *
721 * @param {int} group the group number.
722 * @returns {int} the number of drops.
723 */
724 DragDropOntoImageQuestion.prototype.noOfDropsInGroup = function(group) {
725 return this.getRoot().find('.dropzone.group' + group).length;
726 };
727
728 /**
729 * Return the number of choices in a given group.
730 *
731 * @param {int} group the group number.
732 * @returns {int} the number of choices.
733 */
734 DragDropOntoImageQuestion.prototype.noOfChoicesInGroup = function(group) {
735 return this.getRoot().find('.dragitemgroup' + group + ' .draghome').length;
736 };
737
738 /**
739 * Return the number at the end of the CSS class name with the given prefix.
740 *
741 * @param {jQuery} node
742 * @param {String} prefix name prefix
743 * @returns {Number|null} the suffix if found, else null.
744 */
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]);
755 }
756 }
757 }
758 return null;
759 };
760
761 /**
762 * Get the choice number of a drag.
763 *
764 * @param {jQuery} drag the drag.
765 * @returns {Number} the choice number.
766 */
767 DragDropOntoImageQuestion.prototype.getChoice = function(drag) {
768 return this.getClassnameNumericSuffix(drag, 'choice');
769 };
770
771 /**
772 * Given a DOM node that is significant to this question
773 * (drag, drop, ...) get the group it belongs to.
774 *
775 * @param {jQuery} node a DOM node.
776 * @returns {Number} the group it belongs to.
777 */
778 DragDropOntoImageQuestion.prototype.getGroup = function(node) {
779 return this.getClassnameNumericSuffix(node, 'group');
780 };
781
782 /**
783 * Get the place number of a drop, or its corresponding hidden input.
784 *
785 * @param {jQuery} node the DOM node.
786 * @returns {Number} the place number.
787 */
788 DragDropOntoImageQuestion.prototype.getPlace = function(node) {
789 return this.getClassnameNumericSuffix(node, 'place');
790 };
791
a05ef130
HN
792 /**
793 * Get drag clone for a given drag.
794 *
795 * @param {jQuery} drag the drag.
796 * @returns {jQuery} the drag's clone.
797 */
798 DragDropOntoImageQuestion.prototype.getDragClone = function(drag) {
799 return this.getRoot().find('.dragitemgroup' +
800 this.getGroup(drag) +
801 ' .draghome' +
802 '.choice' + this.getChoice(drag) +
803 '.group' + this.getGroup(drag) +
804 '.dragplaceholder');
805 };
806
807 /**
808 * Get infinite drag clones for given drag.
809 *
810 * @param {jQuery} drag the drag.
811 * @param {Boolean} inHome in the home area or not.
812 * @returns {jQuery} the drag's clones.
813 */
814 DragDropOntoImageQuestion.prototype.getInfiniteDragClones = function(drag, inHome) {
815 if (inHome) {
816 return this.getRoot().find('.dragitemgroup' +
817 this.getGroup(drag) +
818 ' .draghome' +
819 '.choice' + this.getChoice(drag) +
820 '.group' + this.getGroup(drag) +
821 '.infinite').not('.dragplaceholder');
822 }
823 return this.getRoot().find('.draghome' +
824 '.choice' + this.getChoice(drag) +
825 '.group' + this.getGroup(drag) +
826 '.infinite').not('.dragplaceholder');
827 };
828
829 /**
830 * Get drop for a given drag and place.
831 *
832 * @param {jQuery} drag the drag.
833 * @param {Integer} currentPlace the current place of drag.
834 * @returns {jQuery} the drop's clone.
835 */
836 DragDropOntoImageQuestion.prototype.getDrop = function(drag, currentPlace) {
837 return this.getRoot().find('.dropzone.group' + this.getGroup(drag) + '.place' + currentPlace);
838 };
839
840 /**
841 * Handle when the window is resized.
842 */
843 DragDropOntoImageQuestion.prototype.handleResize = function() {
844 var thisQ = this,
845 bgRatio = this.bgRatio();
846 if (this.isPrinting) {
847 bgRatio = 1;
848 }
849
850 this.getRoot().find('.ddarea .dropzone').each(function(i, dropNode) {
851 $(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');
855 });
856
857 this.getRoot().find('div.droparea .draghome').not('.beingdragged').each(function(key, drag) {
858 $(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');
862 });
863 };
864
865 /**
866 * Return the background ratio.
867 *
868 * @returns {number} Background ratio.
869 */
870 DragDropOntoImageQuestion.prototype.bgRatio = function() {
871 var bgImg = this.bgImage();
872 var bgImgNaturalWidth = bgImg.get(0).naturalWidth;
873 var bgImgClientWidth = bgImg.width();
874
875 return bgImgClientWidth / bgImgNaturalWidth;
876 };
877
878 /**
879 * Scale the drag if needed.
880 *
881 * @param {jQuery} element the item to place.
882 * @param {String} type scaling type
883 */
884 DragDropOntoImageQuestion.prototype.handleElementScale = function(element, type) {
885 var bgRatio = parseFloat(this.bgRatio());
886 if (this.isPrinting) {
887 bgRatio = 1;
888 }
889 $(element).css({
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
896 });
897 };
898
899 /**
900 * Calculate z-index value.
901 *
902 * @returns {number} z-index value
903 */
904 DragDropOntoImageQuestion.prototype.calculateZIndex = function() {
905 var zIndex = 0;
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;
911
912 if (itemZIndex > zIndex) {
913 zIndex = itemZIndex;
914 }
915 });
916
917 return zIndex;
918 };
919
ebf91776
TH
920 /**
921 * Singleton object that handles all the DragDropOntoImageQuestions
922 * on the page, and deals with event dispatching.
923 * @type {Object}
924 */
925 var questionManager = {
926
927 /**
928 * {boolean} ensures that the event handlers are only initialised once per page.
929 */
930 eventHandlersInitialised: false,
931
a05ef130
HN
932 /**
933 * {boolean} is printing or not.
934 */
935 isPrinting: false,
936
937 /**
938 * {boolean} is keyboard navigation or not.
939 */
940 isKeyboardNavigation: false,
941
ebf91776
TH
942 /**
943 * {Object} all the questions on this page, indexed by containerId (id on the .que div).
944 */
945 questions: {}, // An object containing all the information about each question on the page.
946
947 /**
948 * Initialise one question.
949 *
950 * @param {String} containerId the id of the div.que that contains this question.
951 * @param {boolean} readOnly whether the question is read-only.
952 * @param {Array} places data.
953 */
954 init: function(containerId, readOnly, places) {
955 questionManager.questions[containerId] =
956 new DragDropOntoImageQuestion(containerId, readOnly, places);
957 if (!questionManager.eventHandlersInitialised) {
958 questionManager.setupEventHandlers();
959 questionManager.eventHandlersInitialised = true;
960 }
961 },
962
963 /**
964 * Set up the event handlers that make this question type work. (Done once per page.)
965 */
966 setupEventHandlers: function() {
5fa8f1c8
HN
967 // We do not use the body event here to prevent the other event on Mobile device, such as scroll event.
968 questionManager.addEventHandlersToDrag($('.que.ddimageortext:not(.qtype_ddimageortext-readonly) .draghome'));
ebf91776 969 $('body')
ebf91776
TH
970 .on('keydown',
971 '.que.ddimageortext:not(.qtype_ddimageortext-readonly) .dropzones .dropzone',
a05ef130
HN
972 questionManager.handleKeyPress)
973 .on('keydown',
974 '.que.ddimageortext:not(.qtype_ddimageortext-readonly) .draghome.placed:not(.beingdragged)',
975 questionManager.handleKeyPress)
5fa8f1c8 976 .on('qtype_ddimageortext-dragmoved', questionManager.handleDragMoved);
a05ef130
HN
977 $(window).on('resize', function() {
978 questionManager.handleWindowResize(false);
979 });
980 window.addEventListener('beforeprint', function() {
981 questionManager.isPrinting = true;
982 questionManager.handleWindowResize(questionManager.isPrinting);
983 });
984 window.addEventListener('afterprint', function() {
985 questionManager.isPrinting = false;
986 questionManager.handleWindowResize(questionManager.isPrinting);
987 });
988 setTimeout(function() {
989 questionManager.fixLayoutIfThingsMoved();
990 }, 100);
ebf91776
TH
991 },
992
5fa8f1c8
HN
993 /**
994 * Binding the drag/touch event again for newly created element.
995 *
996 * @param {jQuery} element Element to bind the event
997 */
998 addEventHandlersToDrag: function(element) {
999 element.on('mousedown touchstart', questionManager.handleDragStart);
1000 },
1001
ebf91776
TH
1002 /**
1003 * Handle mouse down / touch start events on drags.
1004 * @param {Event} e the DOM event.
1005 */
1006 handleDragStart: function(e) {
1007 e.preventDefault();
1008 var question = questionManager.getQuestionForEvent(e);
1009 if (question) {
1010 question.handleDragStart(e);
1011 }
1012 },
1013
1014 /**
1015 * Handle key down / press events on drags.
1016 * @param {KeyboardEvent} e
1017 */
1018 handleKeyPress: function(e) {
a05ef130
HN
1019 if (questionManager.isKeyboardNavigation) {
1020 return;
1021 }
1022 questionManager.isKeyboardNavigation = true;
ebf91776
TH
1023 var question = questionManager.getQuestionForEvent(e);
1024 if (question) {
1025 question.handleKeyPress(e);
1026 }
1027 },
1028
1029 /**
1030 * Handle when the window is resized.
a05ef130 1031 * @param {boolean} isPrinting
ebf91776 1032 */
a05ef130 1033 handleWindowResize: function(isPrinting) {
ebf91776
TH
1034 for (var containerId in questionManager.questions) {
1035 if (questionManager.questions.hasOwnProperty(containerId)) {
a05ef130
HN
1036 questionManager.questions[containerId].isPrinting = isPrinting;
1037 questionManager.questions[containerId].handleResize();
ebf91776
TH
1038 }
1039 }
1040 },
1041
e5153d93
TH
1042 /**
1043 * Sometimes, despite our best efforts, things change in a way that cannot
1044 * be specifically caught (e.g. dock expanding or collapsing in Boost).
1045 * Therefore, we need to periodically check everything is in the right position.
1046 */
1047 fixLayoutIfThingsMoved: function() {
a05ef130 1048 this.handleWindowResize(questionManager.isPrinting);
e5153d93
TH
1049 // We use setTimeout after finishing work, rather than setInterval,
1050 // in case positioning things is slow. We want 100 ms gap
1051 // between executions, not what setInterval does.
a05ef130
HN
1052 setTimeout(function() {
1053 questionManager.fixLayoutIfThingsMoved(questionManager.isPrinting);
1054 }, 100);
1055 },
1056
1057 /**
1058 * Handle when drag moved.
1059 *
1060 * @param {Event} e the event.
1061 * @param {jQuery} drag the drag
1062 * @param {jQuery} target the target
1063 * @param {DragDropOntoImageQuestion} thisQ the question.
1064 */
1065 handleDragMoved: function(e, drag, target, thisQ) {
1066 drag.removeClass('beingdragged').css('z-index', '');
1067 drag.css('top', target.position().top).css('left', target.position().left);
1068 target.after(drag);
1069 target.removeClass('active');
1070 if (typeof drag.data('unplaced') !== 'undefined' && drag.data('unplaced') === true) {
1071 drag.removeClass('placed').addClass('unplaced');
1072 drag.removeAttr('tabindex');
1073 drag.removeData('unplaced');
1074 drag.css('top', '')
1075 .css('left', '')
1076 .css('transform', '');
1077 if (drag.hasClass('infinite') && thisQ.getInfiniteDragClones(drag, true).length > 1) {
1078 thisQ.getInfiniteDragClones(drag, true).first().remove();
1079 }
1080 } else {
1081 drag.data('originX', target.data('originX')).data('originY', target.data('originY'));
1082 thisQ.handleElementScale(drag, 'left top');
1083 }
1084 if (typeof drag.data('isfocus') !== 'undefined' && drag.data('isfocus') === true) {
1085 drag.focus();
1086 drag.removeData('isfocus');
1087 }
1088 if (typeof target.data('isfocus') !== 'undefined' && target.data('isfocus') === true) {
1089 target.removeData('isfocus');
1090 }
1091 if (questionManager.isKeyboardNavigation) {
1092 questionManager.isKeyboardNavigation = false;
1093 }
e5153d93
TH
1094 },
1095
ebf91776
TH
1096 /**
1097 * Given an event, work out which question it effects.
1098 * @param {Event} e the event.
1099 * @returns {DragDropOntoImageQuestion|undefined} The question, or undefined.
1100 */
1101 getQuestionForEvent: function(e) {
1102 var containerId = $(e.currentTarget).closest('.que.ddimageortext').attr('id');
1103 return questionManager.questions[containerId];
1104 }
1105 };
1106
1107 /**
1108 * @alias module:qtype_ddimageortext/question
1109 */
1110 return {
1111 /**
1112 * Initialise one drag-drop onto image question.
1113 *
1114 * @param {String} containerId id of the outer div for this question.
1115 * @param {boolean} readOnly whether the question is being displayed read-only.
1116 * @param {Array} Information about the drop places.
1117 */
1118 init: questionManager.init
1119 };
1120});