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/form
20 * @copyright 2018 The Open University
21 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 define(['jquery', 'core/dragdrop'], function($, dragDrop) {
28 * Singleton object to handle progressive enhancement of the
29 * drag-drop onto image question editing form.
32 var dragDropToImageForm = {
34 * @var {Object} maxBgImageSize Properties width and height.
40 * @var {Object} maxDragImageSize with properties width and height.
43 maxDragImageSize: null,
46 * @property {object} fp for interacting with the file pickers.
49 fp: null, // Object containing functions associated with the file picker.
52 * Initialise the form javascript features.
57 dragDropToImageForm.fp = dragDropToImageForm.filePickers();
59 $('#id_previewareaheader').append(
60 '<div class="ddarea que ddimageortext">' +
61 ' <div class="droparea">' +
62 ' <img class="dropbackground" />' +
63 ' <div class="dropzones"></div>' +
65 ' <div class="dragitems"></div>' +
68 dragDropToImageForm.updateVisibilityOfFilePickers();
69 dragDropToImageForm.setOptionsForDragItemSelectors();
70 dragDropToImageForm.setupEventHandlers();
71 dragDropToImageForm.waitForFilePickerToInitialise();
75 * Waits for the file-pickers to be sufficiently ready before initialising the preview.
77 waitForFilePickerToInitialise: function() {
78 if (dragDropToImageForm.fp.file('bgimage').href === null) {
79 // It would be better to use an onload or onchange event rather than this timeout.
80 // Unfortunately attempts to do this early are overwritten by filepicker during its loading.
81 setTimeout(dragDropToImageForm.waitForFilePickerToInitialise, 1000);
84 M.util.js_pending('dragDropToImageForm');
86 // From now on, when a new file gets loaded into the filepicker, update the preview.
87 // This is not in the setupEventHandlers section as it needs to be delayed until
88 // after filepicker's javascript has finished.
89 $('form.mform[data-qtype="ddimageortext"]').on('change', '.filepickerhidden', function() {
90 M.util.js_pending('dragDropToImageForm');
91 dragDropToImageForm.loadPreviewImage();
94 dragDropToImageForm.loadPreviewImage();
98 * Loads the preview background image.
100 loadPreviewImage: function() {
101 $('fieldset#id_previewareaheader .dropbackground')
102 .one('load', dragDropToImageForm.afterPreviewImageLoaded)
103 .attr('src', dragDropToImageForm.fp.file('bgimage').href);
107 * After the background image is loaded, continue setting up the preview.
109 afterPreviewImageLoaded: function() {
110 dragDropToImageForm.createDropZones();
111 M.util.js_complete('dragDropToImageForm');
115 * Create, or recreate all the drop zones.
117 createDropZones: function() {
118 var dropZoneHolder = $('.dropzones');
119 dropZoneHolder.empty();
121 var bgimageurl = dragDropToImageForm.fp.file('bgimage').href;
122 if (bgimageurl === null) {
123 return; // There is not currently a valid preview to update.
126 var numDrops = dragDropToImageForm.form.getFormValue('nodropzone', []);
127 for (var dropNo = 0; dropNo < numDrops; dropNo++) {
128 var dragNo = dragDropToImageForm.form.getFormValue('drops', [dropNo, 'choice']);
129 if (dragNo === '0') {
133 var group = dragDropToImageForm.form.getFormValue('drags', [dragNo, 'draggroup']),
134 label = dragDropToImageForm.form.getFormValue('draglabel', [dragNo]);
135 if ('image' === dragDropToImageForm.form.getFormValue('drags', [dragNo, 'dragitemtype'])) {
136 var imgUrl = dragDropToImageForm.fp.file('dragitem[' + dragNo + ']').href;
137 if (imgUrl === null) {
140 // Althoug these are previews of drops, we also add the class name 'drag',
141 dropZoneHolder.append('<img class="droppreview group' + group + ' drop' + dropNo +
142 '" src="' + imgUrl + '" alt="' + label + '" data-drop-no="' + dropNo + '">');
144 } else if (label !== '') {
145 dropZoneHolder.append('<div class="droppreview group' + group + ' drop' + dropNo +
146 '" data-drop-no="' + dropNo + '">' + label + '</div>');
150 dragDropToImageForm.waitForAllDropImagesToBeLoaded();
154 * This polls until all the drop-zone images have loaded, and then calls updateDropZones().
156 waitForAllDropImagesToBeLoaded: function() {
157 var notYetLoadedImages = $('.dropzones img').not(function(i, imgNode) {
158 return dragDropToImageForm.imageIsLoaded(imgNode);
161 if (notYetLoadedImages.length > 0) {
162 setTimeout(function() {
163 dragDropToImageForm.waitForAllDropImagesToBeLoaded();
168 dragDropToImageForm.updateDropZones();
172 * Check if an image has loaded without errors.
174 * @param {HTMLImageElement} imgElement an image.
175 * @returns {boolean} true if this image has loaded without errors.
177 imageIsLoaded: function(imgElement) {
178 return imgElement.complete && imgElement.naturalHeight !== 0;
182 * Set the size and position of all the drop zones.
184 updateDropZones: function() {
185 var bgimageurl = dragDropToImageForm.fp.file('bgimage').href;
186 if (bgimageurl === null) {
187 return; // There is not currently a valid preview to update.
190 var dropBackgroundPosition = $('fieldset#id_previewareaheader .dropbackground').offset(),
191 numDrops = dragDropToImageForm.form.getFormValue('nodropzone', []);
193 // Move each drop to the right position and update the text.
194 for (var dropNo = 0; dropNo < numDrops; dropNo++) {
195 var drop = $('.dropzones .drop' + dropNo);
196 if (drop.length === 0) {
199 var dragNo = dragDropToImageForm.form.getFormValue('drops', [dropNo, 'choice']) - 1;
202 left: dropBackgroundPosition.left +
203 parseInt(dragDropToImageForm.form.getFormValue('drops', [dropNo, 'xleft'])),
204 top: dropBackgroundPosition.top +
205 parseInt(dragDropToImageForm.form.getFormValue('drops', [dropNo, 'ytop']))
208 var label = dragDropToImageForm.form.getFormValue('draglabel', [dragNo]);
209 if (drop.is('img')) {
210 drop.attr('alt', label);
216 // Resize them to the same size.
217 $('.dropzones .droppreview').css('padding', '0');
218 var numGroups = $('.draggroup select').first().find('option').length;
219 for (var group = 1; group <= numGroups; group++) {
220 dragDropToImageForm.resizeAllDragsAndDropsInGroup(group);
225 * In a given group, set all the drags and drops to be the same size.
227 * @param {int} group the group number.
229 resizeAllDragsAndDropsInGroup: function(group) {
230 var drops = $('.dropzones .droppreview.group' + group),
234 // Find the maximum size of any drag in this groups.
235 drops.each(function(i, drop) {
236 maxWidth = Math.max(maxWidth, Math.ceil(drop.offsetWidth));
237 maxHeight = Math.max(maxHeight, Math.ceil(drop.offsetHeight));
240 // The size we will want to set is a bit bigger than this.
244 // Set each drag home to that size.
245 drops.each(function(i, drop) {
246 var left = Math.round((maxWidth - drop.offsetWidth) / 2),
247 top = Math.floor((maxHeight - drop.offsetHeight) / 2);
248 // Set top and left padding so the item is centred.
250 'padding-left': left + 'px',
251 'padding-right': (maxWidth - drop.offsetWidth - left) + 'px',
252 'padding-top': top + 'px',
253 'padding-bottom': (maxHeight - drop.offsetHeight - top) + 'px'
259 * Events linked to form actions.
261 setupEventHandlers: function() {
262 // Changes to settings in the draggable items section.
263 $('fieldset#id_draggableitemheader')
264 .on('change input', 'input, select', function(e) {
265 var input = $(e.target).closest('select, input');
266 if (input.hasClass('dragitemtype')) {
267 dragDropToImageForm.updateVisibilityOfFilePickers();
270 dragDropToImageForm.setOptionsForDragItemSelectors();
272 if (input.is('.dragitemtype, .draggroup')) {
273 dragDropToImageForm.createDropZones();
274 } else if (input.is('.draglabel')) {
275 dragDropToImageForm.updateDropZones();
279 // Changes to Drop zones section: left, top and drag item.
280 $('fieldset#id_dropzoneheader').on('change input', 'input, select', function(e) {
281 var input = $(e.target).closest('select, input');
282 if (input.is('select')) {
283 dragDropToImageForm.createDropZones();
285 dragDropToImageForm.updateDropZones();
289 // Moving drop zones in the preview.
290 $('fieldset#id_previewareaheader').on('mousedown touchstart', '.droppreview', function(e) {
291 dragDropToImageForm.dragStart(e);
294 $(window).on('resize', function() {
295 dragDropToImageForm.updateDropZones();
300 * Update all the drag item filepickers, so they are only shown for
302 updateVisibilityOfFilePickers: function() {
303 var numDrags = dragDropToImageForm.form.getFormValue('noitems', []);
304 for (var dragNo = 0; dragNo < numDrags; dragNo++) {
305 var picker = $('input#id_dragitem_' + dragNo).closest('.fitem_ffilepicker');
306 if ('image' === dragDropToImageForm.form.getFormValue('drags', [dragNo, 'dragitemtype'])) {
315 setOptionsForDragItemSelectors: function() {
316 var dragItemOptions = {'0': ''},
317 numDrags = dragDropToImageForm.form.getFormValue('noitems', []),
318 numDrops = dragDropToImageForm.form.getFormValue('nodropzone', []);
320 // Work out the list of options.
321 for (var dragNo = 0; dragNo < numDrags; dragNo++) {
322 var label = dragDropToImageForm.form.getFormValue('draglabel', [dragNo]);
323 var file = dragDropToImageForm.fp.file(dragDropToImageForm.form.toNameWithIndex('dragitem', [dragNo]));
324 if ('image' === dragDropToImageForm.form.getFormValue('drags', [dragNo, 'dragitemtype']) && file.name !== null) {
325 dragItemOptions[dragNo + 1] = (dragNo + 1) + '. ' + label + ' (' + file.name + ')';
326 } else if (label !== '') {
327 dragItemOptions[dragNo + 1] = (dragNo + 1) + '. ' + label;
331 // Initialise each select.
332 for (var dropNo = 0; dropNo < numDrops; dropNo++) {
333 var selector = $('#id_drops_' + dropNo + '_choice');
335 var selectedvalue = selector.val();
336 selector.find('option').remove();
337 for (var value in dragItemOptions) {
338 if (!dragItemOptions.hasOwnProperty(value)) {
341 selector.append('<option value="' + value + '">' + dragItemOptions[value] + '</option>');
342 var optionnode = selector.find('option[value="' + value + '"]');
343 if (parseInt(value) === parseInt(selectedvalue)) {
344 optionnode.attr('selected', true);
345 } else if (dragDropToImageForm.isItemUsed(parseInt(value))) {
346 optionnode.attr('disabled', true);
353 * Checks if the specified drag option is already used somewhere.
355 * @param {Number} value of the drag item to check
356 * @return {Boolean} true if item is allocated to dropzone
358 isItemUsed: function(value) {
360 return false; // None option can always be selected.
363 if (dragDropToImageForm.form.getFormValue('drags', [value - 1, 'infinite'])) {
364 return false; // Infinite, so can't be used up.
367 return $('fieldset#id_dropzoneheader select').filter(function(i, selectNode) {
368 return parseInt($(selectNode).val()) === value;
373 * Handles when a dropzone in dragged in the preview.
374 * @param {Object} e Event object
376 dragStart: function(e) {
377 var drop = $(e.target).closest('.droppreview');
379 var info = dragDrop.prepare(e);
384 dragDrop.start(e, drop, function(x, y, drop) {
385 dragDropToImageForm.dragMove(drop);
387 dragDropToImageForm.dragEnd();
392 * Handles update while a drop is being dragged.
394 * @param {jQuery} drop the drop preview being moved.
396 dragMove: function(drop) {
397 var backgroundImage = $('fieldset#id_previewareaheader .dropbackground'),
398 backgroundPosition = backgroundImage.offset(),
399 dropNo = drop.data('dropNo'),
400 dropPosition = drop.offset(),
401 left = Math.round(dropPosition.left - backgroundPosition.left),
402 top = Math.round(dropPosition.top - backgroundPosition.top);
404 // Constrain coordinates to be inside the background.
405 left = Math.round(Math.max(0, Math.min(left, backgroundImage.outerWidth() - drop.outerWidth())));
406 top = Math.round(Math.max(0, Math.min(top, backgroundImage.outerHeight() - drop.outerHeight())));
409 dragDropToImageForm.form.setFormValue('drops', [dropNo, 'xleft'], left);
410 dragDropToImageForm.form.setFormValue('drops', [dropNo, 'ytop'], top);
414 * Handles when the drag ends.
416 dragEnd: function() {
417 // Redraw, in case the position was constrained.
418 dragDropToImageForm.updateDropZones();
422 * Low level operations on form.
425 toNameWithIndex: function(name, indexes) {
426 var indexString = name;
427 for (var i = 0; i < indexes.length; i++) {
428 indexString = indexString + '[' + indexes[i] + ']';
433 getEl: function(name, indexes) {
434 var form = $('form.mform[data-qtype="ddimageortext"]')[0];
435 return form.elements[this.toNameWithIndex(name, indexes)];
439 * Helper to get the value of a form elements with name like "drops[0][xleft]".
441 * @param {String} name the base name, e.g. 'drops'.
442 * @param {String[]} indexes the indexes, e.g. ['0', 'xleft'].
443 * @return {String} the value of that field.
445 getFormValue: function(name, indexes) {
446 var el = this.getEl(name, indexes);
448 el = el[el.length - 1];
450 if (el.type === 'checkbox') {
458 * Helper to get the value of a form elements with name like "drops[0][xleft]".
460 * @param {String} name the base name, e.g. 'drops'.
461 * @param {String[]} indexes the indexes, e.g. ['0', 'xleft'].
462 * @param {String|Number} value the value to set.
464 setFormValue: function(name, indexes, value) {
465 var el = this.getEl(name, indexes);
466 if (el.type === 'checkbox') {
475 * Utility to get the file name and url from the filepicker.
476 * @returns {Object} object containing functions {file, name}
478 filePickers: function() {
479 var draftItemIdsToName;
480 var nameToParentNode;
482 if (draftItemIdsToName === undefined) {
483 draftItemIdsToName = {};
484 nameToParentNode = {};
485 var fp = $('form.mform[data-qtype="ddimageortext"] input.filepickerhidden');
486 fp.each(function(index, filepicker) {
487 draftItemIdsToName[filepicker.value] = filepicker.name;
488 nameToParentNode[filepicker.name] = filepicker.parentNode;
493 file: function(name) {
494 var parentNode = $(nameToParentNode[name]);
495 var fileAnchor = parentNode.find('div.filepicker-filelist a');
496 if (fileAnchor.length) {
497 return {href: fileAnchor.get(0).href, name: fileAnchor.get(0).innerHTML};
499 return {href: null, name: null};
503 name: function(draftitemid) {
504 return draftItemIdsToName[draftitemid];
511 init: dragDropToImageForm.init