1 // This file is part of Moodle - http://moodle.org/
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.
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.
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/>.
17 * Contain the logic for modals.
22 * @copyright 2016 Ryan Wyllie <ryan@moodle.com>
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 define(['jquery', 'core/templates', 'core/notification', 'core/key_codes',
26 'core/custom_interaction_events', 'core/modal_backdrop', 'core/event', 'core/modal_events'],
27 function($, Templates, Notification, KeyCodes, CustomEvents, ModalBackdrop, Event, ModalEvents) {
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]',
44 LOADING: 'core/loading',
45 BACKDROP: 'core/modal_backdrop',
49 * Module singleton for the backdrop to be reused by all Modal instances.
54 * Constructor for the Modal.
56 * @param {object} root The root jQuery element for the modal
58 var Modal = function(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;
70 if (!this.root.is(SELECTORS.CONTAINER)) {
71 Notification.exception({message: 'Element is not a modal container'});
74 if (!this.modal.length) {
75 Notification.exception({message: 'Container does not contain a modal'});
78 if (!this.header.length) {
79 Notification.exception({message: 'Modal is missing a header region'});
82 if (!this.title.length) {
83 Notification.exception({message: 'Modal header is missing a title region'});
86 if (!this.body.length) {
87 Notification.exception({message: 'Modal is missing a body region'});
90 if (!this.footer.length) {
91 Notification.exception({message: 'Modal is missing a footer region'});
94 this.registerEventListeners();
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.
101 * @method attachToDOM
103 Modal.prototype.attachToDOM = function() {
104 if (this.isAttached) {
108 $('body').append(this.root);
110 // If we'd cached any JS then we can run it how that the modal is
111 // attached to the DOM.
113 Templates.runTemplateJS(this.bodyJS);
118 Templates.runTemplateJS(this.footerJS);
119 this.footerJS = null;
122 this.isAttached = true;
126 * Count the number of other visible modals (not including this one).
128 * @method countOtherVisibleModals
131 Modal.prototype.countOtherVisibleModals = function() {
133 $('body').find(SELECTORS.CONTAINER).each(function(index, element) {
134 element = $(element);
136 // If we haven't found ourself and the element is visible.
137 if (!this.root.is(element) && element.hasClass('show')) {
146 * Get the modal backdrop.
148 * @method getBackdrop
149 * @return {object} jQuery promise
151 Modal.prototype.getBackdrop = function() {
152 if (!backdropPromise) {
153 backdropPromise = Templates.render(TEMPLATES.BACKDROP, {})
154 .then(function(html) {
155 var element = $(html);
157 return new ModalBackdrop(element);
159 .fail(Notification.exception);
162 return backdropPromise;
166 * Get the root element of this modal.
169 * @return {object} jQuery object
171 Modal.prototype.getRoot = function() {
176 * Get the modal element of this modal.
179 * @return {object} jQuery object
181 Modal.prototype.getModal = function() {
186 * Get the modal title element.
189 * @return {object} jQuery object
191 Modal.prototype.getTitle = function() {
196 * Get the modal body element.
199 * @return {object} jQuery object
201 Modal.prototype.getBody = function() {
206 * Get the modal footer element.
209 * @return {object} jQuery object
211 Modal.prototype.getFooter = function() {
216 * Set the modal title element.
219 * @param {string} value The title string
221 Modal.prototype.setTitle = function(value) {
222 var title = this.getTitle();
227 * Set the modal body element.
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.
234 * @param {(string|object)} value The body string or jQuery promise
236 Modal.prototype.setBody = function(value) {
237 var body = this.getBody();
239 if (typeof value === 'string') {
240 // Just set the value if it's a string.
242 Event.notifyFilterContentUpdated(body);
243 this.getRoot().trigger(ModalEvents.bodyRendered, this);
245 // Otherwise we assume it's a promise to be resolved with
246 // html and javascript.
247 Templates.render(TEMPLATES.LOADING, {}).done(function(html) {
250 value.done(function(html, js) {
254 if (this.isAttached) {
255 // If we're in the DOM then run the JS immediately.
256 Templates.runTemplateJS(js);
258 // Otherwise cache it to be run when we're attached.
262 Event.notifyFilterContentUpdated(body);
263 this.getRoot().trigger(ModalEvents.bodyRendered, this);
270 * Set the modal footer element.
272 * This method is overloaded to take either a string
273 * value for the body or a jQuery promise that is resolved with HTML and Javascript
274 * most commonly from a Templates.render call.
277 * @param {(string|object)} value The footer string or jQuery promise
279 Modal.prototype.setFooter = function(value) {
280 var footer = this.getFooter();
282 if (typeof value === 'string') {
283 // Just set the value if it's a string.
286 // Otherwise we assume it's a promise to be resolved with
287 // html and javascript.
288 Templates.render(TEMPLATES.LOADING, {}).done(function(html) {
291 value.done(function(html, js) {
295 if (this.isAttached) {
296 // If we're in the DOM then run the JS immediately.
297 Templates.runTemplateJS(js);
299 // Otherwise cache it to be run when we're attached.
309 * Mark the modal as a large modal.
313 Modal.prototype.setLarge = function() {
314 if (this.isLarge()) {
318 this.getRoot().addClass('large');
322 * Check if the modal is a large modal.
327 Modal.prototype.isLarge = function() {
328 return this.getRoot().hasClass('large');
332 * Mark the modal as a small modal.
336 Modal.prototype.setSmall = function() {
337 if (this.isSmall()) {
341 this.getRoot().removeClass('large');
345 * Check if the modal is a small modal.
350 Modal.prototype.isSmall = function() {
351 return !this.getRoot().hasClass('large');
355 * Determine the highest z-index value currently on the page.
357 * @method calculateZIndex
360 Modal.prototype.calculateZIndex = function() {
361 var items = $(SELECTORS.DIALOG + ', ' + SELECTORS.MENU_BAR + ', ' + SELECTORS.HAS_Z_INDEX);
362 var zIndex = parseInt(this.root.css('z-index'));
364 items.each(function(index, item) {
366 // Note that webkit browsers won't return the z-index value from the CSS stylesheet
367 // if the element doesn't have a position specified. Instead it'll return "auto".
368 var itemZIndex = item.css('z-index') ? parseInt(item.css('z-index')) : 0;
370 if (itemZIndex > zIndex) {
379 * Check if this modal is visible.
384 Modal.prototype.isVisible = function() {
385 return this.root.hasClass('show');
389 * Check if this modal has focus.
394 Modal.prototype.hasFocus = function() {
395 var target = $(document.activeElement);
396 return this.root.is(target) || this.root.has(target).length;
400 * Check if this modal has CSS transitions applied.
402 * @method hasTransitions
405 Modal.prototype.hasTransitions = function() {
406 return this.getRoot().hasClass('fade');
410 * Display this modal. The modal will be attached to the DOM if it hasn't
415 Modal.prototype.show = function() {
416 if (this.isVisible()) {
420 if (!this.isAttached) {
424 this.getBackdrop().done(function(backdrop) {
425 var currentIndex = this.calculateZIndex();
426 var newIndex = currentIndex + 2;
427 var newBackdropIndex = newIndex - 1;
428 this.root.css('z-index', newIndex);
429 backdrop.setZIndex(newBackdropIndex);
432 this.root.removeClass('hide').addClass('show');
433 this.accessibilityShow();
434 this.getTitle().focus();
435 $('body').addClass('modal-open');
436 this.root.trigger(ModalEvents.shown, this);
445 Modal.prototype.hide = function() {
446 if (!this.isVisible()) {
450 this.getBackdrop().done(function(backdrop) {
451 if (!this.countOtherVisibleModals()) {
452 // Hide the backdrop if we're the last open modal.
454 $('body').removeClass('modal-open');
457 var currentIndex = parseInt(this.root.css('z-index'));
458 this.root.css('z-index', '');
459 backdrop.setZIndex(currentIndex - 3);
461 this.accessibilityHide();
463 if (this.hasTransitions()) {
464 // Wait for CSS transitions to complete before hiding the element.
465 this.getRoot().one('transitionend webkitTransitionEnd oTransitionEnd', function() {
466 this.getRoot().removeClass('show').addClass('hide');
469 this.getRoot().removeClass('show').addClass('hide');
472 this.root.trigger(ModalEvents.hidden, this);
477 * Remove this modal from the DOM.
481 Modal.prototype.destroy = function() {
483 this.root.trigger(ModalEvents.destroyed, this);
487 * Sets the appropriate aria attributes on this dialogue and the other
488 * elements in the DOM to ensure that screen readers are able to navigate
489 * the dialogue popup correctly.
491 * @method accessibilityShow
493 Modal.prototype.accessibilityShow = function() {
494 // We need to get a list containing each sibling element and the shallowest
495 // non-ancestral nodes in the DOM. We can shortcut this a little by leveraging
496 // the fact that this dialogue is always appended to the document body therefore
497 // it's siblings are the shallowest non-ancestral nodes. If that changes then
498 // this code should also be updated.
499 $('body').children().each(function(index, child) {
500 // Skip the current modal.
501 if (!this.root.is(child)) {
503 var hidden = child.attr('aria-hidden');
504 // If they are already hidden we can ignore them.
505 if (hidden !== 'true') {
506 // Save their current state.
507 child.data('previous-aria-hidden', hidden);
508 this.hiddenSiblings.push(child);
510 // Hide this node from screen readers.
511 child.attr('aria-hidden', 'true');
516 // Make us visible to screen readers.
517 this.root.attr('aria-hidden', 'false');
521 * Restores the aria visibility on the DOM elements changed when displaying
522 * the dialogue popup and makes the dialogue aria hidden to allow screen
523 * readers to navigate the main page correctly when the dialogue is closed.
525 * @method accessibilityHide
527 Modal.prototype.accessibilityHide = function() {
528 this.root.attr('aria-hidden', 'true');
530 // Restore the sibling nodes back to their original values.
531 $.each(this.hiddenSiblings, function(index, sibling) {
532 sibling = $(sibling);
533 var previousValue = sibling.data('previous-aria-hidden');
534 // If the element didn't previously have an aria-hidden attribute
535 // then we can just remove the one we set.
536 if (typeof previousValue == 'undefined') {
537 sibling.removeAttr('aria-hidden');
539 // Otherwise set it back to the old value (which will be false).
540 sibling.attr('aria-hidden', previousValue);
544 // Clear the cache. No longer need to store these.
545 this.hiddenSiblings = [];
549 * Handle the tab event to lock focus within this modal.
551 * @method handleTabLock
552 * @param {event} e The tab key jQuery event
554 Modal.prototype.handleTabLock = function(e) {
555 if (!this.hasFocus()) {
559 var target = $(document.activeElement);
560 var focusableElements = this.modal.find(SELECTORS.CAN_RECEIVE_FOCUS);
561 var firstFocusable = focusableElements.first();
562 var lastFocusable = focusableElements.last();
564 if (target.is(firstFocusable) && e.shiftKey) {
565 lastFocusable.focus();
567 } else if (target.is(lastFocusable) && !e.shiftKey) {
568 firstFocusable.focus();
574 * Set up all of the event handling for the modal.
576 * @method registerEventListeners
578 Modal.prototype.registerEventListeners = function() {
579 this.getRoot().on('keydown', function(e) {
580 if (!this.isVisible()) {
584 if (e.keyCode == KeyCodes.tab) {
585 this.handleTabLock(e);
586 } else if (e.keyCode == KeyCodes.escape) {
591 CustomEvents.define(this.getModal(), [CustomEvents.events.activate]);
592 this.getModal().on(CustomEvents.events.activate, SELECTORS.HIDE, function(e, data) {
594 data.originalEvent.preventDefault();