Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 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/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) {
24
 
25
    "use strict";
26
 
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,
38
 
39
        /**
40
         * @var {Object} maxDragImageSize with properties width and height.
41
         * @private
42
         */
43
        maxDragImageSize: null,
44
 
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.
50
 
51
        /**
52
         * Initialise the form javascript features.
53
         *
54
         * @method
55
         */
56
        init: function() {
57
            dragDropToImageForm.fp = dragDropToImageForm.filePickers();
58
            dragDropToImageForm.updateVisibilityOfFilePickers();
59
            dragDropToImageForm.setOptionsForDragItemSelectors();
60
            dragDropToImageForm.setupEventHandlers();
61
            dragDropToImageForm.waitForFilePickerToInitialise();
62
        },
63
 
64
        /**
65
         * Add html for the preview area.
66
         */
67
        setupPreviewArea: function() {
68
            $('#id_previewareaheader').append(
69
                '<div class="ddarea que ddimageortext">' +
70
                '  <div id="id_droparea" class="droparea">' +
71
                '    <img class="dropbackground" />' +
72
                '    <div class="dropzones"></div>' +
73
                '  </div>' +
74
                '  <div class="dragitems"></div>' +
75
                '</div>');
76
        },
77
 
78
        /**
79
         * Waits for the file-pickers to be sufficiently ready before initialising the preview.
80
         */
81
        waitForFilePickerToInitialise: function() {
82
            if (dragDropToImageForm.fp.file('bgimage').href === null) {
83
                // It would be better to use an onload or onchange event rather than this timeout.
84
                // Unfortunately attempts to do this early are overwritten by filepicker during its loading.
85
                setTimeout(dragDropToImageForm.waitForFilePickerToInitialise, 1000);
86
                return;
87
            }
88
            M.util.js_pending('dragDropToImageForm');
89
 
90
            // From now on, when a new file gets loaded into the filepicker, update the preview.
91
            // This is not in the setupEventHandlers section as it needs to be delayed until
92
            // after filepicker's javascript has finished.
93
            $('form.mform[data-qtype="ddimageortext"]').on('change', '.filepickerhidden', function() {
94
                M.util.js_pending('dragDropToImageForm');
95
                dragDropToImageForm.loadPreviewImage();
96
            });
97
            if ($('#id_droparea').length) {
98
                dragDropToImageForm.loadPreviewImage();
99
            } else {
100
                // Setup preview area when the background image is uploaded the first time.
101
                dragDropToImageForm.setupPreviewArea();
102
                dragDropToImageForm.loadPreviewImage();
103
            }
104
        },
105
 
106
        /**
107
         * Loads the preview background image.
108
         */
109
        loadPreviewImage: function() {
110
            $('fieldset#id_previewareaheader .dropbackground')
111
                .one('load', dragDropToImageForm.afterPreviewImageLoaded)
112
                .attr('src', dragDropToImageForm.fp.file('bgimage').href);
113
        },
114
 
115
        /**
116
         * After the background image is loaded, continue setting up the preview.
117
         */
118
        afterPreviewImageLoaded: function() {
119
            dragDropToImageForm.createDropZones();
120
            M.util.js_complete('dragDropToImageForm');
121
        },
122
 
123
        /**
124
         * Create, or recreate all the drop zones.
125
         */
126
        createDropZones: function() {
127
            var dropZoneHolder = $('.dropzones');
128
            dropZoneHolder.empty();
129
 
130
            var bgimageurl = dragDropToImageForm.fp.file('bgimage').href;
131
            if (bgimageurl === null) {
132
                return; // There is not currently a valid preview to update.
133
            }
134
 
135
            var numDrops = dragDropToImageForm.form.getFormValue('nodropzone', []);
136
            for (var dropNo = 0; dropNo < numDrops; dropNo++) {
137
                var dragNo = dragDropToImageForm.form.getFormValue('drops', [dropNo, 'choice']);
138
                if (dragNo === '0') {
139
                    continue;
140
                }
141
                dragNo = dragNo - 1;
142
                var group = dragDropToImageForm.form.getFormValue('drags', [dragNo, 'draggroup']),
143
                    label = dragDropToImageForm.form.getFormValue('draglabel', [dragNo]);
144
                if ('image' === dragDropToImageForm.form.getFormValue('drags', [dragNo, 'dragitemtype'])) {
145
                    var imgUrl = dragDropToImageForm.fp.file('dragitem[' + dragNo + ']').href;
146
                    if (imgUrl === null) {
147
                        continue;
148
                    }
149
                    // Althoug these are previews of drops, we also add the class name 'drag',
150
                    dropZoneHolder.append('<img class="droppreview group' + group + ' drop' + dropNo +
151
                            '" src="' + imgUrl + '" alt="' + label + '" data-drop-no="' + dropNo + '">');
152
 
153
                } else if (label !== '') {
154
                    dropZoneHolder.append('<div class="droppreview group' + group + ' drop' + dropNo +
155
                        '"  data-drop-no="' + dropNo + '">' + label + '</div>');
156
                }
157
            }
158
 
159
            dragDropToImageForm.waitForAllDropImagesToBeLoaded();
160
        },
161
 
162
        /**
163
         * This polls until all the drop-zone images have loaded, and then calls updateDropZones().
164
         */
165
        waitForAllDropImagesToBeLoaded: function() {
166
            var notYetLoadedImages = $('.dropzones img').not(function(i, imgNode) {
167
                return dragDropToImageForm.imageIsLoaded(imgNode);
168
            });
169
 
170
            if (notYetLoadedImages.length > 0) {
171
                setTimeout(function() {
172
                    dragDropToImageForm.waitForAllDropImagesToBeLoaded();
173
                }, 100);
174
                return;
175
            }
176
 
177
            dragDropToImageForm.updateDropZones();
178
        },
179
 
180
        /**
181
         * Check if an image has loaded without errors.
182
         *
183
         * @param {HTMLImageElement} imgElement an image.
184
         * @returns {boolean} true if this image has loaded without errors.
185
         */
186
        imageIsLoaded: function(imgElement) {
187
            return imgElement.complete && imgElement.naturalHeight !== 0;
188
        },
189
 
190
        /**
191
         * Set the size and position of all the drop zones.
192
         */
193
        updateDropZones: function() {
194
            var bgimageurl = dragDropToImageForm.fp.file('bgimage').href;
195
            if (bgimageurl === null) {
196
                return; // There is not currently a valid preview to update.
197
            }
198
 
199
            var dropBackgroundPosition = $('fieldset#id_previewareaheader .dropbackground').offset(),
200
                numDrops = dragDropToImageForm.form.getFormValue('nodropzone', []);
201
 
202
            // Move each drop to the right position and update the text.
203
            for (var dropNo = 0; dropNo < numDrops; dropNo++) {
204
                var drop = $('.dropzones .drop' + dropNo);
205
                if (drop.length === 0) {
206
                    continue;
207
                }
208
                var dragNo = dragDropToImageForm.form.getFormValue('drops', [dropNo, 'choice']) - 1;
209
 
210
                drop.offset({
211
                    left: dropBackgroundPosition.left +
212
                            parseInt(dragDropToImageForm.form.getFormValue('drops', [dropNo, 'xleft'])),
213
                    top: dropBackgroundPosition.top +
214
                            parseInt(dragDropToImageForm.form.getFormValue('drops', [dropNo, 'ytop']))
215
                });
216
 
217
                var label = dragDropToImageForm.form.getFormValue('draglabel', [dragNo]);
218
                if (drop.is('img')) {
219
                    drop.attr('alt', label);
220
                } else {
221
                    drop.html(label);
222
                }
223
            }
224
 
225
            // Resize them to the same size.
226
            $('.dropzones .droppreview').css('padding', '0');
227
            var numGroups = $('.draggroup select').first().find('option').length;
228
            for (var group = 1; group <= numGroups; group++) {
229
                dragDropToImageForm.resizeAllDragsAndDropsInGroup(group);
230
            }
231
        },
232
 
233
        /**
234
         * In a given group, set all the drags and drops to be the same size.
235
         *
236
         * @param {int} group the group number.
237
         */
238
        resizeAllDragsAndDropsInGroup: function(group) {
239
            var drops = $('.dropzones .droppreview.group' + group),
240
                maxWidth = 0,
241
                maxHeight = 0;
242
 
243
            // Find the maximum size of any drag in this groups.
244
            drops.each(function(i, drop) {
245
                maxWidth = Math.max(maxWidth, Math.ceil(drop.offsetWidth));
246
                maxHeight = Math.max(maxHeight, Math.ceil(drop.offsetHeight));
247
            });
248
 
249
            // The size we will want to set is a bit bigger than this.
250
            maxWidth += 10;
251
            maxHeight += 10;
252
 
253
            // Set each drag home to that size.
254
            drops.each(function(i, drop) {
255
                var left = Math.round((maxWidth - drop.offsetWidth) / 2),
256
                    top = Math.floor((maxHeight - drop.offsetHeight) / 2);
257
                // Set top and left padding so the item is centred.
258
                $(drop).css({
259
                    'padding-left': left + 'px',
260
                    'padding-right': (maxWidth - drop.offsetWidth - left) + 'px',
261
                    'padding-top': top + 'px',
262
                    'padding-bottom': (maxHeight - drop.offsetHeight - top) + 'px'
263
                });
264
            });
265
        },
266
 
267
        /**
268
         * Events linked to form actions.
269
         */
270
        setupEventHandlers: function() {
271
            // Changes to settings in the draggable items section.
272
            $('fieldset#id_draggableitemheader')
273
                .on('change input', 'input, select', function(e) {
274
                    var input = $(e.target).closest('select, input');
275
                    if (input.hasClass('dragitemtype')) {
276
                        dragDropToImageForm.updateVisibilityOfFilePickers();
277
                    }
278
 
279
                    dragDropToImageForm.setOptionsForDragItemSelectors();
280
 
281
                    if (input.is('.dragitemtype, .draggroup')) {
282
                        dragDropToImageForm.createDropZones();
283
                    } else if (input.is('.draglabel')) {
284
                        dragDropToImageForm.updateDropZones();
285
                    }
286
                });
287
 
288
            // Changes to Drop zones section: left, top and drag item.
289
            $('fieldset#id_dropzoneheader').on('change input', 'input, select', function(e) {
290
                var input = $(e.target).closest('select, input');
291
                if (input.is('select')) {
292
                    dragDropToImageForm.createDropZones();
293
                } else {
294
                    dragDropToImageForm.updateDropZones();
295
                }
296
            });
297
 
298
            // Moving drop zones in the preview.
299
            $('fieldset#id_previewareaheader').on('mousedown touchstart', '.droppreview', function(e) {
300
                dragDropToImageForm.dragStart(e);
301
            });
302
 
303
            $(window).on('resize', function() {
304
                dragDropToImageForm.updateDropZones();
305
            });
306
        },
307
 
308
        /**
309
         * Update all the drag item filepickers, so they are only shown for
310
         */
311
        updateVisibilityOfFilePickers: function() {
312
            var numDrags = dragDropToImageForm.form.getFormValue('noitems', []);
313
            for (var dragNo = 0; dragNo < numDrags; dragNo++) {
314
                var picker = $('input#id_dragitem_' + dragNo).closest('.fitem_ffilepicker');
315
                if ('image' === dragDropToImageForm.form.getFormValue('drags', [dragNo, 'dragitemtype'])) {
316
                    picker.show();
317
                } else {
318
                    picker.hide();
319
                }
320
            }
321
        },
322
 
323
 
324
        setOptionsForDragItemSelectors: function() {
325
            var dragItemOptions = {'0': ''},
326
                numDrags = dragDropToImageForm.form.getFormValue('noitems', []),
327
                numDrops = dragDropToImageForm.form.getFormValue('nodropzone', []);
328
 
329
            // Work out the list of options.
330
            for (var dragNo = 0; dragNo < numDrags; dragNo++) {
331
                var label = dragDropToImageForm.form.getFormValue('draglabel', [dragNo]);
332
                var file = dragDropToImageForm.fp.file(dragDropToImageForm.form.toNameWithIndex('dragitem', [dragNo]));
333
                if ('image' === dragDropToImageForm.form.getFormValue('drags', [dragNo, 'dragitemtype']) && file.name !== null) {
334
                    dragItemOptions[dragNo + 1] = (dragNo + 1) + '. ' + label + ' (' + file.name + ')';
335
                } else if (label !== '') {
336
                    dragItemOptions[dragNo + 1] = (dragNo + 1) + '. ' + label;
337
                }
338
            }
339
 
340
            // Initialise each select.
341
            for (var dropNo = 0; dropNo < numDrops; dropNo++) {
342
                var selector = $('#id_drops_' + dropNo + '_choice');
343
 
344
                var selectedvalue = selector.val();
345
                selector.find('option').remove();
346
                for (var value in dragItemOptions) {
347
                    if (!dragItemOptions.hasOwnProperty(value)) {
348
                        continue;
349
                    }
350
                    selector.append('<option value="' + value + '">' + dragItemOptions[value] + '</option>');
351
                    var optionnode = selector.find('option[value="' + value + '"]');
352
                    if (parseInt(value) === parseInt(selectedvalue)) {
353
                        optionnode.attr('selected', true);
354
                    } else if (dragDropToImageForm.isItemUsed(parseInt(value))) {
355
                        optionnode.attr('disabled', true);
356
                    }
357
                }
358
            }
359
        },
360
 
361
        /**
362
         * Checks if the specified drag option is already used somewhere.
363
         *
364
         * @param {Number} value of the drag item to check
365
         * @return {Boolean} true if item is allocated to dropzone
366
         */
367
        isItemUsed: function(value) {
368
            if (value === 0) {
369
                return false; // None option can always be selected.
370
            }
371
 
372
            if (dragDropToImageForm.form.getFormValue('drags', [value - 1, 'infinite'])) {
373
                return false; // Infinite, so can't be used up.
374
            }
375
 
376
            return $('fieldset#id_dropzoneheader select').filter(function(i, selectNode) {
377
                return parseInt($(selectNode).val()) === value;
378
            }).length !== 0;
379
        },
380
 
381
        /**
382
         * Handles when a dropzone in dragged in the preview.
383
         * @param {Object} e Event object
384
         */
385
        dragStart: function(e) {
386
            var drop = $(e.target).closest('.droppreview');
387
 
388
            var info = dragDrop.prepare(e);
389
            if (!info.start) {
390
                return;
391
            }
392
 
393
            dragDrop.start(e, drop, function(x, y, drop) {
394
                dragDropToImageForm.dragMove(drop);
395
            }, function() {
396
                dragDropToImageForm.dragEnd();
397
            });
398
        },
399
 
400
        /**
401
         * Handles update while a drop is being dragged.
402
         *
403
         * @param {jQuery} drop the drop preview being moved.
404
         */
405
        dragMove: function(drop) {
406
            var backgroundImage = $('fieldset#id_previewareaheader .dropbackground'),
407
                backgroundPosition = backgroundImage.offset(),
408
                dropNo = drop.data('dropNo'),
409
                dropPosition = drop.offset(),
410
                left = Math.round(dropPosition.left - backgroundPosition.left),
411
                top = Math.round(dropPosition.top - backgroundPosition.top);
412
 
413
            // Constrain coordinates to be inside the background.
414
            left = Math.round(Math.max(0, Math.min(left, backgroundImage.outerWidth() - drop.outerWidth())));
415
            top = Math.round(Math.max(0, Math.min(top, backgroundImage.outerHeight() - drop.outerHeight())));
416
 
417
            // Update the form.
418
            dragDropToImageForm.form.setFormValue('drops', [dropNo, 'xleft'], left);
419
            dragDropToImageForm.form.setFormValue('drops', [dropNo, 'ytop'], top);
420
        },
421
 
422
        /**
423
         * Handles when the drag ends.
424
         */
425
        dragEnd: function() {
426
            // Redraw, in case the position was constrained.
427
            dragDropToImageForm.updateDropZones();
428
        },
429
 
430
        /**
431
         * Low level operations on form.
432
         */
433
        form: {
434
            toNameWithIndex: function(name, indexes) {
435
                var indexString = name;
436
                for (var i = 0; i < indexes.length; i++) {
437
                    indexString = indexString + '[' + indexes[i] + ']';
438
                }
439
                return indexString;
440
            },
441
 
442
            getEl: function(name, indexes) {
443
                var form = $('form.mform[data-qtype="ddimageortext"]')[0];
444
                return form.elements[this.toNameWithIndex(name, indexes)];
445
            },
446
 
447
            /**
448
             * Helper to get the value of a form elements with name like "drops[0][xleft]".
449
             *
450
             * @param {String} name the base name, e.g. 'drops'.
451
             * @param {String[]} indexes the indexes, e.g. ['0', 'xleft'].
452
             * @return {String} the value of that field.
453
             */
454
            getFormValue: function(name, indexes) {
455
                var el = this.getEl(name, indexes);
456
                if (!el.type) {
457
                    el = el[el.length - 1];
458
                }
459
                if (el.type === 'checkbox') {
460
                    return el.checked;
461
                } else {
462
                    return el.value;
463
                }
464
            },
465
 
466
            /**
467
             * Helper to get the value of a form elements with name like "drops[0][xleft]".
468
             *
469
             * @param {String} name the base name, e.g. 'drops'.
470
             * @param {String[]} indexes the indexes, e.g. ['0', 'xleft'].
471
             * @param {String|Number} value the value to set.
472
             */
473
            setFormValue: function(name, indexes, value) {
474
                var el = this.getEl(name, indexes);
475
                if (el.type === 'checkbox') {
476
                    el.checked = value;
477
                } else {
478
                    el.value = value;
479
                }
480
            }
481
        },
482
 
483
        /**
484
         * Utility to get the file name and url from the filepicker.
485
         * @returns {Object} object containing functions {file, name}
486
         */
487
        filePickers: function() {
488
            var draftItemIdsToName;
489
            var nameToParentNode;
490
 
491
            if (draftItemIdsToName === undefined) {
492
                draftItemIdsToName = {};
493
                nameToParentNode = {};
494
                var fp = $('form.mform[data-qtype="ddimageortext"] input.filepickerhidden');
495
                fp.each(function(index, filepicker) {
496
                    draftItemIdsToName[filepicker.value] = filepicker.name;
497
                    nameToParentNode[filepicker.name] = filepicker.parentNode;
498
                });
499
            }
500
 
501
            return {
502
                file: function(name) {
503
                    var parentNode = $(nameToParentNode[name]);
504
                    var fileAnchor = parentNode.find('div.filepicker-filelist a');
505
                    if (fileAnchor.length) {
506
                        return {href: fileAnchor.get(0).href, name: fileAnchor.get(0).innerHTML};
507
                    } else {
508
                        return {href: null, name: null};
509
                    }
510
                },
511
 
512
                name: function(draftitemid) {
513
                    return draftItemIdsToName[draftitemid];
514
                }
515
            };
516
        }
517
    };
518
 
519
    return {
520
        init: dragDropToImageForm.init
521
    };
522
});