Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | 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', []);
1441 ariadna 136
            var dropzonevisibility = dragDropToImageForm.form.getFormValue('dropzonevisibility', []);
137
            var dropzonevisibilitystyle = dropzonevisibility === '1' ? 'background: transparent;' : '';
1 efrain 138
            for (var dropNo = 0; dropNo < numDrops; dropNo++) {
139
                var dragNo = dragDropToImageForm.form.getFormValue('drops', [dropNo, 'choice']);
140
                if (dragNo === '0') {
141
                    continue;
142
                }
143
                dragNo = dragNo - 1;
144
                var group = dragDropToImageForm.form.getFormValue('drags', [dragNo, 'draggroup']),
145
                    label = dragDropToImageForm.form.getFormValue('draglabel', [dragNo]);
146
                if ('image' === dragDropToImageForm.form.getFormValue('drags', [dragNo, 'dragitemtype'])) {
147
                    var imgUrl = dragDropToImageForm.fp.file('dragitem[' + dragNo + ']').href;
148
                    if (imgUrl === null) {
149
                        continue;
150
                    }
151
                    // Althoug these are previews of drops, we also add the class name 'drag',
152
                    dropZoneHolder.append('<img class="droppreview group' + group + ' drop' + dropNo +
1441 ariadna 153
                        '" src="' + imgUrl + '" alt="' + label + '" data-drop-no="' + dropNo +
154
                        '" style="' + dropzonevisibilitystyle + '" >');
1 efrain 155
 
156
                } else if (label !== '') {
157
                    dropZoneHolder.append('<div class="droppreview group' + group + ' drop' + dropNo +
158
                        '"  data-drop-no="' + dropNo + '">' + label + '</div>');
159
                }
160
            }
161
 
162
            dragDropToImageForm.waitForAllDropImagesToBeLoaded();
163
        },
164
 
165
        /**
166
         * This polls until all the drop-zone images have loaded, and then calls updateDropZones().
167
         */
168
        waitForAllDropImagesToBeLoaded: function() {
169
            var notYetLoadedImages = $('.dropzones img').not(function(i, imgNode) {
170
                return dragDropToImageForm.imageIsLoaded(imgNode);
171
            });
172
 
173
            if (notYetLoadedImages.length > 0) {
174
                setTimeout(function() {
175
                    dragDropToImageForm.waitForAllDropImagesToBeLoaded();
176
                }, 100);
177
                return;
178
            }
179
 
180
            dragDropToImageForm.updateDropZones();
181
        },
182
 
183
        /**
184
         * Check if an image has loaded without errors.
185
         *
186
         * @param {HTMLImageElement} imgElement an image.
187
         * @returns {boolean} true if this image has loaded without errors.
188
         */
189
        imageIsLoaded: function(imgElement) {
190
            return imgElement.complete && imgElement.naturalHeight !== 0;
191
        },
192
 
193
        /**
194
         * Set the size and position of all the drop zones.
195
         */
196
        updateDropZones: function() {
197
            var bgimageurl = dragDropToImageForm.fp.file('bgimage').href;
198
            if (bgimageurl === null) {
199
                return; // There is not currently a valid preview to update.
200
            }
201
 
202
            var dropBackgroundPosition = $('fieldset#id_previewareaheader .dropbackground').offset(),
203
                numDrops = dragDropToImageForm.form.getFormValue('nodropzone', []);
204
 
205
            // Move each drop to the right position and update the text.
206
            for (var dropNo = 0; dropNo < numDrops; dropNo++) {
207
                var drop = $('.dropzones .drop' + dropNo);
208
                if (drop.length === 0) {
209
                    continue;
210
                }
211
                var dragNo = dragDropToImageForm.form.getFormValue('drops', [dropNo, 'choice']) - 1;
212
 
213
                drop.offset({
214
                    left: dropBackgroundPosition.left +
215
                            parseInt(dragDropToImageForm.form.getFormValue('drops', [dropNo, 'xleft'])),
216
                    top: dropBackgroundPosition.top +
217
                            parseInt(dragDropToImageForm.form.getFormValue('drops', [dropNo, 'ytop']))
218
                });
219
 
220
                var label = dragDropToImageForm.form.getFormValue('draglabel', [dragNo]);
221
                if (drop.is('img')) {
222
                    drop.attr('alt', label);
223
                } else {
224
                    drop.html(label);
225
                }
226
            }
227
 
228
            // Resize them to the same size.
229
            $('.dropzones .droppreview').css('padding', '0');
230
            var numGroups = $('.draggroup select').first().find('option').length;
231
            for (var group = 1; group <= numGroups; group++) {
232
                dragDropToImageForm.resizeAllDragsAndDropsInGroup(group);
233
            }
234
        },
