dialog.js 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892
  1. /*!
  2. * Angular Material Design
  3. * https://github.com/angular/material
  4. * @license MIT
  5. * v0.11.4
  6. */
  7. (function( window, angular, undefined ){
  8. "use strict";
  9. /**
  10. * @ngdoc module
  11. * @name material.components.dialog
  12. */
  13. angular
  14. .module('material.components.dialog', [
  15. 'material.core',
  16. 'material.components.backdrop'
  17. ])
  18. .directive('mdDialog', MdDialogDirective)
  19. .provider('$mdDialog', MdDialogProvider);
  20. function MdDialogDirective($$rAF, $mdTheming, $mdDialog) {
  21. return {
  22. restrict: 'E',
  23. link: function(scope, element, attr) {
  24. $mdTheming(element);
  25. $$rAF(function() {
  26. var images;
  27. var content = element[0].querySelector('md-dialog-content');
  28. if (content) {
  29. images = content.getElementsByTagName('img');
  30. addOverflowClass();
  31. //-- delayed image loading may impact scroll height, check after images are loaded
  32. angular.element(images).on('load', addOverflowClass);
  33. }
  34. scope.$on('$destroy', function() {
  35. $mdDialog.destroy();
  36. });
  37. /**
  38. *
  39. */
  40. function addOverflowClass() {
  41. element.toggleClass('md-content-overflow', content.scrollHeight > content.clientHeight);
  42. }
  43. });
  44. }
  45. };
  46. }
  47. MdDialogDirective.$inject = ["$$rAF", "$mdTheming", "$mdDialog"];
  48. /**
  49. * @ngdoc service
  50. * @name $mdDialog
  51. * @module material.components.dialog
  52. *
  53. * @description
  54. * `$mdDialog` opens a dialog over the app to inform users about critical information or require
  55. * them to make decisions. There are two approaches for setup: a simple promise API
  56. * and regular object syntax.
  57. *
  58. * ## Restrictions
  59. *
  60. * - The dialog is always given an isolate scope.
  61. * - The dialog's template must have an outer `<md-dialog>` element.
  62. * Inside, use an `<md-dialog-content>` element for the dialog's content, and use
  63. * an element with class `md-actions` for the dialog's actions.
  64. * - Dialogs must cover the entire application to keep interactions inside of them.
  65. * Use the `parent` option to change where dialogs are appended.
  66. *
  67. * ## Sizing
  68. * - Complex dialogs can be sized with `flex="percentage"`, i.e. `flex="66"`.
  69. * - Default max-width is 80% of the `rootElement` or `parent`.
  70. *
  71. * ## Css
  72. * - `.md-dialog-content` - class that sets the padding on the content as the spec file
  73. *
  74. * @usage
  75. * <hljs lang="html">
  76. * <div ng-app="demoApp" ng-controller="EmployeeController">
  77. * <div>
  78. * <md-button ng-click="showAlert()" class="md-raised md-warn">
  79. * Employee Alert!
  80. * </md-button>
  81. * </div>
  82. * <div>
  83. * <md-button ng-click="showDialog($event)" class="md-raised">
  84. * Custom Dialog
  85. * </md-button>
  86. * </div>
  87. * <div>
  88. * <md-button ng-click="closeAlert()" ng-disabled="!hasAlert()" class="md-raised">
  89. * Close Alert
  90. * </md-button>
  91. * </div>
  92. * <div>
  93. * <md-button ng-click="showGreeting($event)" class="md-raised md-primary" >
  94. * Greet Employee
  95. * </md-button>
  96. * </div>
  97. * </div>
  98. * </hljs>
  99. *
  100. * ### JavaScript: object syntax
  101. * <hljs lang="js">
  102. * (function(angular, undefined){
  103. * "use strict";
  104. *
  105. * angular
  106. * .module('demoApp', ['ngMaterial'])
  107. * .controller('AppCtrl', AppController);
  108. *
  109. * function AppController($scope, $mdDialog) {
  110. * var alert;
  111. * $scope.showAlert = showAlert;
  112. * $scope.showDialog = showDialog;
  113. * $scope.items = [1, 2, 3];
  114. *
  115. * // Internal method
  116. * function showAlert() {
  117. * alert = $mdDialog.alert({
  118. * title: 'Attention',
  119. * content: 'This is an example of how easy dialogs can be!',
  120. * ok: 'Close'
  121. * });
  122. *
  123. * $mdDialog
  124. * .show( alert )
  125. * .finally(function() {
  126. * alert = undefined;
  127. * });
  128. * }
  129. *
  130. * function showDialog($event) {
  131. * var parentEl = angular.element(document.body);
  132. * $mdDialog.show({
  133. * parent: parentEl,
  134. * targetEvent: $event,
  135. * template:
  136. * '<md-dialog aria-label="List dialog">' +
  137. * ' <md-dialog-content>'+
  138. * ' <md-list>'+
  139. * ' <md-list-item ng-repeat="item in items">'+
  140. * ' <p>Number {{item}}</p>' +
  141. * ' </md-item>'+
  142. * ' </md-list>'+
  143. * ' </md-dialog-content>' +
  144. * ' <div class="md-actions">' +
  145. * ' <md-button ng-click="closeDialog()" class="md-primary">' +
  146. * ' Close Dialog' +
  147. * ' </md-button>' +
  148. * ' </div>' +
  149. * '</md-dialog>',
  150. * locals: {
  151. * items: $scope.items
  152. * },
  153. * controller: DialogController
  154. * });
  155. * function DialogController($scope, $mdDialog, items) {
  156. * $scope.items = items;
  157. * $scope.closeDialog = function() {
  158. * $mdDialog.hide();
  159. * }
  160. * }
  161. * }
  162. * }
  163. * })(angular);
  164. * </hljs>
  165. *
  166. * ### JavaScript: promise API syntax, custom dialog template
  167. * <hljs lang="js">
  168. * (function(angular, undefined){
  169. * "use strict";
  170. *
  171. * angular
  172. * .module('demoApp', ['ngMaterial'])
  173. * .controller('EmployeeController', EmployeeEditor)
  174. * .controller('GreetingController', GreetingController);
  175. *
  176. * // Fictitious Employee Editor to show how to use simple and complex dialogs.
  177. *
  178. * function EmployeeEditor($scope, $mdDialog) {
  179. * var alert;
  180. *
  181. * $scope.showAlert = showAlert;
  182. * $scope.closeAlert = closeAlert;
  183. * $scope.showGreeting = showCustomGreeting;
  184. *
  185. * $scope.hasAlert = function() { return !!alert };
  186. * $scope.userName = $scope.userName || 'Bobby';
  187. *
  188. * // Dialog #1 - Show simple alert dialog and cache
  189. * // reference to dialog instance
  190. *
  191. * function showAlert() {
  192. * alert = $mdDialog.alert()
  193. * .title('Attention, ' + $scope.userName)
  194. * .content('This is an example of how easy dialogs can be!')
  195. * .ok('Close');
  196. *
  197. * $mdDialog
  198. * .show( alert )
  199. * .finally(function() {
  200. * alert = undefined;
  201. * });
  202. * }
  203. *
  204. * // Close the specified dialog instance and resolve with 'finished' flag
  205. * // Normally this is not needed, just use '$mdDialog.hide()' to close
  206. * // the most recent dialog popup.
  207. *
  208. * function closeAlert() {
  209. * $mdDialog.hide( alert, "finished" );
  210. * alert = undefined;
  211. * }
  212. *
  213. * // Dialog #2 - Demonstrate more complex dialogs construction and popup.
  214. *
  215. * function showCustomGreeting($event) {
  216. * $mdDialog.show({
  217. * targetEvent: $event,
  218. * template:
  219. * '<md-dialog>' +
  220. *
  221. * ' <md-dialog-content>Hello {{ employee }}!</md-dialog-content>' +
  222. *
  223. * ' <div class="md-actions">' +
  224. * ' <md-button ng-click="closeDialog()" class="md-primary">' +
  225. * ' Close Greeting' +
  226. * ' </md-button>' +
  227. * ' </div>' +
  228. * '</md-dialog>',
  229. * controller: 'GreetingController',
  230. * onComplete: afterShowAnimation,
  231. * locals: { employee: $scope.userName }
  232. * });
  233. *
  234. * // When the 'enter' animation finishes...
  235. *
  236. * function afterShowAnimation(scope, element, options) {
  237. * // post-show code here: DOM element focus, etc.
  238. * }
  239. * }
  240. *
  241. * // Dialog #3 - Demonstrate use of ControllerAs and passing $scope to dialog
  242. * // Here we used ng-controller="GreetingController as vm" and
  243. * // $scope.vm === <controller instance>
  244. *
  245. * function showCustomGreeting() {
  246. *
  247. * $mdDialog.show({
  248. * clickOutsideToClose: true,
  249. *
  250. * scope: $scope, // use parent scope in template
  251. * preserveScope: true, // do not forget this if use parent scope
  252. * // Since GreetingController is instantiated with ControllerAs syntax
  253. * // AND we are passing the parent '$scope' to the dialog, we MUST
  254. * // use 'vm.<xxx>' in the template markup
  255. *
  256. * template: '<md-dialog>' +
  257. * ' <md-dialog-content>' +
  258. * ' Hi There {{vm.employee}}' +
  259. * ' </md-dialog-content>' +
  260. * '</md-dialog>',
  261. *
  262. * controller: function DialogController($scope, $mdDialog) {
  263. * $scope.closeDialog = function() {
  264. * $mdDialog.hide();
  265. * }
  266. * }
  267. * });
  268. * }
  269. *
  270. * }
  271. *
  272. * // Greeting controller used with the more complex 'showCustomGreeting()' custom dialog
  273. *
  274. * function GreetingController($scope, $mdDialog, employee) {
  275. * // Assigned from construction <code>locals</code> options...
  276. * $scope.employee = employee;
  277. *
  278. * $scope.closeDialog = function() {
  279. * // Easily hides most recent dialog shown...
  280. * // no specific instance reference is needed.
  281. * $mdDialog.hide();
  282. * };
  283. * }
  284. *
  285. * })(angular);
  286. * </hljs>
  287. */
  288. /**
  289. * @ngdoc method
  290. * @name $mdDialog#alert
  291. *
  292. * @description
  293. * Builds a preconfigured dialog with the specified message.
  294. *
  295. * @returns {obj} an `$mdDialogPreset` with the chainable configuration methods:
  296. *
  297. * - $mdDialogPreset#title(string) - sets title to string
  298. * - $mdDialogPreset#content(string) - sets content / message to string
  299. * - $mdDialogPreset#ok(string) - sets okay button text to string
  300. * - $mdDialogPreset#theme(string) - sets the theme of the dialog
  301. *
  302. */
  303. /**
  304. * @ngdoc method
  305. * @name $mdDialog#confirm
  306. *
  307. * @description
  308. * Builds a preconfigured dialog with the specified message. You can call show and the promise returned
  309. * will be resolved only if the user clicks the confirm action on the dialog.
  310. *
  311. * @returns {obj} an `$mdDialogPreset` with the chainable configuration methods:
  312. *
  313. * Additionally, it supports the following methods:
  314. *
  315. * - $mdDialogPreset#title(string) - sets title to string
  316. * - $mdDialogPreset#content(string) - sets content / message to string
  317. * - $mdDialogPreset#ok(string) - sets okay button text to string
  318. * - $mdDialogPreset#cancel(string) - sets cancel button text to string
  319. * - $mdDialogPreset#theme(string) - sets the theme of the dialog
  320. *
  321. */
  322. /**
  323. * @ngdoc method
  324. * @name $mdDialog#show
  325. *
  326. * @description
  327. * Show a dialog with the specified options.
  328. *
  329. * @param {object} optionsOrPreset Either provide an `$mdDialogPreset` returned from `alert()`, and
  330. * `confirm()`, or an options object with the following properties:
  331. * - `templateUrl` - `{string=}`: The url of a template that will be used as the content
  332. * of the dialog.
  333. * - `template` - `{string=}`: Same as templateUrl, except this is an actual template string.
  334. * - `targetEvent` - `{DOMClickEvent=}`: A click's event object. When passed in as an option,
  335. * the location of the click will be used as the starting point for the opening animation
  336. * of the the dialog.
  337. * - `scope` - `{object=}`: the scope to link the template / controller to. If none is specified,
  338. * it will create a new isolate scope.
  339. * This scope will be destroyed when the dialog is removed unless `preserveScope` is set to true.
  340. * - `preserveScope` - `{boolean=}`: whether to preserve the scope when the element is removed. Default is false
  341. * - `disableParentScroll` - `{boolean=}`: Whether to disable scrolling while the dialog is open.
  342. * Default true.
  343. * - `hasBackdrop` - `{boolean=}`: Whether there should be an opaque backdrop behind the dialog.
  344. * Default true.
  345. * - `clickOutsideToClose` - `{boolean=}`: Whether the user can click outside the dialog to
  346. * close it. Default false.
  347. * - `escapeToClose` - `{boolean=}`: Whether the user can press escape to close the dialog.
  348. * Default true.
  349. * - `focusOnOpen` - `{boolean=}`: An option to override focus behavior on open. Only disable if
  350. * focusing some other way, as focus management is required for dialogs to be accessible.
  351. * Defaults to true.
  352. * - `controller` - `{string=}`: The controller to associate with the dialog. The controller
  353. * will be injected with the local `$mdDialog`, which passes along a scope for the dialog.
  354. * - `locals` - `{object=}`: An object containing key/value pairs. The keys will be used as names
  355. * of values to inject into the controller. For example, `locals: {three: 3}` would inject
  356. * `three` into the controller, with the value 3. If `bindToController` is true, they will be
  357. * copied to the controller instead.
  358. * - `bindToController` - `bool`: bind the locals to the controller, instead of passing them in.
  359. * These values will not be available until after initialization.
  360. * - `resolve` - `{object=}`: Similar to locals, except it takes promises as values, and the
  361. * dialog will not open until all of the promises resolve.
  362. * - `controllerAs` - `{string=}`: An alias to assign the controller to on the scope.
  363. * - `parent` - `{element=}`: The element to append the dialog to. Defaults to appending
  364. * to the root element of the application.
  365. * - `onShowing` `{function=} Callback function used to announce the show() action is
  366. * starting.
  367. * - `onComplete` `{function=}`: Callback function used to announce when the show() action is
  368. * finished.
  369. * - `onRemoving` `{function=} Callback function used to announce the close/hide() action is
  370. * starting. This allows developers to run custom animations in parallel the close animations.
  371. *
  372. * @returns {promise} A promise that can be resolved with `$mdDialog.hide()` or
  373. * rejected with `$mdDialog.cancel()`.
  374. */
  375. /**
  376. * @ngdoc method
  377. * @name $mdDialog#hide
  378. *
  379. * @description
  380. * Hide an existing dialog and resolve the promise returned from `$mdDialog.show()`.
  381. *
  382. * @param {*=} response An argument for the resolved promise.
  383. *
  384. * @returns {promise} A promise that is resolved when the dialog has been closed.
  385. */
  386. /**
  387. * @ngdoc method
  388. * @name $mdDialog#cancel
  389. *
  390. * @description
  391. * Hide an existing dialog and reject the promise returned from `$mdDialog.show()`.
  392. *
  393. * @param {*=} response An argument for the rejected promise.
  394. *
  395. * @returns {promise} A promise that is resolved when the dialog has been closed.
  396. */
  397. function MdDialogProvider($$interimElementProvider) {
  398. advancedDialogOptions.$inject = ["$mdDialog", "$mdTheming"];
  399. dialogDefaultOptions.$inject = ["$mdDialog", "$mdAria", "$mdUtil", "$mdConstant", "$animate", "$document", "$window", "$rootElement"];
  400. return $$interimElementProvider('$mdDialog')
  401. .setDefaults({
  402. methods: ['disableParentScroll', 'hasBackdrop', 'clickOutsideToClose', 'escapeToClose', 'targetEvent', 'parent'],
  403. options: dialogDefaultOptions
  404. })
  405. .addPreset('alert', {
  406. methods: ['title', 'content', 'ariaLabel', 'ok', 'theme', 'css'],
  407. options: advancedDialogOptions
  408. })
  409. .addPreset('confirm', {
  410. methods: ['title', 'content', 'ariaLabel', 'ok', 'cancel', 'theme', 'css'],
  411. options: advancedDialogOptions
  412. });
  413. /* ngInject */
  414. function advancedDialogOptions($mdDialog, $mdTheming) {
  415. return {
  416. template: [
  417. '<md-dialog md-theme="{{ dialog.theme }}" aria-label="{{ dialog.ariaLabel }}" ng-class="dialog.css">',
  418. ' <md-dialog-content class="md-dialog-content" role="document" tabIndex="-1">',
  419. ' <h2 class="md-title">{{ dialog.title }}</h2>',
  420. ' <div class="md-dialog-content-body" md-template="::dialog.mdContent"></div>',
  421. ' </md-dialog-content>',
  422. ' <div class="md-actions">',
  423. ' <md-button ng-if="dialog.$type == \'confirm\'"' +
  424. ' ng-click="dialog.abort()" class="md-primary">',
  425. ' {{ dialog.cancel }}',
  426. ' </md-button>',
  427. ' <md-button ng-click="dialog.hide()" class="md-primary" md-autofocus="dialog.$type!=\'confirm\'">',
  428. ' {{ dialog.ok }}',
  429. ' </md-button>',
  430. ' </div>',
  431. '</md-dialog>'
  432. ].join('').replace(/\s\s+/g, ''),
  433. controller: function mdDialogCtrl() {
  434. this.hide = function() {
  435. $mdDialog.hide(true);
  436. };
  437. this.abort = function() {
  438. $mdDialog.cancel();
  439. };
  440. },
  441. controllerAs: 'dialog',
  442. bindToController: true,
  443. theme: $mdTheming.defaultTheme()
  444. };
  445. }
  446. /* ngInject */
  447. function dialogDefaultOptions($mdDialog, $mdAria, $mdUtil, $mdConstant, $animate, $document, $window, $rootElement) {
  448. return {
  449. hasBackdrop: true,
  450. isolateScope: true,
  451. onShow: onShow,
  452. onRemove: onRemove,
  453. clickOutsideToClose: false,
  454. escapeToClose: true,
  455. targetEvent: null,
  456. focusOnOpen: true,
  457. disableParentScroll: true,
  458. transformTemplate: function(template) {
  459. return '<div class="md-dialog-container">' + validatedTemplate(template) + '</div>';
  460. /**
  461. * The specified template should contain a <md-dialog> wrapper element....
  462. */
  463. function validatedTemplate(template) {
  464. template || ""
  465. return /<\/md-dialog>/g.test(template) ? template : "<md-dialog>" + template + "</md-dialog>";
  466. }
  467. }
  468. };
  469. /**
  470. * Show method for dialogs
  471. */
  472. function onShow(scope, element, options, controller) {
  473. angular.element($document[0].body).addClass('md-dialog-is-showing');
  474. wrapSimpleContent();
  475. captureSourceAndParent(element, options);
  476. configureAria(element.find('md-dialog'), options);
  477. showBackdrop(scope, element, options);
  478. return dialogPopIn(element, options)
  479. .then(function() {
  480. activateListeners(element, options);
  481. lockScreenReader(element, options);
  482. focusOnOpen();
  483. });
  484. /**
  485. * For alerts, focus on content... otherwise focus on
  486. * the close button (or equivalent)
  487. */
  488. function focusOnOpen() {
  489. if (options.focusOnOpen) {
  490. var target = $mdUtil.findFocusTarget(element) || findCloseButton();
  491. target.focus();
  492. }
  493. /**
  494. * If no element with class dialog-close, try to find the last
  495. * button child in md-actions and assume it is a close button
  496. */
  497. function findCloseButton() {
  498. var closeButton = element[0].querySelector('.dialog-close');
  499. if (!closeButton) {
  500. var actionButtons = element[0].querySelectorAll('.md-actions button');
  501. closeButton = actionButtons[actionButtons.length - 1];
  502. }
  503. return angular.element(closeButton);
  504. }
  505. }
  506. /**
  507. * Wrap any simple content [specified via .content("")] in <p></p> tags.
  508. * otherwise accept HTML content within the dialog content area...
  509. * NOTE: Dialog uses the md-template directive to safely inject HTML content.
  510. */
  511. function wrapSimpleContent() {
  512. if ( controller ) {
  513. var HTML_END_TAG = /<\/[\w-]*>/gm;
  514. var content = controller.content || options.content || "";
  515. var hasHTML = HTML_END_TAG.test(content);
  516. if (!hasHTML) {
  517. content = $mdUtil.supplant("<p>{0}</p>", [content]);
  518. }
  519. // Publish updated dialog content body... to be compiled by mdTemplate directive
  520. controller.mdContent = content;
  521. }
  522. }
  523. }
  524. /**
  525. * Remove function for all dialogs
  526. */
  527. function onRemove(scope, element, options) {
  528. options.deactivateListeners();
  529. options.unlockScreenReader();
  530. options.hideBackdrop(options.$destroy);
  531. // For navigation $destroy events, do a quick, non-animated removal,
  532. // but for normal closes (from clicks, etc) animate the removal
  533. return !!options.$destroy ? detachAndClean() : animateRemoval().then( detachAndClean );
  534. /**
  535. * For normal closes, animate the removal.
  536. * For forced closes (like $destroy events), skip the animations
  537. */
  538. function animateRemoval() {
  539. return dialogPopOut(element, options);
  540. }
  541. /**
  542. * Detach the element
  543. */
  544. function detachAndClean() {
  545. angular.element($document[0].body).removeClass('md-dialog-is-showing');
  546. element.remove();
  547. if (!options.$destroy) options.origin.focus();
  548. }
  549. }
  550. /**
  551. * Capture originator/trigger element information (if available)
  552. * and the parent container for the dialog; defaults to the $rootElement
  553. * unless overridden in the options.parent
  554. */
  555. function captureSourceAndParent(element, options) {
  556. options.origin = angular.extend({
  557. element: null,
  558. bounds: null,
  559. focus: angular.noop
  560. }, options.origin || {});
  561. var source = angular.element((options.targetEvent || {}).target);
  562. if (source && source.length) {
  563. // Compute and save the target element's bounding rect, so that if the
  564. // element is hidden when the dialog closes, we can shrink the dialog
  565. // back to the same position it expanded from.
  566. options.origin.element = source;
  567. options.origin.bounds = source[0].getBoundingClientRect();
  568. options.origin.focus = function() {
  569. source.focus();
  570. }
  571. }
  572. // If the parent specifier is a simple string selector, then query for
  573. // the DOM element.
  574. if ( angular.isString(options.parent) ) {
  575. var simpleSelector = options.parent,
  576. container = $document[0].querySelectorAll(simpleSelector);
  577. options.parent = container.length ? container[0] : null;
  578. }
  579. // If we have a reference to a raw dom element, always wrap it in jqLite
  580. options.parent = angular.element(options.parent || $rootElement);
  581. }
  582. /**
  583. * Listen for escape keys and outside clicks to auto close
  584. */
  585. function activateListeners(element, options) {
  586. var window = angular.element($window);
  587. var onWindowResize = $mdUtil.debounce(function(){
  588. stretchDialogContainerToViewport(element, options);
  589. }, 60);
  590. var removeListeners = [];
  591. var smartClose = function() {
  592. // Only 'confirm' dialogs have a cancel button... escape/clickOutside will
  593. // cancel or fallback to hide.
  594. var closeFn = ( options.$type == 'alert' ) ? $mdDialog.hide : $mdDialog.cancel;
  595. $mdUtil.nextTick(closeFn, true);
  596. };
  597. if (options.escapeToClose) {
  598. var target = options.parent;
  599. var keyHandlerFn = function(ev) {
  600. if (ev.keyCode === $mdConstant.KEY_CODE.ESCAPE) {
  601. ev.stopPropagation();
  602. ev.preventDefault();
  603. smartClose();
  604. }
  605. };
  606. // Add keydown listeners
  607. element.on('keydown', keyHandlerFn);
  608. target.on('keydown', keyHandlerFn);
  609. window.on('resize', onWindowResize);
  610. // Queue remove listeners function
  611. removeListeners.push(function() {
  612. element.off('keydown', keyHandlerFn);
  613. target.off('keydown', keyHandlerFn);
  614. window.off('resize', onWindowResize);
  615. });
  616. }
  617. if (options.clickOutsideToClose) {
  618. var target = element;
  619. var sourceElem;
  620. // Keep track of the element on which the mouse originally went down
  621. // so that we can only close the backdrop when the 'click' started on it.
  622. // A simple 'click' handler does not work,
  623. // it sets the target object as the element the mouse went down on.
  624. var mousedownHandler = function(ev) {
  625. sourceElem = ev.target;
  626. };
  627. // We check if our original element and the target is the backdrop
  628. // because if the original was the backdrop and the target was inside the dialog
  629. // we don't want to dialog to close.
  630. var mouseupHandler = function(ev) {
  631. if (sourceElem === target[0] && ev.target === target[0]) {
  632. ev.stopPropagation();
  633. ev.preventDefault();
  634. smartClose();
  635. }
  636. };
  637. // Add listeners
  638. target.on('mousedown', mousedownHandler);
  639. target.on('mouseup', mouseupHandler);
  640. // Queue remove listeners function
  641. removeListeners.push(function() {
  642. target.off('mousedown', mousedownHandler);
  643. target.off('mouseup', mouseupHandler);
  644. });
  645. }
  646. // Attach specific `remove` listener handler
  647. options.deactivateListeners = function() {
  648. removeListeners.forEach(function(removeFn) {
  649. removeFn();
  650. });
  651. options.deactivateListeners = null;
  652. };
  653. }
  654. /**
  655. * Show modal backdrop element...
  656. */
  657. function showBackdrop(scope, element, options) {
  658. if (options.disableParentScroll) {
  659. // !! DO this before creating the backdrop; since disableScrollAround()
  660. // configures the scroll offset; which is used by mdBackDrop postLink()
  661. options.restoreScroll = $mdUtil.disableScrollAround(element, options.parent);
  662. }
  663. if (options.hasBackdrop) {
  664. options.backdrop = $mdUtil.createBackdrop(scope, "md-dialog-backdrop md-opaque");
  665. $animate.enter(options.backdrop, options.parent);
  666. }
  667. /**
  668. * Hide modal backdrop element...
  669. */
  670. options.hideBackdrop = function hideBackdrop($destroy) {
  671. if (options.backdrop) {
  672. if ( !!$destroy ) options.backdrop.remove();
  673. else $animate.leave(options.backdrop);
  674. }
  675. if (options.disableParentScroll) {
  676. options.restoreScroll();
  677. delete options.restoreScroll;
  678. }
  679. options.hideBackdrop = null;
  680. }
  681. }
  682. /**
  683. * Inject ARIA-specific attributes appropriate for Dialogs
  684. */
  685. function configureAria(element, options) {
  686. var role = (options.$type === 'alert') ? 'alertdialog' : 'dialog';
  687. var dialogContent = element.find('md-dialog-content');
  688. var dialogId = element.attr('id') || ('dialog_' + $mdUtil.nextUid());
  689. element.attr({
  690. 'role': role,
  691. 'tabIndex': '-1'
  692. });
  693. if (dialogContent.length === 0) {
  694. dialogContent = element;
  695. }
  696. dialogContent.attr('id', dialogId);
  697. element.attr('aria-describedby', dialogId);
  698. if (options.ariaLabel) {
  699. $mdAria.expect(element, 'aria-label', options.ariaLabel);
  700. }
  701. else {
  702. $mdAria.expectAsync(element, 'aria-label', function() {
  703. var words = dialogContent.text().split(/\s+/);
  704. if (words.length > 3) words = words.slice(0, 3).concat('...');
  705. return words.join(' ');
  706. });
  707. }
  708. }
  709. /**
  710. * Prevents screen reader interaction behind modal window
  711. * on swipe interfaces
  712. */
  713. function lockScreenReader(element, options) {
  714. var isHidden = true;
  715. // get raw DOM node
  716. walkDOM(element[0]);
  717. options.unlockScreenReader = function() {
  718. isHidden = false;
  719. walkDOM(element[0]);
  720. options.unlockScreenReader = null;
  721. };
  722. /**
  723. * Walk DOM to apply or remove aria-hidden on sibling nodes
  724. * and parent sibling nodes
  725. *
  726. */
  727. function walkDOM(element) {
  728. while (element.parentNode) {
  729. if (element === document.body) {
  730. return;
  731. }
  732. var children = element.parentNode.children;
  733. for (var i = 0; i < children.length; i++) {
  734. // skip over child if it is an ascendant of the dialog
  735. // or a script or style tag
  736. if (element !== children[i] && !isNodeOneOf(children[i], ['SCRIPT', 'STYLE'])) {
  737. children[i].setAttribute('aria-hidden', isHidden);
  738. }
  739. }
  740. walkDOM(element = element.parentNode);
  741. }
  742. }
  743. }
  744. /**
  745. * Ensure the dialog container fill-stretches to the viewport
  746. */
  747. function stretchDialogContainerToViewport(container, options) {
  748. var isFixed = $window.getComputedStyle($document[0].body).position == 'fixed';
  749. var backdrop = options.backdrop ? $window.getComputedStyle(options.backdrop[0]) : null;
  750. var height = backdrop ? Math.min($document[0].body.clientHeight, Math.ceil(Math.abs(parseInt(backdrop.height, 10)))) : 0;
  751. container.css({
  752. top: (isFixed ? $mdUtil.scrollTop(options.parent) : 0) + 'px',
  753. height: height ? height + 'px' : '100%'
  754. });
  755. return container;
  756. }
  757. /**
  758. * Dialog open and pop-in animation
  759. */
  760. function dialogPopIn(container, options) {
  761. // Add the `md-dialog-container` to the DOM
  762. options.parent.append(container);
  763. stretchDialogContainerToViewport(container, options);
  764. var dialogEl = container.find('md-dialog');
  765. var animator = $mdUtil.dom.animator;
  766. var buildTranslateToOrigin = animator.calculateZoomToOrigin;
  767. var translateOptions = {transitionInClass: 'md-transition-in', transitionOutClass: 'md-transition-out'};
  768. var from = animator.toTransformCss(buildTranslateToOrigin(dialogEl, options.origin));
  769. var to = animator.toTransformCss(""); // defaults to center display (or parent or $rootElement)
  770. return animator
  771. .translate3d(dialogEl, from, to, translateOptions)
  772. .then(function(animateReversal) {
  773. // Build a reversal translate function synched to this translation...
  774. options.reverseAnimate = function() {
  775. delete options.reverseAnimate;
  776. return animateReversal(
  777. animator.toTransformCss(
  778. // in case the origin element has moved or is hidden,
  779. // let's recalculate the translateCSS
  780. buildTranslateToOrigin(dialogEl, options.origin)
  781. )
  782. );
  783. };
  784. return true;
  785. });
  786. }
  787. /**
  788. * Dialog close and pop-out animation
  789. */
  790. function dialogPopOut(container, options) {
  791. return options.reverseAnimate();
  792. }
  793. /**
  794. * Utility function to filter out raw DOM nodes
  795. */
  796. function isNodeOneOf(elem, nodeTypeArray) {
  797. if (nodeTypeArray.indexOf(elem.nodeName) !== -1) {
  798. return true;
  799. }
  800. }
  801. }
  802. }
  803. MdDialogProvider.$inject = ["$$interimElementProvider"];
  804. })(window, window.angular);