MDL-55727 javascript: Add modal module
[moodle.git] / lib / amd / src / modal.js
CommitLineData
2bcef559
RW
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 * Contain the logic for modals.
18 *
19 * @module core/modal
20 * @class modal
21 * @package core
22 * @copyright 2016 Ryan Wyllie <ryan@moodle.com>
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 */
25define(['jquery', 'core/templates', 'core/notification', 'core/key_codes',
26 'core/custom_interaction_events', 'core/modal_backdrop', 'core/modal_events'],
27 function($, Templates, Notification, KeyCodes, CustomEvents, ModalBackdrop, ModalEvents) {
28
29 var SELECTORS = {
30 CONTAINER: '[data-region="modal-container"]',
31 MODAL: '[data-region="modal"]',
32 HEADER: '[data-region="header"]',
33 TITLE: '[data-region="title"]',
34 BODY: '[data-region="body"]',
35 FOOTER: '[data-region="footer"]',
36 HIDE: '[data-action="hide"]',
37 DIALOG: '[role=dialog]',
38 MENU_BAR: '[role=menubar]',
39 HAS_Z_INDEX: '.moodle-has-zindex',
40 CAN_RECEIVE_FOCUS: 'input:not([type="hidden"]), a[href], button, textarea, select, [tabindex]',
41 };
42
43 var TEMPLATES = {
44 LOADING: 'core/loading',
45 BACKDROP: 'core/modal_backdrop',
46 };
47
48 /**
49 * Module singleton for the backdrop to be reused by all Modal instances.
50 */
51 var backdropPromise;
52
53 /**
54 * Constructor for the Modal.
55 *
56 * @param {object} root The root jQuery element for the modal
57 */
58 var Modal = function(root) {
59 this.root = $(root);
60 this.modal = this.root.find(SELECTORS.MODAL);
61 this.header = this.modal.find(SELECTORS.HEADER);
62 this.title = this.header.find(SELECTORS.TITLE);
63 this.body = this.modal.find(SELECTORS.BODY);
64 this.footer = this.modal.find(SELECTORS.FOOTER);
65 this.hiddenSiblings = [];
66 this.isAttached = false;
67 this.bodyJS = null;
68 this.footerJS = null;
69
70 if (!this.root.is(SELECTORS.CONTAINER)) {
71 Notification.exception({message: 'Element is not a modal container'});
72 }
73
74 if (!this.modal.length) {
75 Notification.exception({message: 'Container does not contain a modal'});
76 }
77
78 if (!this.header.length) {
79 Notification.exception({message: 'Modal is missing a header region'});
80 }
81
82 if (!this.title.length) {
83 Notification.exception({message: 'Modal header is missing a title region'});
84 }
85
86 if (!this.body.length) {
87 Notification.exception({message: 'Modal is missing a body region'});
88 }
89
90 if (!this.footer.length) {
91 Notification.exception({message: 'Modal is missing a footer region'});
92 }
93
94 this.registerEventListeners();
95 };
96
97 /**
98 * Add the modal to the page, if it hasn't already been added. This includes running any
99 * javascript that has been cached until now.
100 *
101 * @method attachToDOM
102 */
103 Modal.prototype.attachToDOM = function() {
104 if (this.isAttached) {
105 return;
106 }
107
108 $('body').append(this.root);
109
110 // If we'd cached any JS then we can run it how that the modal is
111 // attached to the DOM.
112 if (this.bodyJS) {
113 Templates.runTemplateJS(this.bodyJS);
114 this.bodyJS = null;
115 }
116
117 if (this.footerJS) {
118 Templates.runTemplateJS(this.footerJS);
119 this.footerJS = null;
120 }
121
122 this.isAttached = true;
123 };
124
125 /**
126 * Count the number of other visible modals (not including this one).
127 *
128 * @method countOtherVisibleModals
129 * @return {int}
130 */
131 Modal.prototype.countOtherVisibleModals = function() {
132 var count = 0;
133 $('body').find(SELECTORS.CONTAINER).each(function(index, element) {
134 element = $(element);
135
136 // If we haven't found ourself and the element is visible.
137 if (!this.root.is(element) && element.hasClass('show')) {
138 count++;
139 }
140 }.bind(this));
141
142 return count;
143 };
144
145 /**
146 * Get the modal backdrop.
147 *
148 * @method getBackdrop
149 * @return {object} jQuery promise
150 */
151 Modal.prototype.getBackdrop = function() {
152 if (!backdropPromise) {
153 backdropPromise = Templates.render(TEMPLATES.BACKDROP, {})
154 .then(function(html) {
155 var element = $(html);
156
157 return new ModalBackdrop(element);
158 })
159 .fail(Notification.exception);
160 }
161
162 return backdropPromise;
163 };
164
165 /**
166 * Get the root element of this modal.
167 *
168 * @method getRoot
169 * @return {object} jQuery object
170 */
171 Modal.prototype.getRoot = function() {
172 return this.root;
173 };
174
175 /**
176 * Get the modal element of this modal.
177 *
178 * @method getModal
179 * @return {object} jQuery object
180 */
181 Modal.prototype.getModal = function() {
182 return this.modal;
183 };
184
185 /**
186 * Get the modal title element.
187 *
188 * @method getTitle
189 * @return {object} jQuery object
190 */
191 Modal.prototype.getTitle = function() {
192 return this.title;
193 };
194
195 /**
196 * Get the modal body element.
197 *
198 * @method getBody
199 * @return {object} jQuery object
200 */
201 Modal.prototype.getBody = function() {
202 return this.body;
203 };
204
205 /**
206 * Get the modal footer element.
207 *
208 * @method getFooter
209 * @return {object} jQuery object
210 */
211 Modal.prototype.getFooter = function() {
212 return this.footer;
213 };
214
215 /**
216 * Set the modal title element.
217 *
218 * @method setTitle
219 * @param {string} value The title string
220 */
221 Modal.prototype.setTitle = function(value) {
222 var title = this.getTitle();
223 title.html(value);
224 };
225
226 /**
227 * Set the modal body element.
228 *
229 * This method is overloaded to take either a string
230 * value for the body or a jQuery promise that is resolved with HTML and Javascript
231 * most commonly from a Templates.render call.
232 *
233 * @method setBody
234 * @param {(string|object)} value The body string or jQuery promise
235 */
236 Modal.prototype.setBody = function(value) {
237 var body = this.getBody();
238
239 if (typeof value === 'string') {
240 // Just set the value if it's a string.
241 body.html(value);
242 } else {
243 // Otherwise we assume it's a promise to be resolved with
244 // html and javascript.
245 Templates.render(TEMPLATES.LOADING, {}).done(function(html) {
246 body.html(html);
247
248 value.done(function(html, js) {
249 body.html(html);
250
251 if (this.isAttached) {
252 // If we're in the DOM then run the JS immediately.
253 Templates.runTemplateJS(js);
254 } else {
255 // Otherwise cache it to be run when we're attached.
256 this.bodyJS = js;
257 }
258 }.bind(this));
259 }.bind(this));
260 }
261 };
262
263 /**
264 * Set the modal footer element.
265 *
266 * This method is overloaded to take either a string
267 * value for the body or a jQuery promise that is resolved with HTML and Javascript
268 * most commonly from a Templates.render call.
269 *
270 * @method setFooter
271 * @param {(string|object)} value The footer string or jQuery promise
272 */
273 Modal.prototype.setFooter = function(value) {
274 var footer = this.getFooter();
275
276 if (typeof value === 'string') {
277 // Just set the value if it's a string.
278 footer.html(value);
279 } else {
280 // Otherwise we assume it's a promise to be resolved with
281 // html and javascript.
282 Templates.render(TEMPLATES.LOADING, {}).done(function(html) {
283 footer.html(html);
284
285 value.done(function(html, js) {
286 footer.html(html);
287
288 if (this.isAttached) {
289 // If we're in the DOM then run the JS immediately.
290 Templates.runTemplateJS(js);
291 } else {
292 // Otherwise cache it to be run when we're attached.
293 this.footerJS = js;
294 }
295 }.bind(this));
296 }.bind(this));
297 }
298 };
299
300 /**
301 * Mark the modal as a large modal.
302 *
303 * @method setLarge
304 */
305 Modal.prototype.setLarge = function() {
306 if (this.isLarge()) {
307 return;
308 }
309
310 this.getRoot().addClass('large');
311 };
312
313 /**
314 * Check if the modal is a large modal.
315 *
316 * @method isLarge
317 * @return {bool}
318 */
319 Modal.prototype.isLarge = function() {
320 return this.getRoot().hasClass('large');
321 };
322
323 /**
324 * Mark the modal as a small modal.
325 *
326 * @method setSmall
327 */
328 Modal.prototype.setSmall = function() {
329 if (this.isSmall()) {
330 return;
331 }
332
333 this.getRoot().removeClass('large');
334 };
335
336 /**
337 * Check if the modal is a small modal.
338 *
339 * @method isSmall
340 * @return {bool}
341 */
342 Modal.prototype.isSmall = function() {
343 return !this.getRoot().hasClass('large');
344 };
345
346 /**
347 * Determine the highest z-index value currently on the page.
348 *
349 * @method calculateZIndex
350 * @return {int}
351 */
352 Modal.prototype.calculateZIndex = function() {
353 var items = $(SELECTORS.DIALOG + ', ' + SELECTORS.MENU_BAR + ', ' + SELECTORS.HAS_Z_INDEX);
354 var zIndex = parseInt(this.root.css('z-index'));
355
356 items.each(function(index, item) {
357 item = $(item);
358 // Note that webkit browsers won't return the z-index value from the CSS stylesheet
359 // if the element doesn't have a position specified. Instead it'll return "auto".
360 var itemZIndex = item.css('z-index') ? parseInt(item.css('z-index')) : 0;
361
362 if (itemZIndex > zIndex) {
363 zIndex = itemZIndex;
364 }
365 });
366
367 return zIndex;
368 };
369
370 /**
371 * Check if this modal is visible.
372 *
373 * @method isVisible
374 * @return {bool}
375 */
376 Modal.prototype.isVisible = function() {
377 return this.root.hasClass('show');
378 };
379
380 /**
381 * Check if this modal has focus.
382 *
383 * @method hasFocus
384 * @return {bool}
385 */
386 Modal.prototype.hasFocus = function() {
387 var target = $(document.activeElement);
388 return this.root.is(target) || this.root.has(target).length;
389 };
390
391 /**
392 * Check if this modal has CSS transitions applied.
393 *
394 * @method hasTransitions
395 * @return {bool}
396 */
397 Modal.prototype.hasTransitions = function() {
398 return this.getRoot().hasClass('fade');
399 };
400
401 /**
402 * Display this modal. The modal will be attached to the DOM if it hasn't
403 * already been.
404 *
405 * @method show
406 */
407 Modal.prototype.show = function() {
408 if (this.isVisible()) {
409 return;
410 }
411
412 if (!this.isAttached) {
413 this.attachToDOM();
414 }
415
416 this.getBackdrop().done(function(backdrop) {
417 var currentIndex = this.calculateZIndex();
418 var newIndex = currentIndex + 2;
419 var newBackdropIndex = newIndex - 1;
420 this.root.css('z-index', newIndex);
421 backdrop.setZIndex(newBackdropIndex);
422 backdrop.show();
423
424 this.root.removeClass('hide').addClass('show');
425 this.accessibilityShow();
426 this.getTitle().focus();
427 $('body').addClass('modal-open');
428 this.root.trigger(ModalEvents.shown, this);
429 }.bind(this));
430 };
431
432 /**
433 * Hide this modal.
434 *
435 * @method hide
436 */
437 Modal.prototype.hide = function() {
438 if (!this.isVisible()) {
439 return;
440 }
441
442 this.getBackdrop().done(function(backdrop) {
443 if (!this.countOtherVisibleModals()) {
444 // Hide the backdrop if we're the last open modal.
445 backdrop.hide();
446 $('body').removeClass('modal-open');
447 }
448
449 var currentIndex = parseInt(this.root.css('z-index'));
450 this.root.css('z-index', '');
451 backdrop.setZIndex(currentIndex - 3);
452
453 this.accessibilityHide();
454
455 if (this.hasTransitions()) {
456 // Wait for CSS transitions to complete before hiding the element.
457 this.getRoot().one('transitionend webkitTransitionEnd oTransitionEnd', function() {
458 this.getRoot().removeClass('show').addClass('hide');
459 }.bind(this));
460 } else {
461 this.getRoot().removeClass('show').addClass('hide');
462 }
463
464 this.root.trigger(ModalEvents.hidden, this);
465 }.bind(this));
466 };
467
468 /**
469 * Remove this modal from the DOM.
470 *
471 * @method destroy
472 */
473 Modal.prototype.destroy = function() {
474 this.root.remove();
475 this.root.trigger(ModalEvents.destroyed, this);
476 };
477
478 /**
479 * Sets the appropriate aria attributes on this dialogue and the other
480 * elements in the DOM to ensure that screen readers are able to navigate
481 * the dialogue popup correctly.
482 *
483 * @method accessibilityShow
484 */
485 Modal.prototype.accessibilityShow = function() {
486 // We need to get a list containing each sibling element and the shallowest
487 // non-ancestral nodes in the DOM. We can shortcut this a little by leveraging
488 // the fact that this dialogue is always appended to the document body therefore
489 // it's siblings are the shallowest non-ancestral nodes. If that changes then
490 // this code should also be updated.
491 $('body').children().each(function(index, child) {
492 // Skip the current modal.
493 if (!this.root.is(child)) {
494 child = $(child);
495 var hidden = child.attr('aria-hidden');
496 // If they are already hidden we can ignore them.
497 if (hidden !== 'true') {
498 // Save their current state.
499 child.data('previous-aria-hidden', hidden);
500 this.hiddenSiblings.push(child);
501
502 // Hide this node from screen readers.
503 child.attr('aria-hidden', 'true');
504 }
505 }
506 }.bind(this));
507
508 // Make us visible to screen readers.
509 this.root.attr('aria-hidden', 'false');
510 };
511
512 /**
513 * Restores the aria visibility on the DOM elements changed when displaying
514 * the dialogue popup and makes the dialogue aria hidden to allow screen
515 * readers to navigate the main page correctly when the dialogue is closed.
516 *
517 * @method accessibilityHide
518 */
519 Modal.prototype.accessibilityHide = function() {
520 this.root.attr('aria-hidden', 'true');
521
522 // Restore the sibling nodes back to their original values.
523 $.each(this.hiddenSiblings, function(index, sibling) {
524 sibling = $(sibling);
525 var previousValue = sibling.data('previous-aria-hidden');
526 // If the element didn't previously have an aria-hidden attribute
527 // then we can just remove the one we set.
528 if (typeof previousValue == 'undefined') {
529 sibling.removeAttr('aria-hidden');
530 } else {
531 // Otherwise set it back to the old value (which will be false).
532 sibling.attr('aria-hidden', previousValue);
533 }
534 });
535
536 // Clear the cache. No longer need to store these.
537 this.hiddenSiblings = [];
538 };
539
540 /**
541 * Handle the tab event to lock focus within this modal.
542 *
543 * @method handleTabLock
544 * @param {event} e The tab key jQuery event
545 */
546 Modal.prototype.handleTabLock = function(e) {
547 if (!this.hasFocus()) {
548 return;
549 }
550
551 var target = $(document.activeElement);
552 var focusableElements = this.modal.find(SELECTORS.CAN_RECEIVE_FOCUS);
553 var firstFocusable = focusableElements.first();
554 var lastFocusable = focusableElements.last();
555
556 if (target.is(firstFocusable) && e.shiftKey) {
557 lastFocusable.focus();
558 e.preventDefault();
559 } else if (target.is(lastFocusable) && !e.shiftKey) {
560 firstFocusable.focus();
561 e.preventDefault();
562 }
563 };
564
565 /**
566 * Set up all of the event handling for the modal.
567 *
568 * @method registerEventListeners
569 */
570 Modal.prototype.registerEventListeners = function() {
571 this.getRoot().on('keydown', function(e) {
572 if (!this.isVisible()) {
573 return;
574 }
575
576 if (e.keyCode == KeyCodes.tab) {
577 this.handleTabLock(e);
578 } else if (e.keyCode == KeyCodes.escape) {
579 this.hide();
580 }
581 }.bind(this));
582
583 CustomEvents.define(this.getModal(), [CustomEvents.events.activate]);
584 this.getModal().on(CustomEvents.events.activate, SELECTORS.HIDE, function(e, data) {
585 this.hide();
586 data.originalEvent.preventDefault();
587 }.bind(this));
588 };
589
590 return Modal;
591});