235
 
236
        /**
237
         * In a given group, set all the drags and drops to be the same size.
238
         *
239
         * @param {int} group the group number.
240
         */
241
        resizeAllDragsAndDropsInGroup: function(group) {
242
            var drops = $('.dropzones .droppreview.group' + group),
243
                maxWidth = 0,
244
                maxHeight = 0;
245
 
246
            // Find the maximum size of any drag in this groups.
247
            drops.each(function(i, drop) {
248
                maxWidth = Math.max(maxWidth, Math.ceil(drop.offsetWidth));
249
                maxHeight = Math.max(maxHeight, Math.ceil(drop.offsetHeight));
250
            });
251
 
252
            // The size we will want to set is a bit bigger than this.
253
            maxWidth += 10;
254
            maxHeight += 10;
255
 
256
            // Set each drag home to that size.
257
            drops.each(function(i, drop) {
258
                var left = Math.round((maxWidth - drop.offsetWidth) / 2),
259
                    top = Math.floor((maxHeight - drop.offsetHeight) / 2);
260
                // Set top and left padding so the item is centred.
261
                $(drop).css({
262
                    'padding-left': left + 'px',
263
                    'padding-right': (maxWidth - drop.offsetWidth - left) + 'px',
264
                    'padding-top': top + 'px',
265
                    'padding-bottom': (maxHeight - drop.offsetHeight - top) + 'px'
266
                });
267
            });
268
        },
269
 
270
        /**
271
         * Events linked to form actions.
272
         */
273
        setupEventHandlers: function() {
274
            // Changes to settings in the draggable items section.
275
            $('fieldset#id_draggableitemheader')
276
                .on('change input', 'input, select', function(e) {
277
                    var input = $(e.target).closest('select, input');
278
                    if (input.hasClass('dragitemtype')) {
279
                        dragDropToImageForm.updateVisibilityOfFilePickers();
280
                    }
281
 
282
                    dragDropToImageForm.setOptionsForDragItemSelectors();
283
 
284
                    if (input.is('.dragitemtype, .draggroup')) {
285
                        dragDropToImageForm.createDropZones();
286
                    } else if (input.is('.draglabel')) {
287
                        dragDropToImageForm.updateDropZones();
288
                    }
289
                });
290
 
291
            // Changes to Drop zones section: left, top and drag item.
292
            $('fieldset#id_dropzoneheader').on('change input', 'input, select', function(e) {
293
                var input = $(e.target).closest('select, input');
1441 ariadna 294
                if (input.attr('id') === 'id_dropzonevisibility') {
295
                    return;
296
                }
297
 
1 efrain 298
                if (input.is('select')) {
299
                    dragDropToImageForm.createDropZones();
300
                } else {
301
                    dragDropToImageForm.updateDropZones();
302
                }
303
            });
304
 
305
            // Moving drop zones in the preview.
306
            $('fieldset#id_previewareaheader').on('mousedown touchstart', '.droppreview', function(e) {
307
                dragDropToImageForm.dragStart(e);
308
            });
309
 
310
            $(window).on('resize', function() {
311
                dragDropToImageForm.updateDropZones();
312
            });
1441 ariadna 313
 
314
            $('#id_dropzonevisibility').on('change', function() {
315
                let selectedvalue = $(this).val();
316
                if (selectedvalue === "1") {
317
                    $('.droppreview').css('background', 'transparent');
318
                } else if (selectedvalue === "0") {
319
                    $('.droppreview').css('background', '');
320
                }
321
            });
1 efrain 322
        },
323
 
324
        /**
325
         * Update all the drag item filepickers, so they are only shown for
326
         */
