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
 * This module provides a wrapper to encapsulate a lot of the common combinations of
18
 * user interaction we use in Moodle.
19
 *
20
 * @module     core/custom_interaction_events
21
 * @copyright  2016 Ryan Wyllie <ryan@moodle.com>
22
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23
 * @since      3.2
24
 */
25
define(['jquery', 'core/key_codes'], function($, keyCodes) {
26
    // The list of events provided by this module. Namespaced to avoid clashes.
27
    var events = {
28
        activate: 'cie:activate',
29
        keyboardActivate: 'cie:keyboardactivate',
30
        escape: 'cie:escape',
31
        down: 'cie:down',
32
        up: 'cie:up',
33
        home: 'cie:home',
34
        end: 'cie:end',
35
        next: 'cie:next',
36
        previous: 'cie:previous',
37
        asterix: 'cie:asterix',
38
        scrollLock: 'cie:scrollLock',
39
        scrollTop: 'cie:scrollTop',
40
        scrollBottom: 'cie:scrollBottom',
41
        ctrlPageUp: 'cie:ctrlPageUp',
42
        ctrlPageDown: 'cie:ctrlPageDown',
43
        enter: 'cie:enter',
44
        accessibleChange: 'cie:accessibleChange',
45
    };
46
    // Static cache of jQuery events that have been handled. This should
47
    // only be populated by JavaScript generated events (which will keep it
48
    // fairly small).
49
    var triggeredEvents = {};
50
 
51
    /**
52
     * Check if the caller has asked for the given event type to be
53
     * registered.
54
     *
55
     * @method shouldAddEvent
56
     * @private
57
     * @param {string} eventType name of the event (see events above)
58
     * @param {array} include the list of events to be added
59
     * @return {bool} true if the event should be added, false otherwise.
60
     */
61
    var shouldAddEvent = function(eventType, include) {
62
        include = include || [];
63
 
64
        if (include.length && include.indexOf(eventType) !== -1) {
65
            return true;
66
        }
67
 
68
        return false;
69
    };
70
 
71
    /**
72
     * Check if any of the modifier keys have been pressed on the event.
73
     *
74
     * @method isModifierPressed
75
     * @private
76
     * @param {event} e jQuery event
77
     * @return {bool} true if shift, meta (command on Mac), alt or ctrl are pressed
78
     */
79
    var isModifierPressed = function(e) {
80
        return (e.shiftKey || e.metaKey || e.altKey || e.ctrlKey);
81
    };
82
 
83
    /**
84
     * Trigger the custom event for the given jQuery event.
85
     *
86
     * This function will only fire the custom event if one hasn't already been
87
     * fired for the jQuery event.
88
     *
89
     * This is to prevent multiple custom event handlers triggering multiple
90
     * custom events for a single jQuery event as it bubbles up the stack.
91
     *
92
     * @param  {string} eventName The name of the custom event
93
     * @param  {event} e          The jQuery event
94
     * @return {void}
95
     */
96
    var triggerEvent = function(eventName, e) {
97
        var eventTypeKey = "";
98
 
99
        if (!e.hasOwnProperty('originalEvent')) {
100
            // This is a jQuery event generated from JavaScript not a browser event so
101
            // we need to build the cache key for the event.
102
            eventTypeKey = "" + eventName + e.type + e.timeStamp;
103
 
104
            if (!triggeredEvents.hasOwnProperty(eventTypeKey)) {
105
                // If we haven't seen this jQuery event before then fire a custom
106
                // event for it and remember the event for later.
107
                triggeredEvents[eventTypeKey] = true;
108
                $(e.target).trigger(eventName, [{originalEvent: e}]);
109
            }
110
            return;
111
        }
112
 
113
        eventTypeKey = "triggeredCustom_" + eventName;
114
        if (!e.originalEvent.hasOwnProperty(eventTypeKey)) {
115
            // If this is a jQuery event generated by the browser then set a
116
            // property on the original event to track that we've seen it before.
117
            // The property is set on the original event because it's the only part
118
            // of the jQuery event that is maintained through multiple event handlers.
119
            e.originalEvent[eventTypeKey] = true;
120
            $(e.target).trigger(eventName, [{originalEvent: e}]);
121
            return;
122
        }
123
    };
124
 
125
    /**
126
     * Register a keyboard event that ignores modifier keys.
127
     *
128
     * @method addKeyboardEvent
129
     * @private
130
     * @param {object} element A jQuery object of the element to bind events to
131
     * @param {string} event The custom interaction event name
132
     * @param {int} keyCode The key code.
133
     */
134
    var addKeyboardEvent = function(element, event, keyCode) {
135
        element.off('keydown.' + event).on('keydown.' + event, function(e) {
136
            if (!isModifierPressed(e)) {
137
                if (e.keyCode == keyCode) {
138
                    triggerEvent(event, e);
139
                }
140
            }
141
        });
142
    };
143
 
144
    /**
145
     * Trigger the activate event on the given element if it is clicked or the enter
146
     * or space key are pressed without a modifier key.
147
     *
148
     * @method addActivateListener
149
     * @private
150
     * @param {object} element jQuery object to add event listeners to
151
     */
152
    var addActivateListener = function(element) {
153
        element.off('click.cie.activate').on('click.cie.activate', function(e) {
154
            triggerEvent(events.activate, e);
155
        });
156
        element.off('keydown.cie.activate').on('keydown.cie.activate', function(e) {
157
            if (!isModifierPressed(e)) {
158
                if (e.keyCode == keyCodes.enter || e.keyCode == keyCodes.space) {
159
                    triggerEvent(events.activate, e);
160
                }
161
            }
162
        });
163
    };
164
 
165
    /**
166
     * Trigger the keyboard activate event on the given element if the enter
167
     * or space key are pressed without a modifier key.
168
     *
169
     * @method addKeyboardActivateListener
170
     * @private
171
     * @param {object} element jQuery object to add event listeners to
172
     */
173
    var addKeyboardActivateListener = function(element) {
174
        element.off('keydown.cie.keyboardactivate').on('keydown.cie.keyboardactivate', function(e) {
175
            if (!isModifierPressed(e)) {
176
                if (e.keyCode == keyCodes.enter || e.keyCode == keyCodes.space) {
177
                    triggerEvent(events.keyboardActivate, e);
178
                }
179
            }
180
        });
181
    };
182
 
183
    /**
184
     * Trigger the escape event on the given element if the escape key is pressed
185
     * without a modifier key.
186
     *
187
     * @method addEscapeListener
188
     * @private
189
     * @param {object} element jQuery object to add event listeners to
190
     */
191
    var addEscapeListener = function(element) {
192
        addKeyboardEvent(element, events.escape, keyCodes.escape);
193
    };
194
 
195
    /**
196
     * Trigger the down event on the given element if the down arrow key is pressed
197
     * without a modifier key.
198
     *
199
     * @method addDownListener
200
     * @private
201
     * @param {object} element jQuery object to add event listeners to
202
     */
203
    var addDownListener = function(element) {
204
        addKeyboardEvent(element, events.down, keyCodes.arrowDown);
205
    };
206
 
207
    /**
208
     * Trigger the up event on the given element if the up arrow key is pressed
209
     * without a modifier key.
210
     *
211
     * @method addUpListener
212
     * @private
213
     * @param {object} element jQuery object to add event listeners to
214
     */
215
    var addUpListener = function(element) {
216
        addKeyboardEvent(element, events.up, keyCodes.arrowUp);
217
    };
218
 
219
    /**
220
     * Trigger the home event on the given element if the home key is pressed
221
     * without a modifier key.
222
     *
223
     * @method addHomeListener
224
     * @private
225
     * @param {object} element jQuery object to add event listeners to
226
     */
227
    var addHomeListener = function(element) {
228
        addKeyboardEvent(element, events.home, keyCodes.home);
229
    };
230
 
231
    /**
232
     * Trigger the end event on the given element if the end key is pressed
233
     * without a modifier key.
234
     *
235
     * @method addEndListener
236
     * @private
237
     * @param {object} element jQuery object to add event listeners to
238
     */
239
    var addEndListener = function(element) {
240
        addKeyboardEvent(element, events.end, keyCodes.end);
241
    };
242
 
243
    /**
244
     * Trigger the next event on the given element if the right arrow key is pressed
245
     * without a modifier key in LTR mode or left arrow key in RTL mode.
246
     *
247
     * @method addNextListener
248
     * @private
249
     * @param {object} element jQuery object to add event listeners to
250
     */
251
    var addNextListener = function(element) {
252
        // Left and right are flipped in RTL mode.
253
        var keyCode = $('html').attr('dir') == "rtl" ? keyCodes.arrowLeft : keyCodes.arrowRight;
254
 
255
        addKeyboardEvent(element, events.next, keyCode);
256
    };
257
 
258
    /**
259
     * Trigger the previous event on the given element if the left arrow key is pressed
260
     * without a modifier key in LTR mode or right arrow key in RTL mode.
261
     *
262
     * @method addPreviousListener
263
     * @private
264
     * @param {object} element jQuery object to add event listeners to
265
     */
266
    var addPreviousListener = function(element) {
267
        // Left and right are flipped in RTL mode.
268
        var keyCode = $('html').attr('dir') == "rtl" ? keyCodes.arrowRight : keyCodes.arrowLeft;
269
 
270
        addKeyboardEvent(element, events.previous, keyCode);
271
    };
272
 
273
    /**
274
     * Trigger the asterix event on the given element if the asterix key is pressed
275
     * without a modifier key.
276
     *
277
     * @method addAsterixListener
278
     * @private
279
     * @param {object} element jQuery object to add event listeners to
280
     */
281
    var addAsterixListener = function(element) {
282
        addKeyboardEvent(element, events.asterix, keyCodes.asterix);
283
    };
284
 
285
 
286
    /**
287
     * Trigger the scrollTop event on the given element if the user scrolls to
288
     * the top of the given element.
289
     *
290
     * @method addScrollTopListener
291
     * @private
292
     * @param {object} element jQuery object to add event listeners to
293
     */
294
    var addScrollTopListener = function(element) {
295
        element.off('scroll.cie.scrollTop').on('scroll.cie.scrollTop', function(e) {
296
            var scrollTop = element.scrollTop();
297
            if (scrollTop === 0) {
298
                triggerEvent(events.scrollTop, e);
299
            }
300
        });
301
    };
302
 
303
    /**
304
     * Trigger the scrollBottom event on the given element if the user scrolls to
305
     * the bottom of the given element.
306
     *
307
     * @method addScrollBottomListener
308
     * @private
309
     * @param {object} element jQuery object to add event listeners to
310
     */
311
    var addScrollBottomListener = function(element) {
312
        element.off('scroll.cie.scrollBottom').on('scroll.cie.scrollBottom', function(e) {
313
            var scrollTop = element.scrollTop();
314
            var innerHeight = element.innerHeight();
315
            var scrollHeight = element[0].scrollHeight;
316
 
317
            if (scrollTop + innerHeight >= scrollHeight) {
318
                triggerEvent(events.scrollBottom, e);
319
            }
320
        });
321
    };
322
 
323
    /**
324
     * Trigger the scrollLock event on the given element if the user scrolls to
325
     * the bottom or top of the given element.
326
     *
327
     * @method addScrollLockListener
328
     * @private
329
     * @param {jQuery} element jQuery object to add event listeners to
330
     */
331
    var addScrollLockListener = function(element) {
332
        // Lock mousewheel scrolling within the element to stop the annoying window scroll.
333
        element.off('DOMMouseScroll.cie.DOMMouseScrollLock mousewheel.cie.mousewheelLock')
334
            .on('DOMMouseScroll.cie.DOMMouseScrollLock mousewheel.cie.mousewheelLock', function(e) {
335
                var scrollTop = element.scrollTop();
336
                var scrollHeight = element[0].scrollHeight;
337
                var height = element.height();
338
                var delta = (e.type == 'DOMMouseScroll' ?
339
                    e.originalEvent.detail * -40 :
340
                    e.originalEvent.wheelDelta);
341
                var up = delta > 0;
342
 
343
                if (!up && -delta > scrollHeight - height - scrollTop) {
344
                    // Scrolling down past the bottom.
345
                    element.scrollTop(scrollHeight);
346
                    e.stopPropagation();
347
                    e.preventDefault();
348
                    e.returnValue = false;
349
                    // Fire the scroll lock event.
350
                    triggerEvent(events.scrollLock, e);
351
 
352
                    return false;
353
                } else if (up && delta > scrollTop) {
354
                    // Scrolling up past the top.
355
                    element.scrollTop(0);
356
                    e.stopPropagation();
357
                    e.preventDefault();
358
                    e.returnValue = false;
359
                    // Fire the scroll lock event.
360
                    triggerEvent(events.scrollLock, e);
361
 
362
                    return false;
363
                }
364
 
365
                return true;
366
            });
367
    };
368
 
369
    /**
370
     * Trigger the ctrlPageUp event on the given element if the user presses the
371
     * control and page up key.
372
     *
373
     * @method addCtrlPageUpListener
374
     * @private
375
     * @param {object} element jQuery object to add event listeners to
376
     */
377
    var addCtrlPageUpListener = function(element) {
378
        element.off('keydown.cie.ctrlpageup').on('keydown.cie.ctrlpageup', function(e) {
379
            if (e.ctrlKey) {
380
                if (e.keyCode == keyCodes.pageUp) {
381
                    triggerEvent(events.ctrlPageUp, e);
382
                }
383
            }
384
        });
385
    };
386
 
387
    /**
388
     * Trigger the ctrlPageDown event on the given element if the user presses the
389
     * control and page down key.
390
     *
391
     * @method addCtrlPageDownListener
392
     * @private
393
     * @param {object} element jQuery object to add event listeners to
394
     */
395
    var addCtrlPageDownListener = function(element) {
396
        element.off('keydown.cie.ctrlpagedown').on('keydown.cie.ctrlpagedown', function(e) {
397
            if (e.ctrlKey) {
398
                if (e.keyCode == keyCodes.pageDown) {
399
                    triggerEvent(events.ctrlPageDown, e);
400
                }
401
            }
402
        });
403
    };
404
 
405
    /**
406
     * Trigger the enter event on the given element if the enter key is pressed
407
     * without a modifier key.
408
     *
409
     * @method addEnterListener
410
     * @private
411
     * @param {object} element jQuery object to add event listeners to
412
     */
413
    var addEnterListener = function(element) {
414
        addKeyboardEvent(element, events.enter, keyCodes.enter);
415
    };
416
 
417
    /**
418
     * Trigger the AccessibleChange event on the given element if the value of the element is changed.
419
     *
420
     * @method addAccessibleChangeListener
421
     * @private
422
     * @param {object} element jQuery object to add event listeners to
423
     */
424
    var addAccessibleChangeListener = function(element) {
425
        var onMac = navigator.userAgent.indexOf('Macintosh') !== -1;
426
        var touchEnabled = ('ontouchstart' in window) || (('msMaxTouchPoints' in navigator) && (navigator.msMaxTouchPoints > 0));
427
        if (onMac || touchEnabled) {
428
            // On Mac devices, and touch-enabled devices, the change event seems to be handled correctly and
429
            // consistently at this time.
430
            element.on('change', function(e) {
431
                triggerEvent(events.accessibleChange, e);
432
            });
433
        } else {
434
            // Some browsers have non-normalised behaviour for handling the selection of values in a <select> element.
435
            // When using Chrome on Linux (and possibly others), a 'change' event is fired when pressing the Escape key.
436
            // When using Firefox on Linux (and possibly others), a 'change' event is fired when navigating through the
437
            // list with a keyboard.
438
            //
439
            // To normalise these behaviours:
440
            // - the initial value is stored in a data attribute when focusing the element
441
            // - the current value is checked against the stored initial value when and the accessibleChange event fired when:
442
            // --- blurring the element
443
            // --- the 'Enter' key is pressed
444
            // --- the element is clicked
445
            // --- the 'change' event is fired, except where it is from a keyboard interaction
446
            //
447
            // To facilitate the change event keyboard interaction check, the 'keyDown' handler sets a flag to ignore
448
            // the change event handler which is unset on the 'keyUp' event.
449
            //
450
            // Unfortunately we cannot control this entirely as some browsers (Chrome) trigger a change event when
451
            // pressign the Escape key, and this is considered to be the correct behaviour.
452
            // Chrome https://bugs.chromium.org/p/chromium/issues/detail?id=839717
453
            //
454
            // Our longer-term solution to this should be to switch away from using <select> boxes as a single-select,
455
            // and make use of a dropdown of action links like the Bootstrap Dropdown menu.
456
            var setInitialValue = function(target) {
457
                target.dataset.initValue = target.value;
458
            };
459
            var resetToInitialValue = function(target) {
460
                if ('initValue' in target.dataset) {
461
                    target.value = target.dataset.initValue;
462
                }
463
            };
464
            var checkAndTriggerAccessibleChange = function(e) {
465
                if (!('initValue' in e.target.dataset)) {
466
                    // Some browsers trigger click before focus, therefore it is possible that initValue is undefined.
467
                    // In this case it's likely that it's being focused for the first time and we should therefore not submit.
468
                    return;
469
                }
470
 
471
                if (e.target.value !== e.target.dataset.initValue) {
472
                    // Update the initValue when the event is triggered.
473
                    // This means that if the click handler fires before the focus handler on a subsequent interaction
474
                    // with the element, the currently dispalyed value will be the best guess current value.
475
                    e.target.dataset.initValue = e.target.value;
476
                    triggerEvent(events.accessibleChange, e);
477
                }
478
            };
479
            var nativeElement = element.get()[0];
480
            // The `focus` and `blur` events do not support bubbling. Use Event Capture instead.
481
            nativeElement.addEventListener('focus', function(e) {
482
                setInitialValue(e.target);
483
            }, true);
484
            nativeElement.addEventListener('blur', function(e) {
485
                checkAndTriggerAccessibleChange(e);
486
            }, true);
487
            element.on('keydown', function(e) {
488
                if ((e.which === keyCodes.enter)) {
489
                    checkAndTriggerAccessibleChange(e);
490
                } else if (e.which === keyCodes.escape) {
491
                    resetToInitialValue(e.target);
492
                    e.target.dataset.ignoreChange = true;
493
                } else {
494
                    // Firefox triggers a change event when using the keyboard to scroll through the selection.
495
                    // Set a data- attribute that the change listener can use to ignore the change event where it was
496
                    // generated from a keyboard change such as typing to complete a value, or using arrow keys.
497
                    e.target.dataset.ignoreChange = true;
498
 
499
                }
500
            });
501
            element.on('change', function(e) {
502
                if (e.target.dataset.ignoreChange) {
503
                    // This change event was triggered from a keyboard change which is not yet complete.
504
                    // Do not trigger the accessibleChange event until the selection is completed using the [return]
505
                    // key.
506
                    return;
507
                }
508
 
509
                checkAndTriggerAccessibleChange(e);
510
            });
511
            element.on('keyup', function(e) {
512
                // The key has been lifted. Stop ignoring the change event.
513
                delete e.target.dataset.ignoreChange;
514
            });
515
            element.on('click', function(e) {
516
                checkAndTriggerAccessibleChange(e);
517
            });
518
        }
519
    };
520
 
521
    /**
522
     * Get the list of events and their handlers.
523
     *
524
     * @method getHandlers
525
     * @private
526
     * @return {object} object key of event names and value of handler functions
527
     */
528
    var getHandlers = function() {
529
        var handlers = {};
530
 
531
        handlers[events.activate] = addActivateListener;
532
        handlers[events.keyboardActivate] = addKeyboardActivateListener;
533
        handlers[events.escape] = addEscapeListener;
534
        handlers[events.down] = addDownListener;
535
        handlers[events.up] = addUpListener;
536
        handlers[events.home] = addHomeListener;
537
        handlers[events.end] = addEndListener;
538
        handlers[events.next] = addNextListener;
539
        handlers[events.previous] = addPreviousListener;
540
        handlers[events.asterix] = addAsterixListener;
541
        handlers[events.scrollLock] = addScrollLockListener;
542
        handlers[events.scrollTop] = addScrollTopListener;
543
        handlers[events.scrollBottom] = addScrollBottomListener;
544
        handlers[events.ctrlPageUp] = addCtrlPageUpListener;
545
        handlers[events.ctrlPageDown] = addCtrlPageDownListener;
546
        handlers[events.enter] = addEnterListener;
547
        handlers[events.accessibleChange] = addAccessibleChangeListener;
548
 
549
        return handlers;
550
    };
551
 
552
    /**
553
     * Add all of the listeners on the given element for the requested events.
554
     *
555
     * @method define
556
     * @public
557
     * @param {object} element the DOM element to register event listeners on
558
     * @param {array} include the array of events to be triggered
559
     */
560
    var define = function(element, include) {
561
        element = $(element);
562
        include = include || [];
563
 
564
        if (!element.length || !include.length) {
565
            return;
566
        }
567
 
568
        $.each(getHandlers(), function(eventType, handler) {
569
            if (shouldAddEvent(eventType, include)) {
570
                handler(element);
571
            }
572
        });
573
    };
574
 
575
    return {
576
        define: define,
577
        events: events,
578
    };
579
});