/* * ngDialog - easy modals and popup windows * http://github.com/likeastore/ngDialog * (c) 2013-2015 MIT License, https://likeastore.com */ (function (root, factory) { if (typeof module !== 'undefined' && module.exports) { // CommonJS if (typeof angular === 'undefined') { factory(require('angular')); } else { factory(angular); } module.exports = 'ngDialog'; } else if (typeof define === 'function' && define.amd) { // AMD define(['angular'], factory); } else { // Global Variables factory(root.angular); } }(this, function (angular) { 'use strict'; var m = angular.module('ngDialog', []); var $el = angular.element; var isDef = angular.isDefined; var style = (document.body || document.documentElement).style; var animationEndSupport = isDef(style.animation) || isDef(style.WebkitAnimation) || isDef(style.MozAnimation) || isDef(style.MsAnimation) || isDef(style.OAnimation); var animationEndEvent = 'animationend webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend'; var focusableElementSelector = 'a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), iframe, object, embed, *[tabindex], *[contenteditable]'; var disabledAnimationClass = 'ngdialog-disabled-animation'; var forceElementsReload = { html: false, body: false }; var scopes = {}; var openIdStack = []; var activeBodyClasses = []; var keydownIsBound = false; var openOnePerName = false; var closeByNavigationDialogStack = []; var UI_ROUTER_VERSION_LEGACY = 'legacy'; var UI_ROUTER_VERSION_ONE_PLUS = '1.0.0+'; m.provider('ngDialog', function () { var defaults = this.defaults = { className: 'ngdialog-theme-default', appendClassName: '', disableAnimation: false, plain: false, showClose: true, closeByDocument: true, closeByEscape: true, closeByNavigation: false, appendTo: false, preCloseCallback: false, onOpenCallback: false, overlay: true, cache: true, trapFocus: true, preserveFocus: true, ariaAuto: true, ariaRole: null, ariaLabelledById: null, ariaLabelledBySelector: null, ariaDescribedById: null, ariaDescribedBySelector: null, bodyClassName: 'ngdialog-open', width: null, height: null }; this.setForceHtmlReload = function (_useIt) { forceElementsReload.html = _useIt || false; }; this.setForceBodyReload = function (_useIt) { forceElementsReload.body = _useIt || false; }; this.setDefaults = function (newDefaults) { angular.extend(defaults, newDefaults); }; this.setOpenOnePerName = function (isOpenOne) { openOnePerName = isOpenOne || false; }; var globalID = 0, dialogsCount = 0, closeByDocumentHandler, defers = {}; this.$get = ['$document', '$templateCache', '$compile', '$q', '$http', '$rootScope', '$timeout', '$window', '$controller', '$injector', function ($document, $templateCache, $compile, $q, $http, $rootScope, $timeout, $window, $controller, $injector) { var $elements = []; var privateMethods = { onDocumentKeydown: function (event) { if (event.keyCode === 27) { publicMethods.close('$escape'); } }, activate: function($dialog) { var options = $dialog.data('$ngDialogOptions'); if (options.trapFocus) { $dialog.on('keydown', privateMethods.onTrapFocusKeydown); // Catch rogue changes (eg. after unfocusing everything by clicking a non-focusable element) $elements.body.on('keydown', privateMethods.onTrapFocusKeydown); } }, deactivate: function ($dialog) { $dialog.off('keydown', privateMethods.onTrapFocusKeydown); $elements.body.off('keydown', privateMethods.onTrapFocusKeydown); }, deactivateAll: function (els) { angular.forEach(els,function(el) { var $dialog = angular.element(el); privateMethods.deactivate($dialog); }); }, setBodyPadding: function (width) { var originalBodyPadding = parseInt(($elements.body.css('padding-right') || 0), 10); $elements.body.css('padding-right', (originalBodyPadding + width) + 'px'); $elements.body.data('ng-dialog-original-padding', originalBodyPadding); $rootScope.$broadcast('ngDialog.setPadding', width); }, resetBodyPadding: function () { var originalBodyPadding = $elements.body.data('ng-dialog-original-padding'); if (originalBodyPadding) { $elements.body.css('padding-right', originalBodyPadding + 'px'); } else { $elements.body.css('padding-right', ''); } $rootScope.$broadcast('ngDialog.setPadding', 0); }, performCloseDialog: function ($dialog, value) { var options = $dialog.data('$ngDialogOptions'); var id = $dialog.attr('id'); var scope = scopes[id]; privateMethods.deactivate($dialog); if (!scope) { // Already closed return; } if (typeof $window.Hammer !== 'undefined') { var hammerTime = scope.hammerTime; hammerTime.off('tap', closeByDocumentHandler); hammerTime.destroy && hammerTime.destroy(); delete scope.hammerTime; } else { $dialog.unbind('click'); } if (dialogsCount === 1) { $elements.body.unbind('keydown', privateMethods.onDocumentKeydown); } if (!$dialog.hasClass('ngdialog-closing')){ dialogsCount -= 1; } var previousFocus = $dialog.data('$ngDialogPreviousFocus'); if (previousFocus && previousFocus.focus) { previousFocus.focus(); } $rootScope.$broadcast('ngDialog.closing', $dialog, value); dialogsCount = dialogsCount < 0 ? 0 : dialogsCount; if (animationEndSupport && !options.disableAnimation) { scope.$destroy(); $dialog.unbind(animationEndEvent).bind(animationEndEvent, function () { privateMethods.closeDialogElement($dialog, value); }).addClass('ngdialog-closing'); } else { scope.$destroy(); privateMethods.closeDialogElement($dialog, value); } if (defers[id]) { defers[id].resolve({ id: id, value: value, $dialog: $dialog, remainingDialogs: dialogsCount }); delete defers[id]; } if (scopes[id]) { delete scopes[id]; } openIdStack.splice(openIdStack.indexOf(id), 1); if (!openIdStack.length) { $elements.body.unbind('keydown', privateMethods.onDocumentKeydown); keydownIsBound = false; } if (dialogsCount == 0) { closeByDocumentHandler = undefined; } }, closeDialogElement: function($dialog, value) { var options = $dialog.data('$ngDialogOptions'); $dialog.remove(); activeBodyClasses.splice(activeBodyClasses.indexOf(options.bodyClassName), 1); if (activeBodyClasses.indexOf(options.bodyClassName) === -1) { $elements.html.removeClass(options.bodyClassName); $elements.body.removeClass(options.bodyClassName); } if (dialogsCount === 0) { privateMethods.resetBodyPadding(); } $rootScope.$broadcast('ngDialog.closed', $dialog, value); }, closeDialog: function ($dialog, value) { var preCloseCallback = $dialog.data('$ngDialogPreCloseCallback'); if (preCloseCallback && angular.isFunction(preCloseCallback)) { var preCloseCallbackResult = preCloseCallback.call($dialog, value); if (angular.isObject(preCloseCallbackResult)) { if (preCloseCallbackResult.closePromise) { preCloseCallbackResult.closePromise.then(function () { privateMethods.performCloseDialog($dialog, value); }, function () { return false; }); } else { preCloseCallbackResult.then(function () { privateMethods.performCloseDialog($dialog, value); }, function () { return false; }); } } else if (preCloseCallbackResult !== false) { privateMethods.performCloseDialog($dialog, value); } else { return false; } } else { privateMethods.performCloseDialog($dialog, value); } }, onTrapFocusKeydown: function(ev) { var el = angular.element(ev.currentTarget); var $dialog; if (el.hasClass('ngdialog')) { $dialog = el; } else { $dialog = privateMethods.getActiveDialog(); if ($dialog === null) { return; } } var isTab = (ev.keyCode === 9); var backward = (ev.shiftKey === true); if (isTab) { privateMethods.handleTab($dialog, ev, backward); } }, handleTab: function($dialog, ev, backward) { var focusableElements = privateMethods.getFocusableElements($dialog); if (focusableElements.length === 0) { if (document.activeElement && document.activeElement.blur) { document.activeElement.blur(); } return; } var currentFocus = document.activeElement; var focusIndex = Array.prototype.indexOf.call(focusableElements, currentFocus); var isFocusIndexUnknown = (focusIndex === -1); var isFirstElementFocused = (focusIndex === 0); var isLastElementFocused = (focusIndex === focusableElements.length - 1); var cancelEvent = false; if (backward) { if (isFocusIndexUnknown || isFirstElementFocused) { focusableElements[focusableElements.length - 1].focus(); cancelEvent = true; } } else { if (isFocusIndexUnknown || isLastElementFocused) { focusableElements[0].focus(); cancelEvent = true; } } if (cancelEvent) { ev.preventDefault(); ev.stopPropagation(); } }, autoFocus: function($dialog) { var dialogEl = $dialog[0]; // Browser's (Chrome 40, Forefix 37, IE 11) don't appear to honor autofocus on the dialog, but we should var autoFocusEl = dialogEl.querySelector('*[autofocus]'); if (autoFocusEl !== null) { autoFocusEl.focus(); if (document.activeElement === autoFocusEl) { return; } // Autofocus element might was display: none, so let's continue } var focusableElements = privateMethods.getFocusableElements($dialog); if (focusableElements.length > 0) { focusableElements[0].focus(); return; } // We need to focus something for the screen readers to notice the dialog var contentElements = privateMethods.filterVisibleElements(dialogEl.querySelectorAll('h1,h2,h3,h4,h5,h6,p,span')); if (contentElements.length > 0) { var contentElement = contentElements[0]; $el(contentElement).attr('tabindex', '-1').css('outline', '0'); contentElement.focus(); } }, getFocusableElements: function ($dialog) { var dialogEl = $dialog[0]; var rawElements = dialogEl.querySelectorAll(focusableElementSelector); // Ignore untabbable elements, ie. those with tabindex = -1 var tabbableElements = privateMethods.filterTabbableElements(rawElements); return privateMethods.filterVisibleElements(tabbableElements); }, filterTabbableElements: function (els) { var tabbableFocusableElements = []; for (var i = 0; i < els.length; i++) { var el = els[i]; if ($el(el).attr('tabindex') !== '-1') { tabbableFocusableElements.push(el); } } return tabbableFocusableElements; }, filterVisibleElements: function (els) { var visibleFocusableElements = []; for (var i = 0; i < els.length; i++) { var el = els[i]; if (el.offsetWidth > 0 || el.offsetHeight > 0) { visibleFocusableElements.push(el); } } return visibleFocusableElements; }, getActiveDialog: function () { var dialogs = document.querySelectorAll('.ngdialog'); if (dialogs.length === 0) { return null; } // TODO: This might be incorrect if there are a mix of open dialogs with different 'appendTo' values return $el(dialogs[dialogs.length - 1]); }, applyAriaAttributes: function ($dialog, options) { if (options.ariaAuto) { if (!options.ariaRole) { var detectedRole = (privateMethods.getFocusableElements($dialog).length > 0) ? 'dialog' : 'alertdialog'; options.ariaRole = detectedRole; } if (!options.ariaLabelledBySelector) { options.ariaLabelledBySelector = 'h1,h2,h3,h4,h5,h6'; } if (!options.ariaDescribedBySelector) { options.ariaDescribedBySelector = 'article,section,p'; } } if (options.ariaRole) { $dialog.attr('role', options.ariaRole); } privateMethods.applyAriaAttribute( $dialog, 'aria-labelledby', options.ariaLabelledById, options.ariaLabelledBySelector); privateMethods.applyAriaAttribute( $dialog, 'aria-describedby', options.ariaDescribedById, options.ariaDescribedBySelector); }, applyAriaAttribute: function($dialog, attr, id, selector) { if (id) { $dialog.attr(attr, id); return; } if (selector) { var dialogId = $dialog.attr('id'); var firstMatch = $dialog[0].querySelector(selector); if (!firstMatch) { return; } var generatedId = dialogId + '-' + attr; $el(firstMatch).attr('id', generatedId); $dialog.attr(attr, generatedId); return generatedId; } }, detectUIRouter: function() { // Detect if ui-router module is installed // Returns ui-router version string if installed // Otherwise false if ($injector.has('$transitions')) { // Only 1.0.0+ ui.router allows us to inject $transitions return UI_ROUTER_VERSION_ONE_PLUS; } else if ($injector.has('$state')) { // The legacy ui.router allows us to inject $state return UI_ROUTER_VERSION_LEGACY; } return false; }, getRouterLocationEventName: function() { if (privateMethods.detectUIRouter()) { return '$stateChangeStart'; } return '$locationChangeStart'; } }; var publicMethods = { __PRIVATE__: privateMethods, /* * @param {Object} options: * - template {String} - id of ng-template, url for partial, plain string (if enabled) * - plain {Boolean} - enable plain string templates, default false * - scope {Object} * - controller {String} * - controllerAs {String} * - className {String} - dialog theme class * - appendClassName {String} - dialog theme class to be appended to defaults * - disableAnimation {Boolean} - set to true to disable animation * - showClose {Boolean} - show close button, default true * - closeByEscape {Boolean} - default true * - closeByDocument {Boolean} - default true * - preCloseCallback {String|Function} - user supplied function name/function called before closing dialog (if set) * - onOpenCallback {String|Function} - user supplied function name/function called after opening dialog (if set) * - bodyClassName {String} - class added to body at open dialog * @return {Object} dialog */ open: function (opts) { var dialogID = null; opts = opts || {}; if (openOnePerName && opts.name) { dialogID = opts.name.toLowerCase().replace(/\s/g, '-') + '-dialog'; if (this.isOpen(dialogID)) { return; } } var options = angular.copy(defaults); var localID = ++globalID; dialogID = dialogID || 'ngdialog' + localID; openIdStack.push(dialogID); // Merge opts.data with predefined via setDefaults if (typeof options.data !== 'undefined') { if (typeof opts.data === 'undefined') { opts.data = {}; } opts.data = angular.merge(angular.copy(options.data), opts.data); } angular.extend(options, opts); var defer; defers[dialogID] = defer = $q.defer(); var scope; scopes[dialogID] = scope = angular.isObject(options.scope) ? options.scope.$new() : $rootScope.$new(); var $dialog, $dialogParent, $dialogContent; var resolve = angular.extend({}, options.resolve); angular.forEach(resolve, function (value, key) { resolve[key] = angular.isString(value) ? $injector.get(value) : $injector.invoke(value, null, null, key); }); $q.all({ template: loadTemplate(options.template || options.templateUrl), locals: $q.all(resolve) }).then(function (setup) { var template = setup.template, locals = setup.locals; if (options.showClose) { template += ''; } var hasOverlayClass = options.overlay ? '' : ' ngdialog-no-overlay'; $dialog = $el('
'); $dialog.html((options.overlay ? '