327
        updateVisibilityOfFilePickers: function() {
328
            var numDrags = dragDropToImageForm.form.getFormValue('noitems', []);
329
            for (var dragNo = 0; dragNo < numDrags; dragNo++) {
330
                var picker = $('input#id_dragitem_' + dragNo).closest('.fitem_ffilepicker');
331
                if ('image' === dragDropToImageForm.form.getFormValue('drags', [dragNo, 'dragitemtype'])) {
332
                    picker.show();
333
                } else {
334
                    picker.hide();
335
                }
336
            }
337
        },
338
 
339
 
340
        setOptionsForDragItemSelectors: function() {
341
            var dragItemOptions = {'0': ''},
342
                numDrags = dragDropToImageForm.form.getFormValue('noitems', []),
343
                numDrops = dragDropToImageForm.form.getFormValue('nodropzone', []);
344
 
345
            // Work out the list of options.
346
            for (var dragNo = 0; dragNo < numDrags; dragNo++) {
347
                var label = dragDropToImageForm.form.getFormValue('draglabel', [dragNo]);
348
                var file = dragDropToImageForm.fp.file(dragDropToImageForm.form.toNameWithIndex('dragitem', [dragNo]));
349
                if ('image' === dragDropToImageForm.form.getFormValue('drags', [dragNo, 'dragitemtype']) && file.name !== null) {
350
                    dragItemOptions[dragNo + 1] = (dragNo + 1) + '. ' + label + ' (' + file.name + ')';
351
                } else if (label !== '') {
352
                    dragItemOptions[dragNo + 1] = (dragNo + 1) + '. ' + label;
353
                }
354
            }
355
 
356
            // Initialise each select.
357
            for (var dropNo = 0; dropNo < numDrops; dropNo++) {
358
                var selector = $('#id_drops_' + dropNo + '_choice');
359
 
360
                var selectedvalue = selector.val();
361
                selector.find('option').remove();
362
                for (var value in dragItemOptions) {
363
                    if (!dragItemOptions.hasOwnProperty(value)) {
364
                        continue;
365
                    }
366
                    selector.append('<option value="' + value + '">' + dragItemOptions[value] + '</option>');
367
                    var optionnode = selector.find('option[value="' + value + '"]');
368
                    if (parseInt(value) === parseInt(selectedvalue)) {
369
                        optionnode.attr('selected', true);
370
                    } else if (dragDropToImageForm.isItemUsed(parseInt(value))) {
371
                        optionnode.attr('disabled', true);
372
                    }
373
                }
374
            }
375
        },
376
 
377
        /**
378
         * Checks if the specified drag option is already used somewhere.
379
         *
380
         * @param {Number} value of the drag item to check
381
         * @return {Boolean} true if item is allocated to dropzone
382
         */
383
        isItemUsed: function(value) {
384
            if (value === 0) {
385
                return false; // None option can always be selected.
386
            }
387
 
388
            if (dragDropToImageForm.form.getFormValue('drags', [value - 1, 'infinite'])) {
389
                return false; // Infinite, so can't be used up.
390
            }
391
 
1441 ariadna 392
            return $('fieldset#id_dropzoneheader select[name^="drops"]').filter(function(i, selectNode) {
1 efrain 393
                return parseInt($(selectNode).val()) === value;
394
            }).length !== 0;
395
        },
396
 
397
        /**
398
         * Handles when a dropzone in dragged in the preview.
399
         * @param {Object} e Event object
400
         */
401
        dragStart: function(e) {
402
            var drop = $(e.target).closest('.droppreview');
403
 
404
            var info = dragDrop.prepare(e);
405
            if (!info.start) {
406
                return;
407
            }
408
 
409
            dragDrop.start(e, drop, function(x, y, drop) {
410
                dragDropToImageForm.dragMove(drop);
411
            }, function() {
412
                dragDropToImageForm.dragEnd();
413
            });
414
        },
415
 
416
        /**
417
         * Handles update while a drop is being dragged.
418
         *
419
         * @param {jQuery} drop the drop preview being moved.
420
         */
