MDL-69104 Questions: Drag and drop question family don't work with iOS
[moodle.git] / question / type / ddwtos / amd / src / ddwtos.js
CommitLineData
68943aff
K
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
c28d0aa1
TH
16/**
17 * JavaScript to make drag-drop into text questions work.
68943aff 18 *
c28d0aa1
TH
19 * Some vocabulary to help understand this code:
20 *
21 * The question text contains 'drops' - blanks into which the 'drags', the missing
22 * words, can be put.
23 *
24 * The thing that can be moved into the drops are called 'drags'. There may be
25 * multiple copies of the 'same' drag which does not really cause problems.
26 * Each drag has a 'choice' number which is the value set on the drop's hidden
27 * input when this drag is placed in a drop.
28 *
29 * These may be in separate 'groups', distinguished by colour.
30 * Things can only interact with other things in the same group.
31 * The groups are numbered from 1.
32 *
33 * The place where a given drag started from is called its 'home'.
34 *
35 * @module qtype_ddwtos/ddwtos
36 * @package qtype_ddwtos
68943aff
K
37 * @copyright 2018 The Open University
38 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
c28d0aa1 39 * @since 3.6
68943aff 40 */
c28d0aa1 41define(['jquery', 'core/dragdrop', 'core/key_codes'], function($, dragDrop, keys) {
68943aff
K
42
43 "use strict";
44
c28d0aa1
TH
45 /**
46 * Object to handle one drag-drop into text question.
47 *
48 * @param {String} containerId id of the outer div for this question.
49 * @param {boolean} readOnly whether the question is being displayed read-only.
50 * @constructor
51 */
52 function DragDropToTextQuestion(containerId, readOnly) {
53 this.containerId = containerId;
54 if (readOnly) {
55 this.getRoot().addClass('qtype_ddwtos-readonly');
56 }
57 this.resizeAllDragsAndDrops();
58 this.cloneDrags();
59 this.positionDrags();
60 }
61
62 /**
63 * In each group, resize all the items to be the same size.
64 */
65 DragDropToTextQuestion.prototype.resizeAllDragsAndDrops = function() {
66 var thisQ = this;
d434dd7a
TH
67 this.getRoot().find('.answercontainer > div').each(function(i, node) {
68 thisQ.resizeAllDragsAndDropsInGroup(
69 thisQ.getClassnameNumericSuffix($(node), 'draggrouphomes'));
c28d0aa1
TH
70 });
71 };
68943aff 72
c28d0aa1
TH
73 /**
74 * In a given group, set all the drags and drops to be the same size.
75 *
76 * @param {int} group the group number.
77 */
78 DragDropToTextQuestion.prototype.resizeAllDragsAndDropsInGroup = function(group) {
79 var thisQ = this,
80 dragHomes = this.getRoot().find('.draggrouphomes' + group + ' span.draghome'),
81 maxWidth = 0,
82 maxHeight = 0;
83
84 // Find the maximum size of any drag in this groups.
85 dragHomes.each(function(i, drag) {
86 maxWidth = Math.max(maxWidth, Math.ceil(drag.offsetWidth));
87 maxHeight = Math.max(maxHeight, Math.ceil(0 + drag.offsetHeight));
88 });
89
90 // The size we will want to set is a bit bigger than this.
91 maxWidth += 8;
92 maxHeight += 2;
93
94 // Set each drag home to that size.
95 dragHomes.each(function(i, drag) {
96 thisQ.setElementSize(drag, maxWidth, maxHeight);
97 });
98
99 // Set each drop to that size.
100 this.getRoot().find('span.drop.group' + group).each(function(i, drop) {
101 thisQ.setElementSize(drop, maxWidth, maxHeight);
102 });
103 };
68943aff 104
c28d0aa1
TH
105 /**
106 * Set a given DOM element to be a particular size.
107 *
108 * @param {HTMLElement} element
109 * @param {int} width
110 * @param {int} height
111 */
112 DragDropToTextQuestion.prototype.setElementSize = function(element, width, height) {
113 $(element).width(width).height(height).css('lineHeight', height + 'px');
114 };
68943aff 115
c28d0aa1
TH
116 /**
117 * Invisible 'drag homes' are output by the renderer. These have the same properties
118 * as the drag items but are invisible. We clone these invisible elements to make the
119 * actual drag items.
120 */
121 DragDropToTextQuestion.prototype.cloneDrags = function() {
122 var thisQ = this;
f389e916
HN
123 thisQ.getRoot().find('span.draghome').each(function(index, draghome) {
124 var drag = $(draghome);
125 var placeHolder = drag.clone();
126 placeHolder.removeClass();
127 placeHolder.addClass('draghome choice' +
128 thisQ.getChoice(drag) + ' group' +
129 thisQ.getGroup(drag) + ' dragplaceholder');
130 drag.before(placeHolder);
c28d0aa1
TH
131 });
132 };
68943aff 133
c28d0aa1
TH
134 /**
135 * Update the position of drags.
136 */
137 DragDropToTextQuestion.prototype.positionDrags = function() {
138 var thisQ = this,
139 root = this.getRoot();
140
141 // First move all items back home.
f389e916 142 root.find('span.draghome').not('.dragplaceholder').each(function(i, dragNode) {
c28d0aa1
TH
143 var drag = $(dragNode),
144 currentPlace = thisQ.getClassnameNumericSuffix(drag, 'inplace');
145 drag.addClass('unplaced')
f389e916
HN
146 .removeClass('placed');
147 drag.removeAttr('tabindex');
c28d0aa1
TH
148 if (currentPlace !== null) {
149 drag.removeClass('inplace' + currentPlace);
150 }
151 });
152
153 // Then place the once that should be placed.
154 root.find('input.placeinput').each(function(i, inputNode) {
155 var input = $(inputNode),
b2512618
JF
156 choice = input.val(),
157 place = thisQ.getPlace(input);
158
159 // Record the last known position of the drop.
160 var drop = root.find('.drop.place' + place),
161 dropPosition = drop.offset();
162 drop.data('prev-top', dropPosition.top).data('prev-left', dropPosition.left);
163
c28d0aa1
TH
164 if (choice === '0') {
165 // No item in this place.
166 return;
167 }
68943aff 168
f389e916
HN
169 // Get the unplaced drag.
170 var unplacedDrag = thisQ.getUnplacedChoice(thisQ.getGroup(input), choice);
171 // Get the clone of the drag.
172 var hiddenDrag = thisQ.getDragClone(unplacedDrag);
173 if (hiddenDrag.length) {
174 hiddenDrag.addClass('active');
b2512618 175 }
f389e916
HN
176 // Send the drag to drop.
177 thisQ.sendDragToDrop(thisQ.getUnplacedChoice(thisQ.getGroup(input), choice), drop);
b2512618 178 });
b2512618
JF
179 };
180
c28d0aa1
TH
181 /**
182 * Handles the start of dragging an item.
183 *
184 * @param {Event} e the touch start or mouse down event.
185 */
186 DragDropToTextQuestion.prototype.handleDragStart = function(e) {
187 var thisQ = this,
f389e916 188 drag = $(e.target).closest('.draghome');
c28d0aa1
TH
189
190 var info = dragDrop.prepare(e);
191 if (!info.start) {
192 return;
193 }
68943aff 194
f389e916 195 drag.addClass('beingdragged');
c28d0aa1
TH
196 var currentPlace = this.getClassnameNumericSuffix(drag, 'inplace');
197 if (currentPlace !== null) {
198 this.setInputValue(currentPlace, 0);
199 drag.removeClass('inplace' + currentPlace);
f389e916
HN
200 var hiddenDrop = thisQ.getDrop(drag, currentPlace);
201 if (hiddenDrop.length) {
202 hiddenDrop.addClass('active');
203 drag.offset(hiddenDrop.offset());
204 }
205 } else {
206 var hiddenDrag = thisQ.getDragClone(drag);
207 if (hiddenDrag.length) {
208 if (drag.hasClass('infinite')) {
209 var noOfDrags = this.noOfDropsInGroup(this.getGroup(drag));
210 var cloneDrags = this.getInfiniteDragClones(drag, false);
211 if (cloneDrags.length < noOfDrags) {
212 var cloneDrag = drag.clone();
213 cloneDrag.removeClass('beingdragged');
214 hiddenDrag.after(cloneDrag);
5fa8f1c8 215 questionManager.addEventHandlersToDrag(cloneDrag);
f389e916
HN
216 drag.offset(cloneDrag.offset());
217 } else {
218 hiddenDrag.addClass('active');
219 drag.offset(hiddenDrag.offset());
220 }
221 } else {
222 hiddenDrag.addClass('active');
223 drag.offset(hiddenDrag.offset());
224 }
225 }
c28d0aa1 226 }
68943aff 227
c28d0aa1
TH
228 dragDrop.start(e, drag, function(x, y, drag) {
229 thisQ.dragMove(x, y, drag);
230 }, function(x, y, drag) {
231 thisQ.dragEnd(x, y, drag);
232 });
233 };
68943aff 234
c28d0aa1
TH
235 /**
236 * Called whenever the currently dragged items moves.
237 *
238 * @param {Number} pageX the x position.
239 * @param {Number} pageY the y position.
240 * @param {jQuery} drag the item being moved.
241 */
242 DragDropToTextQuestion.prototype.dragMove = function(pageX, pageY, drag) {
243 var thisQ = this;
244 this.getRoot().find('span.drop.group' + this.getGroup(drag)).each(function(i, dropNode) {
245 var drop = $(dropNode);
246 if (thisQ.isPointInDrop(pageX, pageY, drop)) {
247 drop.addClass('valid-drag-over-drop');
68943aff 248 } else {
c28d0aa1 249 drop.removeClass('valid-drag-over-drop');
68943aff 250 }
c28d0aa1 251 });
f389e916
HN
252 this.getRoot().find('span.draghome.placed.group' + this.getGroup(drag)).not('.beingdragged').each(function(i, dropNode) {
253 var drop = $(dropNode);
254 if (thisQ.isPointInDrop(pageX, pageY, drop)) {
255 drop.addClass('valid-drag-over-drop');
256 } else {
257 drop.removeClass('valid-drag-over-drop');
258 }
259 });
c28d0aa1 260 };
68943aff 261
c28d0aa1
TH
262 /**
263 * Called when user drops a drag item.
264 *
265 * @param {Number} pageX the x position.
266 * @param {Number} pageY the y position.
267 * @param {jQuery} drag the item being moved.
268 */
269 DragDropToTextQuestion.prototype.dragEnd = function(pageX, pageY, drag) {
270 var thisQ = this,
271 root = this.getRoot(),
272 placed = false;
273 root.find('span.drop.group' + this.getGroup(drag)).each(function(i, dropNode) {
274 var drop = $(dropNode);
275 if (!thisQ.isPointInDrop(pageX, pageY, drop)) {
276 // Not this drop.
277 return true;
68943aff 278 }
68943aff 279
c28d0aa1
TH
280 // Now put this drag into the drop.
281 drop.removeClass('valid-drag-over-drop');
282 thisQ.sendDragToDrop(drag, drop);
283 placed = true;
284 return false; // Stop the each() here.
285 });
68943aff 286
f389e916
HN
287 root.find('span.draghome.placed.group' + this.getGroup(drag)).not('.beingdragged').each(function(i, placedNode) {
288 var placedDrag = $(placedNode);
289 if (!thisQ.isPointInDrop(pageX, pageY, placedDrag)) {
290 // Not this placed drag.
291 return true;
292 }
293
294 // Now put this drag into the drop.
295 placedDrag.removeClass('valid-drag-over-drop');
296 var currentPlace = thisQ.getClassnameNumericSuffix(placedDrag, 'inplace');
297 var drop = thisQ.getDrop(drag, currentPlace);
298 thisQ.sendDragToDrop(drag, drop);
299 placed = true;
300 return false; // Stop the each() here.
301 });
302
c28d0aa1
TH
303 if (!placed) {
304 this.sendDragHome(drag);
305 }
306 };
68943aff 307
c28d0aa1
TH
308 /**
309 * Animate a drag item into a given place (or back home).
310 *
311 * @param {jQuery|null} drag the item to place. If null, clear the place.
312 * @param {jQuery} drop the place to put it.
313 */
314 DragDropToTextQuestion.prototype.sendDragToDrop = function(drag, drop) {
315 // Is there already a drag in this drop? if so, evict it.
316 var oldDrag = this.getCurrentDragInPlace(this.getPlace(drop));
317 if (oldDrag.length !== 0) {
f389e916
HN
318 var currentPlace = this.getClassnameNumericSuffix(oldDrag, 'inplace');
319 var hiddenDrop = this.getDrop(oldDrag, currentPlace);
320 hiddenDrop.addClass('active');
1937957b
HN
321 oldDrag.addClass('beingdragged');
322 oldDrag.offset(hiddenDrop.offset());
c28d0aa1
TH
323 this.sendDragHome(oldDrag);
324 }
68943aff 325
c28d0aa1
TH
326 if (drag.length === 0) {
327 this.setInputValue(this.getPlace(drop), 0);
f389e916
HN
328 if (drop.data('isfocus')) {
329 drop.focus();
330 }
c28d0aa1
TH
331 } else {
332 this.setInputValue(this.getPlace(drop), this.getChoice(drag));
333 drag.removeClass('unplaced')
334 .addClass('placed inplace' + this.getPlace(drop));
f389e916 335 drag.attr('tabindex', 0);
c28d0aa1
TH
336 this.animateTo(drag, drop);
337 }
338 };
339
340 /**
341 * Animate a drag back to its home.
342 *
343 * @param {jQuery} drag the item being moved.
344 */
345 DragDropToTextQuestion.prototype.sendDragHome = function(drag) {
c28d0aa1
TH
346 var currentPlace = this.getClassnameNumericSuffix(drag, 'inplace');
347 if (currentPlace !== null) {
348 drag.removeClass('inplace' + currentPlace);
349 }
f389e916 350 drag.data('unplaced', true);
68943aff 351
c28d0aa1
TH
352 this.animateTo(drag, this.getDragHome(this.getGroup(drag), this.getChoice(drag)));
353 };
354
355 /**
356 * Handles keyboard events on drops.
357 *
358 * Drops are focusable. Once focused, right/down/space switches to the next choice, and
359 * left/up switches to the previous. Escape clear.
360 *
361 * @param {KeyboardEvent} e
362 */
363 DragDropToTextQuestion.prototype.handleKeyPress = function(e) {
f389e916
HN
364 var drop = $(e.target).closest('.drop');
365 if (drop.length === 0) {
366 var placedDrag = $(e.target);
367 var currentPlace = this.getClassnameNumericSuffix(placedDrag, 'inplace');
368 if (currentPlace !== null) {
369 drop = this.getDrop(placedDrag, currentPlace);
370 }
371 }
372 var currentDrag = this.getCurrentDragInPlace(this.getPlace(drop)),
c28d0aa1
TH
373 nextDrag = $();
374
375 switch (e.keyCode) {
376 case keys.space:
377 case keys.arrowRight:
378 case keys.arrowDown:
379 nextDrag = this.getNextDrag(this.getGroup(drop), currentDrag);
380 break;
381
382 case keys.arrowLeft:
383 case keys.arrowUp:
384 nextDrag = this.getPreviousDrag(this.getGroup(drop), currentDrag);
385 break;
386
387 case keys.escape:
388 break;
389
390 default:
1937957b 391 questionManager.isKeyboardNavigation = false;
c28d0aa1
TH
392 return; // To avoid the preventDefault below.
393 }
394
f389e916
HN
395 if (nextDrag.length) {
396 nextDrag.data('isfocus', true);
1937957b
HN
397 nextDrag.addClass('beingdragged');
398 var hiddenDrag = this.getDragClone(nextDrag);
399 if (hiddenDrag.length) {
400 if (nextDrag.hasClass('infinite')) {
401 var noOfDrags = this.noOfDropsInGroup(this.getGroup(nextDrag));
402 var cloneDrags = this.getInfiniteDragClones(nextDrag, false);
403 if (cloneDrags.length < noOfDrags) {
404 var cloneDrag = nextDrag.clone();
405 cloneDrag.removeClass('beingdragged');
406 cloneDrag.removeAttr('tabindex');
407 hiddenDrag.after(cloneDrag);
5fa8f1c8 408 questionManager.addEventHandlersToDrag(cloneDrag);
1937957b
HN
409 nextDrag.offset(cloneDrag.offset());
410 } else {
411 hiddenDrag.addClass('active');
412 nextDrag.offset(hiddenDrag.offset());
413 }
414 } else {
415 hiddenDrag.addClass('active');
416 nextDrag.offset(hiddenDrag.offset());
417 }
418 }
f389e916
HN
419 } else {
420 drop.data('isfocus', true);
421 }
422
c28d0aa1
TH
423 e.preventDefault();
424 this.sendDragToDrop(nextDrag, drop);
425 };
426
427 /**
428 * Choose the next drag in a group.
429 *
430 * @param {int} group which group.
431 * @param {jQuery} drag current choice (empty jQuery if there isn't one).
432 * @return {jQuery} the next drag in that group, or null if there wasn't one.
433 */
434 DragDropToTextQuestion.prototype.getNextDrag = function(group, drag) {
435 var choice,
436 numChoices = this.noOfChoicesInGroup(group);
437
438 if (drag.length === 0) {
439 choice = 1; // Was empty, so we want to select the first choice.
440 } else {
441 choice = this.getChoice(drag) + 1;
442 }
443
444 var next = this.getUnplacedChoice(group, choice);
445 while (next.length === 0 && choice < numChoices) {
446 choice++;
447 next = this.getUnplacedChoice(group, choice);
448 }
449
450 return next;
451 };
452
453 /**
454 * Choose the previous drag in a group.
455 *
456 * @param {int} group which group.
457 * @param {jQuery} drag current choice (empty jQuery if there isn't one).
458 * @return {jQuery} the next drag in that group, or null if there wasn't one.
459 */
460 DragDropToTextQuestion.prototype.getPreviousDrag = function(group, drag) {
461 var choice;
462
463 if (drag.length === 0) {
464 choice = this.noOfChoicesInGroup(group);
465 } else {
466 choice = this.getChoice(drag) - 1;
467 }
468
469 var previous = this.getUnplacedChoice(group, choice);
470 while (previous.length === 0 && choice > 1) {
471 choice--;
472 previous = this.getUnplacedChoice(group, choice);
473 }
474
475 // Does this choice exist?
476 return previous;
477 };
478
479 /**
480 * Animate an object to the given destination.
481 *
482 * @param {jQuery} drag the element to be animated.
483 * @param {jQuery} target element marking the place to move it to.
484 */
485 DragDropToTextQuestion.prototype.animateTo = function(drag, target) {
486 var currentPos = drag.offset(),
f389e916
HN
487 targetPos = target.offset(),
488 thisQ = this;
c28d0aa1 489
f389e916 490 M.util.js_pending('qtype_ddwtos-animate-' + thisQ.containerId);
c28d0aa1
TH
491 // Animate works in terms of CSS position, whereas locating an object
492 // on the page works best with jQuery offset() function. So, to get
493 // the right target position, we work out the required change in
494 // offset() and then add that to the current CSS position.
495 drag.animate(
496 {
497 left: parseInt(drag.css('left')) + targetPos.left - currentPos.left,
498 top: parseInt(drag.css('top')) + targetPos.top - currentPos.top
499 },
500 {
501 duration: 'fast',
502 done: function() {
5fa8f1c8 503 $('body').trigger('qtype_ddwtos-dragmoved', [drag, target, thisQ]);
f389e916 504 M.util.js_complete('qtype_ddwtos-animate-' + thisQ.containerId);
68943aff 505 }
68943aff 506 }
c28d0aa1
TH
507 );
508 };
68943aff 509
c28d0aa1
TH
510 /**
511 * Detect if a point is inside a given DOM node.
512 *
513 * @param {Number} pageX the x position.
514 * @param {Number} pageY the y position.
515 * @param {jQuery} drop the node to check (typically a drop).
516 * @return {boolean} whether the point is inside the node.
517 */
518 DragDropToTextQuestion.prototype.isPointInDrop = function(pageX, pageY, drop) {
519 var position = drop.offset();
520 return pageX >= position.left && pageX < position.left + drop.width()
521 && pageY >= position.top && pageY < position.top + drop.height();
522 };
68943aff 523
c28d0aa1
TH
524 /**
525 * Set the value of the hidden input for a place, to record what is currently there.
526 *
527 * @param {int} place which place to set the input value for.
528 * @param {int} choice the value to set.
529 */
530 DragDropToTextQuestion.prototype.setInputValue = function(place, choice) {
531 this.getRoot().find('input.placeinput.place' + place).val(choice);
532 };
68943aff 533
c28d0aa1
TH
534 /**
535 * Get the outer div for this question.
536 *
537 * @returns {jQuery} containing that div.
538 */
539 DragDropToTextQuestion.prototype.getRoot = function() {
540 return $(document.getElementById(this.containerId));
541 };
68943aff 542
c28d0aa1
TH
543 /**
544 * Get drag home for a given choice.
545 *
546 * @param {int} group the group.
547 * @param {int} choice the choice number.
548 * @returns {jQuery} containing that div.
549 */
550 DragDropToTextQuestion.prototype.getDragHome = function(group, choice) {
f389e916
HN
551 if (!this.getRoot().find('.draghome.dragplaceholder.group' + group + '.choice' + choice).is(':visible')) {
552 return this.getRoot().find('.draggrouphomes' + group +
553 ' span.draghome.infinite' +
554 '.choice' + choice +
555 '.group' + group);
556 }
557 return this.getRoot().find('.draghome.dragplaceholder.group' + group + '.choice' + choice);
c28d0aa1 558 };
68943aff 559
c28d0aa1
TH
560 /**
561 * Get an unplaced choice for a particular group.
562 *
563 * @param {int} group the group.
564 * @param {int} choice the choice number.
565 * @returns {jQuery} jQuery wrapping the unplaced choice. If there isn't one, the jQuery will be empty.
566 */
567 DragDropToTextQuestion.prototype.getUnplacedChoice = function(group, choice) {
f389e916 568 return this.getRoot().find('.draghome.group' + group + '.choice' + choice + '.unplaced').slice(0, 1);
c28d0aa1 569 };
68943aff 570
c28d0aa1
TH
571 /**
572 * Get the drag that is currently in a given place.
573 *
574 * @param {int} place the place number.
575 * @return {jQuery} the current drag (or an empty jQuery if none).
576 */
577 DragDropToTextQuestion.prototype.getCurrentDragInPlace = function(place) {
f389e916 578 return this.getRoot().find('span.draghome.inplace' + place);
c28d0aa1 579 };
68943aff 580
c28d0aa1
TH
581 /**
582 * Return the number of blanks in a given group.
583 *
584 * @param {int} group the group number.
585 * @returns {int} the number of drops.
586 */
587 DragDropToTextQuestion.prototype.noOfDropsInGroup = function(group) {
588 return this.getRoot().find('.drop.group' + group).length;
589 };
68943aff 590
c28d0aa1
TH
591 /**
592 * Return the number of choices in a given group.
593 *
594 * @param {int} group the group number.
595 * @returns {int} the number of choices.
596 */
597 DragDropToTextQuestion.prototype.noOfChoicesInGroup = function(group) {
598 return this.getRoot().find('.draghome.group' + group).length;
599 };
68943aff 600
c28d0aa1
TH
601 /**
602 * Return the number at the end of the CSS class name with the given prefix.
603 *
604 * @param {jQuery} node
605 * @param {String} prefix name prefix
606 * @returns {Number|null} the suffix if found, else null.
607 */
608 DragDropToTextQuestion.prototype.getClassnameNumericSuffix = function(node, prefix) {
609 var classes = node.attr('class');
610 if (classes !== '') {
611 var classesArr = classes.split(' ');
612 for (var index = 0; index < classesArr.length; index++) {
613 var patt1 = new RegExp('^' + prefix + '([0-9])+$');
614 if (patt1.test(classesArr[index])) {
615 var patt2 = new RegExp('([0-9])+$');
616 var match = patt2.exec(classesArr[index]);
617 return Number(match[0]);
618 }
68943aff 619 }
c28d0aa1
TH
620 }
621 return null;
622 };
68943aff 623
c28d0aa1
TH
624 /**
625 * Get the choice number of a drag.
626 *
627 * @param {jQuery} drag the drag.
628 * @returns {Number} the choice number.
629 */
630 DragDropToTextQuestion.prototype.getChoice = function(drag) {
631 return this.getClassnameNumericSuffix(drag, 'choice');
632 };
68943aff 633
c28d0aa1
TH
634 /**
635 * Given a DOM node that is significant to this question
636 * (drag, drop, ...) get the group it belongs to.
637 *
638 * @param {jQuery} node a DOM node.
639 * @returns {Number} the group it belongs to.
640 */
641 DragDropToTextQuestion.prototype.getGroup = function(node) {
642 return this.getClassnameNumericSuffix(node, 'group');
643 };
644
645 /**
646 * Get the place number of a drop, or its corresponding hidden input.
647 *
648 * @param {jQuery} node the DOM node.
649 * @returns {Number} the place number.
650 */
651 DragDropToTextQuestion.prototype.getPlace = function(node) {
652 return this.getClassnameNumericSuffix(node, 'place');
653 };
68943aff 654
f389e916
HN
655 /**
656 * Get drag clone for a given drag.
657 *
658 * @param {jQuery} drag the drag.
659 * @returns {jQuery} the drag's clone.
660 */
661 DragDropToTextQuestion.prototype.getDragClone = function(drag) {
662 return this.getRoot().find('.draggrouphomes' +
663 this.getGroup(drag) +
664 ' span.draghome' +
665 '.choice' + this.getChoice(drag) +
666 '.group' + this.getGroup(drag) +
667 '.dragplaceholder');
668 };
669
670 /**
671 * Get infinite drag clones for given drag.
672 *
673 * @param {jQuery} drag the drag.
674 * @param {Boolean} inHome in the home area or not.
675 * @returns {jQuery} the drag's clones.
676 */
677 DragDropToTextQuestion.prototype.getInfiniteDragClones = function(drag, inHome) {
678 if (inHome) {
679 return this.getRoot().find('.draggrouphomes' +
680 this.getGroup(drag) +
681 ' span.draghome' +
682 '.choice' + this.getChoice(drag) +
683 '.group' + this.getGroup(drag) +
684 '.infinite').not('.dragplaceholder');
685 }
686 return this.getRoot().find('span.draghome' +
687 '.choice' + this.getChoice(drag) +
688 '.group' + this.getGroup(drag) +
689 '.infinite').not('.dragplaceholder');
690 };
691
692 /**
693 * Get drop for a given drag and place.
694 *
695 * @param {jQuery} drag the drag.
696 * @param {Integer} currentPlace the current place of drag.
697 * @returns {jQuery} the drop's clone.
698 */
699 DragDropToTextQuestion.prototype.getDrop = function(drag, currentPlace) {
700 return this.getRoot().find('.drop.group' + this.getGroup(drag) + '.place' + currentPlace);
701 };
702
c28d0aa1
TH
703 /**
704 * Singleton that tracks all the DragDropToTextQuestions on this page, and deals
705 * with event dispatching.
706 *
707 * @type {Object}
708 */
709 var questionManager = {
68943aff 710 /**
c28d0aa1 711 * {boolean} used to ensure the event handlers are only initialised once per page.
68943aff 712 */
c28d0aa1 713 eventHandlersInitialised: false,
68943aff 714
1937957b
HN
715 /**
716 * {boolean} is keyboard navigation or not.
717 */
718 isKeyboardNavigation: false,
719
68943aff 720 /**
c28d0aa1 721 * {DragDropToTextQuestion[]} all the questions on this page, indexed by containerId (id on the .que div).
68943aff 722 */
c28d0aa1 723 questions: {},
68943aff
K
724
725 /**
c28d0aa1
TH
726 * Initialise questions.
727 *
728 * @param {String} containerId id of the outer div for this question.
729 * @param {boolean} readOnly whether the question is being displayed read-only.
730 */
731 init: function(containerId, readOnly) {
732 questionManager.questions[containerId] = new DragDropToTextQuestion(containerId, readOnly);
733 if (!questionManager.eventHandlersInitialised) {
734 questionManager.setupEventHandlers();
735 questionManager.eventHandlersInitialised = true;
68943aff 736 }
68943aff
K
737 },
738
739 /**
c28d0aa1 740 * Set up the event handlers that make this question type work. (Done once per page.)
68943aff 741 */
c28d0aa1 742 setupEventHandlers: function() {
5fa8f1c8
HN
743 // We do not use the body event here to prevent the other event on Mobile device, such as scroll event.
744 questionManager.addEventHandlersToDrag($('.que.ddwtos:not(.qtype_ddwtos-readonly) span.draghome'));
745 $('body')
c28d0aa1
TH
746 .on('keydown',
747 '.que.ddwtos:not(.qtype_ddwtos-readonly) span.drop',
f389e916
HN
748 questionManager.handleKeyPress)
749 .on('keydown',
750 '.que.ddwtos:not(.qtype_ddwtos-readonly) span.draghome.placed:not(.beingdragged)',
751 questionManager.handleKeyPress)
5fa8f1c8
HN
752 .on('qtype_ddwtos-dragmoved', questionManager.handleDragMoved);
753 },
754
755 /**
756 * Binding the drag/touch event again for newly created element.
757 *
758 * @param {jQuery} element Element to bind the event
759 */
760 addEventHandlersToDrag: function(element) {
761 element.on('mousedown touchstart', questionManager.handleDragStart);
68943aff
K
762 },
763
764 /**
c28d0aa1
TH
765 * Handle mouse down / touch start on drags.
766 * @param {Event} e the DOM event.
68943aff 767 */
c28d0aa1
TH
768 handleDragStart: function(e) {
769 e.preventDefault();
770 var question = questionManager.getQuestionForEvent(e);
771 if (question) {
772 question.handleDragStart(e);
773 }
68943aff
K
774 },
775
776 /**
c28d0aa1
TH
777 * Handle key down / press on drops.
778 * @param {KeyboardEvent} e
68943aff 779 */
c28d0aa1 780 handleKeyPress: function(e) {
1937957b
HN
781 if (questionManager.isKeyboardNavigation) {
782 return;
783 }
784 questionManager.isKeyboardNavigation = true;
c28d0aa1
TH
785 var question = questionManager.getQuestionForEvent(e);
786 if (question) {
787 question.handleKeyPress(e);
788 }
68943aff
K
789 },
790
68943aff 791 /**
c28d0aa1 792 * Given an event, work out which question it affects.
68943aff 793 *
c28d0aa1
TH
794 * @param {Event} e the event.
795 * @returns {DragDropToTextQuestion|undefined} The question, or undefined.
68943aff 796 */
c28d0aa1
TH
797 getQuestionForEvent: function(e) {
798 var containerId = $(e.currentTarget).closest('.que.ddwtos').attr('id');
799 return questionManager.questions[containerId];
f389e916
HN
800 },
801
802 /**
803 * Handle when drag moved.
804 *
805 * @param {Event} e the event.
806 * @param {jQuery} drag the drag
807 * @param {jQuery} target the target
808 * @param {DragDropToTextQuestion} thisQ the question.
809 */
810 handleDragMoved: function(e, drag, target, thisQ) {
811 drag.removeClass('beingdragged');
812 drag.css('top', '').css('left', '');
813 target.after(drag);
814 target.removeClass('active');
815 if (typeof drag.data('unplaced') !== 'undefined' && drag.data('unplaced') === true) {
816 drag.removeClass('placed').addClass('unplaced');
817 drag.removeAttr('tabindex');
818 drag.removeData('unplaced');
819 if (drag.hasClass('infinite') && thisQ.getInfiniteDragClones(drag, true).length > 1) {
1937957b 820 thisQ.getInfiniteDragClones(drag, true).first().remove();
f389e916
HN
821 }
822 }
823 if (typeof drag.data('isfocus') !== 'undefined' && drag.data('isfocus') === true) {
f389e916
HN
824 drag.focus();
825 drag.removeData('isfocus');
826 }
827 if (typeof target.data('isfocus') !== 'undefined' && target.data('isfocus') === true) {
828 target.removeData('isfocus');
829 }
1937957b
HN
830 if (questionManager.isKeyboardNavigation) {
831 questionManager.isKeyboardNavigation = false;
832 }
68943aff
K
833 }
834 };
c28d0aa1
TH
835
836 /**
837 * @alias module:qtype_ddwtos/ddwtos
838 */
839 return {
840 /**
841 * Initialise one drag-drop into text question.
842 *
843 * @param {String} containerId id of the outer div for this question.
844 * @param {boolean} readOnly whether the question is being displayed read-only.
845 */
846 init: questionManager.init
847 };
68943aff 848});