on-demand release 3.4beta+
[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.
275 body.animate({height: '100px'}, 150);
276
277 body.html('');
278 contentPromise = Templates.render(TEMPLATES.LOADING, {})
279 .then(function(html) {
280 var loadingIcon = $(html).hide();
281 body.html(loadingIcon);
282 loadingIcon.fadeIn(150);
283
284 // We only want the loading icon to fade out
285 // when the content for the body has finished
286 // loading.
287 return $.when(loadingIcon.promise(), value);
288 })
289 .then(function(loadingIcon) {
290 // Once the content has finished loading and
291 // the loading icon has been shown then we can
292 // fade the icon away to reveal the content.
293 return loadingIcon.fadeOut(100).promise();
294 })
295 .then(function() {
296 return value;
297 });
298 } else {
299 // The content is already loaded so let's just display
300 // it to the user. No need for a loading icon.
301 contentPromise = value;
302 }
2bcef559 303
946f9d0a
RW
304 // Now we can actually display the content.
305 contentPromise.then(function(html, js) {
306 var result = null;
2bcef559 307
946f9d0a
RW
308 if (this.isVisible()) {
309 // If the modal is visible then we should display
310 // the content gracefully for the user.
311 body.css('opacity', 0);
312 var currentHeight = body.innerHeight();
313 body.html(html);
314 // We need to clear any height values we've set here
315 // in order to measure the height of the content being
316 // added. This then allows us to animate the height
317 // transition.
318 body.css('height', '');
319 var newHeight = body.innerHeight();
320 body.css('height', currentHeight + 'px');
321 result = body.animate(
322 {height: newHeight + 'px', opacity: 1},
323 {duration: 150, queue: false}
324 ).promise();
325 } else {
326 // Since the modal isn't visible we can just immediately
327 // set the content. No need to animate it.
328 body.html(html);
329 }
330
331 if (js) {
332 if (this.isAttached) {
333 // If we're in the DOM then run the JS immediately.
334 Templates.runTemplateJS(js);
335 } else {
336 // Otherwise cache it to be run when we're attached.
337 this.bodyJS = js;
2bcef559 338 }
946f9d0a
RW
339 }
340 Event.notifyFilterContentUpdated(body);
341 this.getRoot().trigger(ModalEvents.bodyRendered, this);
342
343 return result;
344 }.bind(this))
345 .fail(Notification.exception)
346 .always(function() {
347 // When we're done displaying all of the content we need
348 // to clear the custom values we've set here.
349 body.css('height', '');
350 body.css('overflow', '');
351 body.css('opacity', '');
352 M.util.js_complete(jsPendingId);
353
354 return;
4c250a5b
AN
355 })
356 .fail(Notification.exception);
2bcef559
RW
357 }
358 };
359
360 /**
361 * Set the modal footer element.
362 *
363 * This method is overloaded to take either a string
364 * value for the body or a jQuery promise that is resolved with HTML and Javascript
365 * most commonly from a Templates.render call.
366 *
367 * @method setFooter
368 * @param {(string|object)} value The footer string or jQuery promise
369 */
370 Modal.prototype.setFooter = function(value) {
371 var footer = this.getFooter();
372
373 if (typeof value === 'string') {
374 // Just set the value if it's a string.
375 footer.html(value);
376 } else {
377 // Otherwise we assume it's a promise to be resolved with
378 // html and javascript.
379 Templates.render(TEMPLATES.LOADING, {}).done(function(html) {
380 footer.html(html);
381
382 value.done(function(html, js) {
383 footer.html(html);
384
10ea8270
RW
385 if (js) {
386 if (this.isAttached) {
387 // If we're in the DOM then run the JS immediately.
388 Templates.runTemplateJS(js);
389 } else {
390 // Otherwise cache it to be run when we're attached.
391 this.footerJS = js;
392 }
2bcef559
RW
393 }
394 }.bind(this));
395 }.bind(this));
396 }
397 };
398
399 /**
400 * Mark the modal as a large modal.
401 *
402 * @method setLarge
403 */
404 Modal.prototype.setLarge = function() {
405 if (this.isLarge()) {
406 return;
407 }
408
4defa05f 409 this.getModal().addClass('modal-lg');
2bcef559
RW
410 };
411
412 /**
413 * Check if the modal is a large modal.
414 *
415 * @method isLarge
416 * @return {bool}
417 */
418 Modal.prototype.isLarge = function() {
4defa05f 419 return this.getModal().hasClass('modal-lg');
2bcef559
RW
420 };
421
422 /**
423 * Mark the modal as a small modal.
424 *
425 * @method setSmall
426 */
427 Modal.prototype.setSmall = function() {
428 if (this.isSmall()) {
429 return;
430 }
431
4defa05f 432 this.getModal().removeClass('modal-lg');
2bcef559
RW
433 };
434
435 /**
436 * Check if the modal is a small modal.
437 *
438 * @method isSmall
439 * @return {bool}
440 */
441 Modal.prototype.isSmall = function() {
4defa05f 442 return !this.getModal().hasClass('modal-lg');
2bcef559
RW
443 };
444
445 /**
446 * Determine the highest z-index value currently on the page.
447 *
448 * @method calculateZIndex
449 * @return {int}
450 */
451 Modal.prototype.calculateZIndex = function() {
452 var items = $(SELECTORS.DIALOG + ', ' + SELECTORS.MENU_BAR + ', ' + SELECTORS.HAS_Z_INDEX);
453 var zIndex = parseInt(this.root.css('z-index'));
454
455 items.each(function(index, item) {
456 item = $(item);
457 // Note that webkit browsers won't return the z-index value from the CSS stylesheet
458 // if the element doesn't have a position specified. Instead it'll return "auto".
459 var itemZIndex = item.css('z-index') ? parseInt(item.css('z-index')) : 0;
460
461 if (itemZIndex > zIndex) {
462 zIndex = itemZIndex;
463 }
464 });
465
466 return zIndex;
467 };
468
469 /**
470 * Check if this modal is visible.
471 *
472 * @method isVisible
473 * @return {bool}
474 */
475 Modal.prototype.isVisible = function() {
476 return this.root.hasClass('show');
477 };
478
479 /**
480 * Check if this modal has focus.
481 *
482 * @method hasFocus
483 * @return {bool}
484 */
485 Modal.prototype.hasFocus = function() {
486 var target = $(document.activeElement);
487 return this.root.is(target) || this.root.has(target).length;
488 };
489
490 /**
491 * Check if this modal has CSS transitions applied.
492 *
493 * @method hasTransitions
494 * @return {bool}
495 */
496 Modal.prototype.hasTransitions = function() {
497 return this.getRoot().hasClass('fade');
498 };
499
500 /**
501 * Display this modal. The modal will be attached to the DOM if it hasn't
502 * already been.
503 *
504 * @method show
505 */
506 Modal.prototype.show = function() {
507 if (this.isVisible()) {
508 return;
509 }
510
511 if (!this.isAttached) {
512 this.attachToDOM();
513 }
514
515 this.getBackdrop().done(function(backdrop) {
516 var currentIndex = this.calculateZIndex();
517 var newIndex = currentIndex + 2;
518 var newBackdropIndex = newIndex - 1;
519 this.root.css('z-index', newIndex);
520 backdrop.setZIndex(newBackdropIndex);
521 backdrop.show();
522
523 this.root.removeClass('hide').addClass('show');
524 this.accessibilityShow();
525 this.getTitle().focus();
526 $('body').addClass('modal-open');
527 this.root.trigger(ModalEvents.shown, this);
528 }.bind(this));
529 };
530
531 /**
532 * Hide this modal.
533 *
534 * @method hide
535 */
536 Modal.prototype.hide = function() {
537 if (!this.isVisible()) {
538 return;
539 }
540
541 this.getBackdrop().done(function(backdrop) {
542 if (!this.countOtherVisibleModals()) {
543 // Hide the backdrop if we're the last open modal.
544 backdrop.hide();
545 $('body').removeClass('modal-open');
546 }
547
548 var currentIndex = parseInt(this.root.css('z-index'));
549 this.root.css('z-index', '');
550 backdrop.setZIndex(currentIndex - 3);
551
552 this.accessibilityHide();
553
554 if (this.hasTransitions()) {
555 // Wait for CSS transitions to complete before hiding the element.
556 this.getRoot().one('transitionend webkitTransitionEnd oTransitionEnd', function() {
557 this.getRoot().removeClass('show').addClass('hide');
558 }.bind(this));
559 } else {
560 this.getRoot().removeClass('show').addClass('hide');
561 }
562
563 this.root.trigger(ModalEvents.hidden, this);
564 }.bind(this));
565 };
566
567 /**
568 * Remove this modal from the DOM.
569 *
570 * @method destroy
571 */
572 Modal.prototype.destroy = function() {
573 this.root.remove();
574 this.root.trigger(ModalEvents.destroyed, this);
575 };
576
577 /**
578 * Sets the appropriate aria attributes on this dialogue and the other
579 * elements in the DOM to ensure that screen readers are able to navigate
580 * the dialogue popup correctly.
581 *
582 * @method accessibilityShow
583 */
584 Modal.prototype.accessibilityShow = function() {
585 // We need to get a list containing each sibling element and the shallowest
586 // non-ancestral nodes in the DOM. We can shortcut this a little by leveraging
587 // the fact that this dialogue is always appended to the document body therefore
588 // it's siblings are the shallowest non-ancestral nodes. If that changes then
589 // this code should also be updated.
590 $('body').children().each(function(index, child) {
591 // Skip the current modal.
592 if (!this.root.is(child)) {
593 child = $(child);
594 var hidden = child.attr('aria-hidden');
595 // If they are already hidden we can ignore them.
596 if (hidden !== 'true') {
597 // Save their current state.
598 child.data('previous-aria-hidden', hidden);
599 this.hiddenSiblings.push(child);
600
601 // Hide this node from screen readers.
602 child.attr('aria-hidden', 'true');
603 }
604 }
605 }.bind(this));
606
607 // Make us visible to screen readers.
608 this.root.attr('aria-hidden', 'false');
609 };
610
611 /**
612 * Restores the aria visibility on the DOM elements changed when displaying
613 * the dialogue popup and makes the dialogue aria hidden to allow screen
614 * readers to navigate the main page correctly when the dialogue is closed.
615 *
616 * @method accessibilityHide
617 */
618 Modal.prototype.accessibilityHide = function() {
619 this.root.attr('aria-hidden', 'true');
620
621 // Restore the sibling nodes back to their original values.
622 $.each(this.hiddenSiblings, function(index, sibling) {
623 sibling = $(sibling);
624 var previousValue = sibling.data('previous-aria-hidden');
625 // If the element didn't previously have an aria-hidden attribute
626 // then we can just remove the one we set.
627 if (typeof previousValue == 'undefined') {
628 sibling.removeAttr('aria-hidden');
629 } else {
630 // Otherwise set it back to the old value (which will be false).
631 sibling.attr('aria-hidden', previousValue);
632 }
633 });
634
635 // Clear the cache. No longer need to store these.
636 this.hiddenSiblings = [];
637 };
638
639 /**
640 * Handle the tab event to lock focus within this modal.
641 *
642 * @method handleTabLock
643 * @param {event} e The tab key jQuery event
644 */
645 Modal.prototype.handleTabLock = function(e) {
646 if (!this.hasFocus()) {
647 return;
648 }
649
650 var target = $(document.activeElement);
651 var focusableElements = this.modal.find(SELECTORS.CAN_RECEIVE_FOCUS);
652 var firstFocusable = focusableElements.first();
653 var lastFocusable = focusableElements.last();
654
655 if (target.is(firstFocusable) && e.shiftKey) {
656 lastFocusable.focus();
657 e.preventDefault();
658 } else if (target.is(lastFocusable) && !e.shiftKey) {
659 firstFocusable.focus();
660 e.preventDefault();
661 }
662 };
663
664 /**
665 * Set up all of the event handling for the modal.
666 *
667 * @method registerEventListeners
668 */
669 Modal.prototype.registerEventListeners = function() {
670 this.getRoot().on('keydown', function(e) {
671 if (!this.isVisible()) {
672 return;
673 }
674
675 if (e.keyCode == KeyCodes.tab) {
676 this.handleTabLock(e);
677 } else if (e.keyCode == KeyCodes.escape) {
678 this.hide();
679 }
680 }.bind(this));
681
682 CustomEvents.define(this.getModal(), [CustomEvents.events.activate]);
683 this.getModal().on(CustomEvents.events.activate, SELECTORS.HIDE, function(e, data) {
684 this.hide();
685 data.originalEvent.preventDefault();
686 }.bind(this));
687 };
688
e2b50304
AN
689 /**
690 * Set or resolve and set the value using the function.
691 *
692 * @method asyncSet
693 * @param {(string|object)} value The string or jQuery promise.
694 * @param {function} setFunction The setter
695 * @return {Promise}
696 */
697 Modal.prototype.asyncSet = function(value, setFunction) {
698 var p = value;
e5bdf51c 699 if (typeof value !== 'object' || !value.hasOwnProperty('then')) {
e2b50304
AN
700 p = $.Deferred();
701 p.resolve(value);
702 }
703
704 p.then(function(content) {
705 setFunction(content);
706
707 return;
4c250a5b
AN
708 })
709 .fail(Notification.exception);
e2b50304
AN
710
711 return p;
712 };
713
2bcef559
RW
714 return Modal;
715});