421
        dragMove: function(drop) {
422
            var backgroundImage = $('fieldset#id_previewareaheader .dropbackground'),
423
                backgroundPosition = backgroundImage.offset(),
424
                dropNo = drop.data('dropNo'),
425
                dropPosition = drop.offset(),
426
                left = Math.round(dropPosition.left - backgroundPosition.left),
427
                top = Math.round(dropPosition.top - backgroundPosition.top);
428
 
429
            // Constrain coordinates to be inside the background.
430
            left = Math.round(Math.max(0, Math.min(left, backgroundImage.outerWidth() - drop.outerWidth())));
431
            top = Math.round(Math.max(0, Math.min(top, backgroundImage.outerHeight() - drop.outerHeight())));
432
 
433
            // Update the form.
434
            dragDropToImageForm.form.setFormValue('drops', [dropNo, 'xleft'], left);
435
            dragDropToImageForm.form.setFormValue('drops', [dropNo, 'ytop'], top);
436
        },
437
 
438
        /**
439
         * Handles when the drag ends.
440
         */
441
        dragEnd: function() {
442
            // Redraw, in case the position was constrained.
443
            dragDropToImageForm.updateDropZones();
444
        },
445
 
446
        /**
447
         * Low level operations on form.
448
         */
449
        form: {
450
            toNameWithIndex: function(name, indexes) {
451
                var indexString = name;
452
                for (var i = 0; i < indexes.length; i++) {
453
                    indexString = indexString + '[' + indexes[i] + ']';
454
                }
455
                return indexString;
456
            },
457
 
458
            getEl: function(name, indexes) {
459
                var form = $('form.mform[data-qtype="ddimageortext"]')[0];
460
                return form.elements[this.toNameWithIndex(name, indexes)];
461
            },
462
 
463
            /**
464
             * Helper to get the value of a form elements with name like "drops[0][xleft]".
465
             *
466
             * @param {String} name the base name, e.g. 'drops'.
467
             * @param {String[]} indexes the indexes, e.g. ['0', 'xleft'].
468
             * @return {String} the value of that field.
469
             */
470
            getFormValue: function(name, indexes) {
471
                var el = this.getEl(name, indexes);
472
                if (!el.type) {
473
                    el = el[el.length - 1];
474
                }
475
                if (el.type === 'checkbox') {
476
                    return el.checked;
477
                } else {
478
                    return el.value;
479
                }
480
            },
481
 
482
            /**
483
             * Helper to get the value of a form elements with name like "drops[0][xleft]".
484
             *
485
             * @param {String} name the base name, e.g. 'drops'.
486
             * @param {String[]} indexes the indexes, e.g. ['0', 'xleft'].
487
             * @param {String|Number} value the value to set.
488
             */
489
            setFormValue: function(name, indexes, value) {
490
                var el = this.getEl(name, indexes);
491
                if (el.type === 'checkbox') {
492
                    el.checked = value;
493
                } else {
494
                    el.value = value;
495
                }
496
            }
497
        },
498
 
499
        /**
500
         * Utility to get the file name and url from the filepicker.
501
         * @returns {Object} object containing functions {file, name}
502
         */
503
        filePickers: function() {
504
            var draftItemIdsToName;
505
            var nameToParentNode;
506
 
507
            if (draftItemIdsToName === undefined) {
508
                draftItemIdsToName = {};
509
                nameToParentNode = {};
510
                var fp = $('form.mform[data-qtype="ddimageortext"] input.filepickerhidden');
511
                fp.each(function(index, filepicker) {
512
                    draftItemIdsToName[filepicker.value] = filepicker.name;
513
                    nameToParentNode[filepicker.name] = filepicker.parentNode;
514
                });
515
            }
516
 
517
            return {
518
                file: function(name) {
519
                    var parentNode = $(nameToParentNode[name]);
520
                    var fileAnchor = parentNode.find('div.filepicker-filelist a');
521
                    if (fileAnchor.length) {
522
                        return {href: fileAnchor.get(0).href, name: fileAnchor.get(0).innerHTML};
523
                    } else {
524
                        return {href: null, name: null};
525
                    }
526
                },
527
 
528
                name: function(draftitemid) {
529
                    return draftItemIdsToName[draftitemid];
530
                }
531
            };
532
        }
533
    };
534
 
535
    return {
536
        init: dragDropToImageForm.init
537
    };
538
});