MDL-62171 Theme boost: modal accessibility focus
[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',
f02e119a
SL
26 'core/custom_interaction_events', 'core/modal_backdrop', 'core/event', 'core/modal_events'],
27 function($, Templates, Notification, KeyCodes, CustomEvents, ModalBackdrop, Event, ModalEvents) {
2bcef559
RW
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
946f9d0a
RW
53 /**
54 * A counter that gets incremented for each modal created. This can be
55 * used to generate unique values for the modals.
56 */
57 var modalCounter = 0;
58
2bcef559
RW
59 /**
60 * Constructor for the Modal.
61 *
62 * @param {object} root The root jQuery element for the modal
63 */
64 var Modal = function(root) {
65 this.root = $(root);
66 this.modal = this.root.find(SELECTORS.MODAL);
67 this.header = this.modal.find(SELECTORS.HEADER);
68 this.title = this.header.find(SELECTORS.TITLE);
69 this.body = this.modal.find(SELECTORS.BODY);
70 this.footer = this.modal.find(SELECTORS.FOOTER);
71 this.hiddenSiblings = [];
72 this.isAttached = false;
73 this.bodyJS = null;
74 this.footerJS = null;
946f9d0a 75 this.modalCount = modalCounter++;
2bcef559
RW
76
77 if (!this.root.is(SELECTORS.CONTAINER)) {
78 Notification.exception({message: 'Element is not a modal container'});
79 }
80
81 if (!this.modal.length) {
82 Notification.exception({message: 'Container does not contain a modal'});
83 }
84
85 if (!this.header.length) {
86 Notification.exception({message: 'Modal is missing a header region'});
87 }
88
89 if (!this.title.length) {
90 Notification.exception({message: 'Modal header is missing a title region'});
91 }
92
93 if (!this.body.length) {
94 Notification.exception({message: 'Modal is missing a body region'});
95 }
96
97 if (!this.footer.length) {
98 Notification.exception({message: 'Modal is missing a footer region'});
99 }
100
101 this.registerEventListeners();
102 };
103
104 /**
105 * Add the modal to the page, if it hasn't already been added. This includes running any
106 * javascript that has been cached until now.
107 *
108 * @method attachToDOM
109 */
110 Modal.prototype.attachToDOM = function() {
111 if (this.isAttached) {
112 return;
113 }
114
115 $('body').append(this.root);
116
117 // If we'd cached any JS then we can run it how that the modal is
118 // attached to the DOM.
119 if (this.bodyJS) {
120 Templates.runTemplateJS(this.bodyJS);
121 this.bodyJS = null;
122 }
123
124 if (this.footerJS) {
125 Templates.runTemplateJS(this.footerJS);
126 this.footerJS = null;
127 }
128
129 this.isAttached = true;
130 };
131
132 /**
133 * Count the number of other visible modals (not including this one).
134 *
135 * @method countOtherVisibleModals
136 * @return {int}
137 */
138 Modal.prototype.countOtherVisibleModals = function() {
139 var count = 0;
140 $('body').find(SELECTORS.CONTAINER).each(function(index, element) {
141 element = $(element);
142
143 // If we haven't found ourself and the element is visible.
144 if (!this.root.is(element) && element.hasClass('show')) {
145 count++;
146 }
147 }.bind(this));
148
149 return count;
150 };
151
152 /**
153 * Get the modal backdrop.
154 *
155 * @method getBackdrop
156 * @return {object} jQuery promise
157 */
158 Modal.prototype.getBackdrop = function() {
159 if (!backdropPromise) {
160 backdropPromise = Templates.render(TEMPLATES.BACKDROP, {})
161 .then(function(html) {
162 var element = $(html);
163
164 return new ModalBackdrop(element);
165 })
166 .fail(Notification.exception);
167 }
168
169 return backdropPromise;
170 };
171
172 /**
173 * Get the root element of this modal.
174 *
175 * @method getRoot
176 * @return {object} jQuery object
177 */
178 Modal.prototype.getRoot = function() {
179 return this.root;
180 };
181
182 /**
183 * Get the modal element of this modal.
184 *
185 * @method getModal
186 * @return {object} jQuery object
187 */
188 Modal.prototype.getModal = function() {
189 return this.modal;
190 };
191
192 /**
193 * Get the modal title element.
194 *
195 * @method getTitle
196 * @return {object} jQuery object
197 */
198 Modal.prototype.getTitle = function() {
199 return this.title;
200 };
201
202 /**
203 * Get the modal body element.
204 *
205 * @method getBody
206 * @return {object} jQuery object
207 */
208 Modal.prototype.getBody = function() {
209 return this.body;
210 };
211
212 /**
213 * Get the modal footer element.
214 *
215 * @method getFooter
216 * @return {object} jQuery object
217 */
218 Modal.prototype.getFooter = function() {
219 return this.footer;
220 };
221
946f9d0a
RW
222 /**
223 * Get the unique modal count.
224 *
225 * @method getModalCount
226 * @return {int}
227 */
228 Modal.prototype.getModalCount = function() {
229 return this.modalCount;
230 };
231
2bcef559
RW
232 /**
233 * Set the modal title element.
234 *
e2b50304
AN
235 * This method is overloaded to take either a string value for the title or a jQuery promise that is resolved with
236 * HTML most commonly from a Str.get_string call.
237 *
2bcef559 238 * @method setTitle
e2b50304 239 * @param {(string|object)} value The title string or jQuery promise which resolves to the title.
2bcef559
RW
240 */
241 Modal.prototype.setTitle = function(value) {
242 var title = this.getTitle();
e2b50304
AN
243
244 this.asyncSet(value, title.html.bind(title));
2bcef559
RW
245 };
246
247 /**
248 * Set the modal body element.
249 *
e2b50304
AN
250 * This method is overloaded to take either a string value for the body or a jQuery promise that is resolved with
251 * HTML and Javascript most commonly from a Templates.render call.
2bcef559
RW
252 *
253 * @method setBody
e2b50304 254 * @param {(string|object)} value The body string or jQuery promise which resolves to the body.
2bcef559
RW
255 */
256 Modal.prototype.setBody = function(value) {
257 var body = this.getBody();
258
259 if (typeof value === 'string') {
260 // Just set the value if it's a string.
261 body.html(value);
f02e119a 262 Event.notifyFilterContentUpdated(body);
97c4a29d 263 this.getRoot().trigger(ModalEvents.bodyRendered, this);
2bcef559 264 } else {
946f9d0a
RW
265 var jsPendingId = 'amd-modal-js-pending-id-' + this.getModalCount();
266 M.util.js_pending(jsPendingId);
2bcef559
RW
267 // Otherwise we assume it's a promise to be resolved with
268 // html and javascript.
946f9d0a
RW
269 var contentPromise = null;
270 body.css('overflow', 'hidden');
271
272 if (value.state() == 'pending') {
273 // We're still waiting for the body promise to resolve so
274 // let's show a loading icon.
2328bccc
RW
275 var height = body.innerHeight();
276 if (height < 100) {
277 height = 100;
278 }
279
280 body.animate({height: height + 'px'}, 150);
946f9d0a
RW
281
282 body.html('');
283 contentPromise = Templates.render(TEMPLATES.LOADING, {})
284 .then(function(html) {
285 var loadingIcon = $(html).hide();
286 body.html(loadingIcon);
287 loadingIcon.fadeIn(150);
288
289 // We only want the loading icon to fade out
290 // when the content for the body has finished
291 // loading.
292 return $.when(loadingIcon.promise(), value);
293 })
294 .then(function(loadingIcon) {
295 // Once the content has finished loading and
296 // the loading icon has been shown then we can
297 // fade the icon away to reveal the content.
298 return loadingIcon.fadeOut(100).promise();
299 })
300 .then(function() {
301 return value;
302 });
303 } else {
304 // The content is already loaded so let's just display
305 // it to the user. No need for a loading icon.
306 contentPromise = value;
307 }
2bcef559 308
946f9d0a
RW
309 // Now we can actually display the content.
310 contentPromise.then(function(html, js) {
311 var result = null;
2bcef559 312
946f9d0a
RW
313 if (this.isVisible()) {
314 // If the modal is visible then we should display
315 // the content gracefully for the user.
316 body.css('opacity', 0);
317 var currentHeight = body.innerHeight();
318 body.html(html);
319 // We need to clear any height values we've set here
320 // in order to measure the height of the content being
321 // added. This then allows us to animate the height
322 // transition.
323 body.css('height', '');
324 var newHeight = body.innerHeight();
325 body.css('height', currentHeight + 'px');
326 result = body.animate(
327 {height: newHeight + 'px', opacity: 1},
328 {duration: 150, queue: false}
329 ).promise();
330 } else {
331 // Since the modal isn't visible we can just immediately
332 // set the content. No need to animate it.
333 body.html(html);
334 }
335
336 if (js) {
337 if (this.isAttached) {
338 // If we're in the DOM then run the JS immediately.
339 Templates.runTemplateJS(js);
340 } else {
341 // Otherwise cache it to be run when we're attached.
342 this.bodyJS = js;
2bcef559 343 }
946f9d0a
RW
344 }
345 Event.notifyFilterContentUpdated(body);
346 this.getRoot().trigger(ModalEvents.bodyRendered, this);
347
348 return result;
349 }.bind(this))
350 .fail(Notification.exception)
351 .always(function() {
352 // When we're done displaying all of the content we need
353 // to clear the custom values we've set here.
354 body.css('height', '');
355 body.css('overflow', '');
356 body.css('opacity', '');
357 M.util.js_complete(jsPendingId);
358
359 return;
4c250a5b
AN
360 })
361 .fail(Notification.exception);
2bcef559
RW
362 }
363 };
364
365 /**
368832d5
RW
366 * Set the modal footer element. The footer element is made visible, if it
367 * isn't already.
2bcef559
RW
368 *
369 * This method is overloaded to take either a string
370 * value for the body or a jQuery promise that is resolved with HTML and Javascript
371 * most commonly from a Templates.render call.
372 *
373 * @method setFooter
374 * @param {(string|object)} value The footer string or jQuery promise
375 */
376 Modal.prototype.setFooter = function(value) {
368832d5
RW
377 // Make sure the footer is visible.
378 this.showFooter();
379
2bcef559
RW
380 var footer = this.getFooter();
381
382 if (typeof value === 'string') {
383 // Just set the value if it's a string.
384 footer.html(value);
385 } else {
386 // Otherwise we assume it's a promise to be resolved with
387 // html and javascript.
388 Templates.render(TEMPLATES.LOADING, {}).done(function(html) {
389 footer.html(html);
390
391 value.done(function(html, js) {
392 footer.html(html);
393
10ea8270
RW
394 if (js) {
395 if (this.isAttached) {
396 // If we're in the DOM then run the JS immediately.
397 Templates.runTemplateJS(js);
398 } else {
399 // Otherwise cache it to be run when we're attached.
400 this.footerJS = js;
401 }
2bcef559
RW
402 }
403 }.bind(this));
404 }.bind(this));
405 }
406 };
407
368832d5
RW
408 /**
409 * Check if the footer has any content in it.
410 *
411 * @method hasFooterContent
412 * @return {bool}
413 */
414 Modal.prototype.hasFooterContent = function() {
415 return this.getFooter().children().length ? true : false;
416 };
417
418 /**
419 * Hide the footer element.
420 *
421 * @method hideFooter
422 */
423 Modal.prototype.hideFooter = function() {
424 this.getFooter().addClass('hidden');
425 };
426
427 /**
428 * Show the footer element.
429 *
430 * @method showFooter
431 */
432 Modal.prototype.showFooter = function() {
433 this.getFooter().removeClass('hidden');
434 };
435
2bcef559
RW
436 /**
437 * Mark the modal as a large modal.
438 *
439 * @method setLarge
440 */
441 Modal.prototype.setLarge = function() {
442 if (this.isLarge()) {
443 return;
444 }
445
4defa05f 446 this.getModal().addClass('modal-lg');
2bcef559
RW
447 };
448
449 /**
450 * Check if the modal is a large modal.
451 *
452 * @method isLarge
453 * @return {bool}
454 */
455 Modal.prototype.isLarge = function() {
4defa05f 456 return this.getModal().hasClass('modal-lg');
2bcef559
RW
457 };
458
459 /**
460 * Mark the modal as a small modal.
461 *
462 * @method setSmall
463 */
464 Modal.prototype.setSmall = function() {
465 if (this.isSmall()) {
466 return;
467 }
468
4defa05f 469 this.getModal().removeClass('modal-lg');
2bcef559
RW
470 };
471
472 /**
473 * Check if the modal is a small modal.
474 *
475 * @method isSmall
476 * @return {bool}
477 */
478 Modal.prototype.isSmall = function() {
4defa05f 479 return !this.getModal().hasClass('modal-lg');
2bcef559
RW
480 };
481
482 /**
483 * Determine the highest z-index value currently on the page.
484 *
485 * @method calculateZIndex
486 * @return {int}
487 */
488 Modal.prototype.calculateZIndex = function() {
489 var items = $(SELECTORS.DIALOG + ', ' + SELECTORS.MENU_BAR + ', ' + SELECTORS.HAS_Z_INDEX);
490 var zIndex = parseInt(this.root.css('z-index'));
491
492 items.each(function(index, item) {
493 item = $(item);
494 // Note that webkit browsers won't return the z-index value from the CSS stylesheet
495 // if the element doesn't have a position specified. Instead it'll return "auto".
496 var itemZIndex = item.css('z-index') ? parseInt(item.css('z-index')) : 0;
497
498 if (itemZIndex > zIndex) {
499 zIndex = itemZIndex;
500 }
501 });
502
503 return zIndex;
504 };
505
506 /**
507 * Check if this modal is visible.
508 *
509 * @method isVisible
510 * @return {bool}
511 */
512 Modal.prototype.isVisible = function() {
513 return this.root.hasClass('show');
514 };
515
516 /**
517 * Check if this modal has focus.
518 *
519 * @method hasFocus
520 * @return {bool}
521 */
522 Modal.prototype.hasFocus = function() {
523 var target = $(document.activeElement);
524 return this.root.is(target) || this.root.has(target).length;
525 };
526
527 /**
528 * Check if this modal has CSS transitions applied.
529 *
530 * @method hasTransitions
531 * @return {bool}
532 */
533 Modal.prototype.hasTransitions = function() {
534 return this.getRoot().hasClass('fade');
535 };
536
537 /**
538 * Display this modal. The modal will be attached to the DOM if it hasn't
539 * already been.
540 *
541 * @method show
542 */
543 Modal.prototype.show = function() {
544 if (this.isVisible()) {
545 return;
546 }
547
368832d5
RW
548 if (this.hasFooterContent()) {
549 this.showFooter();
550 } else {
551 this.hideFooter();
552 }
553
2bcef559
RW
554 if (!this.isAttached) {
555 this.attachToDOM();
556 }
557
558 this.getBackdrop().done(function(backdrop) {
559 var currentIndex = this.calculateZIndex();
560 var newIndex = currentIndex + 2;
561 var newBackdropIndex = newIndex - 1;
562 this.root.css('z-index', newIndex);
563 backdrop.setZIndex(newBackdropIndex);
564 backdrop.show();
565
566 this.root.removeClass('hide').addClass('show');
567 this.accessibilityShow();
ae0629d2 568 this.getModal().focus();
2bcef559
RW
569 $('body').addClass('modal-open');
570 this.root.trigger(ModalEvents.shown, this);
571 }.bind(this));
572 };
573
574 /**
575 * Hide this modal.
576 *
577 * @method hide
578 */
579 Modal.prototype.hide = function() {
580 if (!this.isVisible()) {
581 return;
582 }
583
584 this.getBackdrop().done(function(backdrop) {
585 if (!this.countOtherVisibleModals()) {
586 // Hide the backdrop if we're the last open modal.
587 backdrop.hide();
588 $('body').removeClass('modal-open');
589 }
590
591 var currentIndex = parseInt(this.root.css('z-index'));
592 this.root.css('z-index', '');
593 backdrop.setZIndex(currentIndex - 3);
594
595 this.accessibilityHide();
596
597 if (this.hasTransitions()) {
598 // Wait for CSS transitions to complete before hiding the element.
599 this.getRoot().one('transitionend webkitTransitionEnd oTransitionEnd', function() {
600 this.getRoot().removeClass('show').addClass('hide');
601 }.bind(this));
602 } else {
603 this.getRoot().removeClass('show').addClass('hide');
604 }
605
606 this.root.trigger(ModalEvents.hidden, this);
607 }.bind(this));
608 };
609
610 /**
611 * Remove this modal from the DOM.
612 *
613 * @method destroy
614 */
615 Modal.prototype.destroy = function() {
616 this.root.remove();
617 this.root.trigger(ModalEvents.destroyed, this);
618 };
619
620 /**
621 * Sets the appropriate aria attributes on this dialogue and the other
622 * elements in the DOM to ensure that screen readers are able to navigate
623 * the dialogue popup correctly.
624 *
625 * @method accessibilityShow
626 */
627 Modal.prototype.accessibilityShow = function() {
628 // We need to get a list containing each sibling element and the shallowest
629 // non-ancestral nodes in the DOM. We can shortcut this a little by leveraging
630 // the fact that this dialogue is always appended to the document body therefore
631 // it's siblings are the shallowest non-ancestral nodes. If that changes then
632 // this code should also be updated.
633 $('body').children().each(function(index, child) {
634 // Skip the current modal.
635 if (!this.root.is(child)) {
636 child = $(child);
637 var hidden = child.attr('aria-hidden');
638 // If they are already hidden we can ignore them.
639 if (hidden !== 'true') {
640 // Save their current state.
641 child.data('previous-aria-hidden', hidden);
642 this.hiddenSiblings.push(child);
643
644 // Hide this node from screen readers.
645 child.attr('aria-hidden', 'true');
646 }
647 }
648 }.bind(this));
649
650 // Make us visible to screen readers.
651 this.root.attr('aria-hidden', 'false');
652 };
653
654 /**
655 * Restores the aria visibility on the DOM elements changed when displaying
656 * the dialogue popup and makes the dialogue aria hidden to allow screen
657 * readers to navigate the main page correctly when the dialogue is closed.
658 *
659 * @method accessibilityHide
660 */
661 Modal.prototype.accessibilityHide = function() {
662 this.root.attr('aria-hidden', 'true');
663
664 // Restore the sibling nodes back to their original values.
665 $.each(this.hiddenSiblings, function(index, sibling) {
666 sibling = $(sibling);
667 var previousValue = sibling.data('previous-aria-hidden');
668 // If the element didn't previously have an aria-hidden attribute
669 // then we can just remove the one we set.
670 if (typeof previousValue == 'undefined') {
671 sibling.removeAttr('aria-hidden');
672 } else {
673 // Otherwise set it back to the old value (which will be false).
674 sibling.attr('aria-hidden', previousValue);
675 }
676 });
677
678 // Clear the cache. No longer need to store these.
679 this.hiddenSiblings = [];
680 };
681
682 /**
683 * Handle the tab event to lock focus within this modal.
684 *
685 * @method handleTabLock
686 * @param {event} e The tab key jQuery event
687 */
688 Modal.prototype.handleTabLock = function(e) {
689 if (!this.hasFocus()) {
690 return;
691 }
692
693 var target = $(document.activeElement);
694 var focusableElements = this.modal.find(SELECTORS.CAN_RECEIVE_FOCUS);
695 var firstFocusable = focusableElements.first();
696 var lastFocusable = focusableElements.last();
697
698 if (target.is(firstFocusable) && e.shiftKey) {
699 lastFocusable.focus();
700 e.preventDefault();
701 } else if (target.is(lastFocusable) && !e.shiftKey) {
702 firstFocusable.focus();
703 e.preventDefault();
704 }
705 };
706
707 /**
708 * Set up all of the event handling for the modal.
709 *
710 * @method registerEventListeners
711 */
712 Modal.prototype.registerEventListeners = function() {
713 this.getRoot().on('keydown', function(e) {
714 if (!this.isVisible()) {
715 return;
716 }
717
718 if (e.keyCode == KeyCodes.tab) {
719 this.handleTabLock(e);
720 } else if (e.keyCode == KeyCodes.escape) {
721 this.hide();
722 }
723 }.bind(this));
724
725 CustomEvents.define(this.getModal(), [CustomEvents.events.activate]);
726 this.getModal().on(CustomEvents.events.activate, SELECTORS.HIDE, function(e, data) {
727 this.hide();
728 data.originalEvent.preventDefault();
729 }.bind(this));
730 };
731
e2b50304
AN
732 /**
733 * Set or resolve and set the value using the function.
734 *
735 * @method asyncSet
736 * @param {(string|object)} value The string or jQuery promise.
737 * @param {function} setFunction The setter
738 * @return {Promise}
739 */
740 Modal.prototype.asyncSet = function(value, setFunction) {
741 var p = value;
e5bdf51c 742 if (typeof value !== 'object' || !value.hasOwnProperty('then')) {
e2b50304
AN
743 p = $.Deferred();
744 p.resolve(value);
745 }
746
747 p.then(function(content) {
748 setFunction(content);
749
750 return;
4c250a5b
AN
751 })
752 .fail(Notification.exception);
e2b50304
AN
753
754 return p;
755 };
756
2bcef559
RW
757 return Modal;
758});