on-demand release 4.0dev+
[moodle.git] / question / type / ddimageortext / amd / src / form.js
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/>.
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/form
20  * @copyright  2018 The Open University
21  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
22  */
23 define(['jquery', 'core/dragdrop'], function($, dragDrop) {
25     "use strict";
27     /**
28      * Singleton object to handle progressive enhancement of the
29      * drag-drop onto image question editing form.
30      * @type {Object}
31      */
32     var dragDropToImageForm = {
33         /**
34          * @var {Object} maxBgImageSize Properties width and height.
35          * @private
36          */
37         maxBgImageSize: null,
39         /**
40          * @var {Object} maxDragImageSize with properties width and height.
41          * @private
42          */
43         maxDragImageSize: null,
45         /**
46          * @property {object} fp for interacting with the file pickers.
47          * @private
48          */
49         fp: null, // Object containing functions associated with the file picker.
51         /**
52          * Initialise the form javascript features.
53          *
54          * @method
55          */
56         init: function() {
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>' +
64                 '  </div>' +
65                 '  <div class="dragitems"></div>' +
66                 '</div>');
68             dragDropToImageForm.updateVisibilityOfFilePickers();
69             dragDropToImageForm.setOptionsForDragItemSelectors();
70             dragDropToImageForm.setupEventHandlers();
71             dragDropToImageForm.waitForFilePickerToInitialise();
72         },
74         /**
75          * Waits for the file-pickers to be sufficiently ready before initialising the preview.
76          */
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);
82                 return;
83             }
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();
92             });
94             dragDropToImageForm.loadPreviewImage();
95         },
97         /**
98          * Loads the preview background image.
99          */
100         loadPreviewImage: function() {
101             $('fieldset#id_previewareaheader .dropbackground')
102                 .one('load', dragDropToImageForm.afterPreviewImageLoaded)
103                 .attr('src', dragDropToImageForm.fp.file('bgimage').href);
104         },
106         /**
107          * After the background image is loaded, continue setting up the preview.
108          */
109         afterPreviewImageLoaded: function() {
110             dragDropToImageForm.createDropZones();
111             M.util.js_complete('dragDropToImageForm');
112         },
114         /**
115          * Create, or recreate all the drop zones.
116          */
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.
124             }
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') {
130                     continue;
131                 }
132                 dragNo = dragNo - 1;
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) {
138                         continue;
139                     }
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>');
147                 }
148             }
150             dragDropToImageForm.waitForAllDropImagesToBeLoaded();
151         },
153         /**
154          * This polls until all the drop-zone images have loaded, and then calls updateDropZones().
155          */
156         waitForAllDropImagesToBeLoaded: function() {
157             var notYetLoadedImages = $('.dropzones img').not(function(i, imgNode) {
158                 return dragDropToImageForm.imageIsLoaded(imgNode);
159             });
161             if (notYetLoadedImages.length > 0) {
162                 setTimeout(function() {
163                     dragDropToImageForm.waitForAllDropImagesToBeLoaded();
164                 }, 100);
165                 return;
166             }
168             dragDropToImageForm.updateDropZones();
169         },
171         /**
172          * Check if an image has loaded without errors.
173          *
174          * @param {HTMLImageElement} imgElement an image.
175          * @returns {boolean} true if this image has loaded without errors.
176          */
177         imageIsLoaded: function(imgElement) {
178             return imgElement.complete && imgElement.naturalHeight !== 0;
179         },
181         /**
182          * Set the size and position of all the drop zones.
183          */
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.
188             }
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) {
197                     continue;
198                 }
199                 var dragNo = dragDropToImageForm.form.getFormValue('drops', [dropNo, 'choice']) - 1;
201                 drop.offset({
202                     left: dropBackgroundPosition.left +
203                             parseInt(dragDropToImageForm.form.getFormValue('drops', [dropNo, 'xleft'])),
204                     top: dropBackgroundPosition.top +
205                             parseInt(dragDropToImageForm.form.getFormValue('drops', [dropNo, 'ytop']))
206                 });
208                 var label = dragDropToImageForm.form.getFormValue('draglabel', [dragNo]);
209                 if (drop.is('img')) {
210                     drop.attr('alt', label);
211                 } else {
212                     drop.html(label);
213                 }
214             }
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);
221             }
222         },
224         /**
225          * In a given group, set all the drags and drops to be the same size.
226          *
227          * @param {int} group the group number.
228          */
229         resizeAllDragsAndDropsInGroup: function(group) {
230             var drops = $('.dropzones .droppreview.group' + group),
231                 maxWidth = 0,
232                 maxHeight = 0;
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));
238             });
240             // The size we will want to set is a bit bigger than this.
241             maxWidth += 10;
242             maxHeight += 10;
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.
249                 $(drop).css({
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'
254                 });
255             });
256         },
258         /**
259          * Events linked to form actions.
260          */
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();
268                     }
270                     dragDropToImageForm.setOptionsForDragItemSelectors();
272                     if (input.is('.dragitemtype, .draggroup')) {
273                         dragDropToImageForm.createDropZones();
274                     } else if (input.is('.draglabel')) {
275                         dragDropToImageForm.updateDropZones();
276                     }
277                 });
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();
284                 } else {
285                     dragDropToImageForm.updateDropZones();
286                 }
287             });
289             // Moving drop zones in the preview.
290             $('fieldset#id_previewareaheader').on('mousedown touchstart', '.droppreview', function(e) {
291                 dragDropToImageForm.dragStart(e);
292             });
294             $(window).on('resize', function() {
295                 dragDropToImageForm.updateDropZones();
296             });
297         },
299         /**
300          * Update all the drag item filepickers, so they are only shown for
301          */
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'])) {
307                     picker.show();
308                 } else {
309                     picker.hide();
310                 }
311             }
312         },
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;
328                 }
329             }
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)) {
339                         continue;
340                     }
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);
347                     }
348                 }
349             }
350         },
352         /**
353          * Checks if the specified drag option is already used somewhere.
354          *
355          * @param {Number} value of the drag item to check
356          * @return {Boolean} true if item is allocated to dropzone
357          */
358         isItemUsed: function(value) {
359             if (value === 0) {
360                 return false; // None option can always be selected.
361             }
363             if (dragDropToImageForm.form.getFormValue('drags', [value - 1, 'infinite'])) {
364                 return false; // Infinite, so can't be used up.
365             }
367             return $('fieldset#id_dropzoneheader select').filter(function(i, selectNode) {
368                 return parseInt($(selectNode).val()) === value;
369             }).length !== 0;
370         },
372         /**
373          * Handles when a dropzone in dragged in the preview.
374          * @param {Object} e Event object
375          */
376         dragStart: function(e) {
377             var drop = $(e.target).closest('.droppreview');
379             var info = dragDrop.prepare(e);
380             if (!info.start) {
381                 return;
382             }
384             dragDrop.start(e, drop, function(x, y, drop) {
385                 dragDropToImageForm.dragMove(drop);
386             }, function() {
387                 dragDropToImageForm.dragEnd();
388             });
389         },
391         /**
392          * Handles update while a drop is being dragged.
393          *
394          * @param {jQuery} drop the drop preview being moved.
395          */
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())));
408             // Update the form.
409             dragDropToImageForm.form.setFormValue('drops', [dropNo, 'xleft'], left);
410             dragDropToImageForm.form.setFormValue('drops', [dropNo, 'ytop'], top);
411         },
413         /**
414          * Handles when the drag ends.
415          */
416         dragEnd: function() {
417             // Redraw, in case the position was constrained.
418             dragDropToImageForm.updateDropZones();
419         },
421         /**
422          * Low level operations on form.
423          */
424         form: {
425             toNameWithIndex: function(name, indexes) {
426                 var indexString = name;
427                 for (var i = 0; i < indexes.length; i++) {
428                     indexString = indexString + '[' + indexes[i] + ']';
429                 }
430                 return indexString;
431             },
433             getEl: function(name, indexes) {
434                 var form = $('form.mform[data-qtype="ddimageortext"]')[0];
435                 return form.elements[this.toNameWithIndex(name, indexes)];
436             },
438             /**
439              * Helper to get the value of a form elements with name like "drops[0][xleft]".
440              *
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.
444              */
445             getFormValue: function(name, indexes) {
446                 var el = this.getEl(name, indexes);
447                 if (!el.type) {
448                     el = el[el.length - 1];
449                 }
450                 if (el.type === 'checkbox') {
451                     return el.checked;
452                 } else {
453                     return el.value;
454                 }
455             },
457             /**
458              * Helper to get the value of a form elements with name like "drops[0][xleft]".
459              *
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.
463              */
464             setFormValue: function(name, indexes, value) {
465                 var el = this.getEl(name, indexes);
466                 if (el.type === 'checkbox') {
467                     el.checked = value;
468                 } else {
469                     el.value = value;
470                 }
471             }
472         },
474         /**
475          * Utility to get the file name and url from the filepicker.
476          * @returns {Object} object containing functions {file, name}
477          */
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;
489                 });
490             }
492             return {
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};
498                     } else {
499                         return {href: null, name: null};
500                     }
501                 },
503                 name: function(draftitemid) {
504                     return draftItemIdsToName[draftitemid];
505                 }
506             };
507         }
508     };
510     return {
511         init: dragDropToImageForm.init
512     };
513 });