You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1294 lines
47 KiB

  1. /*!
  2. * Angular Material Design
  3. * https://github.com/angular/material
  4. * @license MIT
  5. * v1.1.1
  6. */
  7. goog.provide('ngmaterial.components.dialog');
  8. goog.require('ngmaterial.components.backdrop');
  9. goog.require('ngmaterial.core');
  10. /**
  11. * @ngdoc module
  12. * @name material.components.dialog
  13. */
  14. MdDialogDirective.$inject = ["$$rAF", "$mdTheming", "$mdDialog"];
  15. MdDialogProvider.$inject = ["$$interimElementProvider"];
  16. angular
  17. .module('material.components.dialog', [
  18. 'material.core',
  19. 'material.components.backdrop'
  20. ])
  21. .directive('mdDialog', MdDialogDirective)
  22. .provider('$mdDialog', MdDialogProvider);
  23. /**
  24. * @ngdoc directive
  25. * @name mdDialog
  26. * @module material.components.dialog
  27. *
  28. * @restrict E
  29. *
  30. * @description
  31. * `<md-dialog>` - The dialog's template must be inside this element.
  32. *
  33. * Inside, use an `<md-dialog-content>` element for the dialog's content, and use
  34. * an `<md-dialog-actions>` element for the dialog's actions.
  35. *
  36. * ## CSS
  37. * - `.md-dialog-content` - class that sets the padding on the content as the spec file
  38. *
  39. * ## Notes
  40. * - If you specify an `id` for the `<md-dialog>`, the `<md-dialog-content>` will have the same `id`
  41. * prefixed with `dialogContent_`.
  42. *
  43. * @usage
  44. * ### Dialog template
  45. * <hljs lang="html">
  46. * <md-dialog aria-label="List dialog">
  47. * <md-dialog-content>
  48. * <md-list>
  49. * <md-list-item ng-repeat="item in items">
  50. * <p>Number {{item}}</p>
  51. * </md-list-item>
  52. * </md-list>
  53. * </md-dialog-content>
  54. * <md-dialog-actions>
  55. * <md-button ng-click="closeDialog()" class="md-primary">Close Dialog</md-button>
  56. * </md-dialog-actions>
  57. * </md-dialog>
  58. * </hljs>
  59. */
  60. function MdDialogDirective($$rAF, $mdTheming, $mdDialog) {
  61. return {
  62. restrict: 'E',
  63. link: function(scope, element) {
  64. element.addClass('_md'); // private md component indicator for styling
  65. $mdTheming(element);
  66. $$rAF(function() {
  67. var images;
  68. var content = element[0].querySelector('md-dialog-content');
  69. if (content) {
  70. images = content.getElementsByTagName('img');
  71. addOverflowClass();
  72. //-- delayed image loading may impact scroll height, check after images are loaded
  73. angular.element(images).on('load', addOverflowClass);
  74. }
  75. scope.$on('$destroy', function() {
  76. $mdDialog.destroy(element);
  77. });
  78. /**
  79. *
  80. */
  81. function addOverflowClass() {
  82. element.toggleClass('md-content-overflow', content.scrollHeight > content.clientHeight);
  83. }
  84. });
  85. }
  86. };
  87. }
  88. /**
  89. * @ngdoc service
  90. * @name $mdDialog
  91. * @module material.components.dialog
  92. *
  93. * @description
  94. * `$mdDialog` opens a dialog over the app to inform users about critical information or require
  95. * them to make decisions. There are two approaches for setup: a simple promise API
  96. * and regular object syntax.
  97. *
  98. * ## Restrictions
  99. *
  100. * - The dialog is always given an isolate scope.
  101. * - The dialog's template must have an outer `<md-dialog>` element.
  102. * Inside, use an `<md-dialog-content>` element for the dialog's content, and use
  103. * an `<md-dialog-actions>` element for the dialog's actions.
  104. * - Dialogs must cover the entire application to keep interactions inside of them.
  105. * Use the `parent` option to change where dialogs are appended.
  106. *
  107. * ## Sizing
  108. * - Complex dialogs can be sized with `flex="percentage"`, i.e. `flex="66"`.
  109. * - Default max-width is 80% of the `rootElement` or `parent`.
  110. *
  111. * ## CSS
  112. * - `.md-dialog-content` - class that sets the padding on the content as the spec file
  113. *
  114. * @usage
  115. * <hljs lang="html">
  116. * <div ng-app="demoApp" ng-controller="EmployeeController">
  117. * <div>
  118. * <md-button ng-click="showAlert()" class="md-raised md-warn">
  119. * Employee Alert!
  120. * </md-button>
  121. * </div>
  122. * <div>
  123. * <md-button ng-click="showDialog($event)" class="md-raised">
  124. * Custom Dialog
  125. * </md-button>
  126. * </div>
  127. * <div>
  128. * <md-button ng-click="closeAlert()" ng-disabled="!hasAlert()" class="md-raised">
  129. * Close Alert
  130. * </md-button>
  131. * </div>
  132. * <div>
  133. * <md-button ng-click="showGreeting($event)" class="md-raised md-primary" >
  134. * Greet Employee
  135. * </md-button>
  136. * </div>
  137. * </div>
  138. * </hljs>
  139. *
  140. * ### JavaScript: object syntax
  141. * <hljs lang="js">
  142. * (function(angular, undefined){
  143. * "use strict";
  144. *
  145. * angular
  146. * .module('demoApp', ['ngMaterial'])
  147. * .controller('AppCtrl', AppController);
  148. *
  149. * function AppController($scope, $mdDialog) {
  150. * var alert;
  151. * $scope.showAlert = showAlert;
  152. * $scope.showDialog = showDialog;
  153. * $scope.items = [1, 2, 3];
  154. *
  155. * // Internal method
  156. * function showAlert() {
  157. * alert = $mdDialog.alert({
  158. * title: 'Attention',
  159. * textContent: 'This is an example of how easy dialogs can be!',
  160. * ok: 'Close'
  161. * });
  162. *
  163. * $mdDialog
  164. * .show( alert )
  165. * .finally(function() {
  166. * alert = undefined;
  167. * });
  168. * }
  169. *
  170. * function showDialog($event) {
  171. * var parentEl = angular.element(document.body);
  172. * $mdDialog.show({
  173. * parent: parentEl,
  174. * targetEvent: $event,
  175. * template:
  176. * '<md-dialog aria-label="List dialog">' +
  177. * ' <md-dialog-content>'+
  178. * ' <md-list>'+
  179. * ' <md-list-item ng-repeat="item in items">'+
  180. * ' <p>Number {{item}}</p>' +
  181. * ' </md-item>'+
  182. * ' </md-list>'+
  183. * ' </md-dialog-content>' +
  184. * ' <md-dialog-actions>' +
  185. * ' <md-button ng-click="closeDialog()" class="md-primary">' +
  186. * ' Close Dialog' +
  187. * ' </md-button>' +
  188. * ' </md-dialog-actions>' +
  189. * '</md-dialog>',
  190. * locals: {
  191. * items: $scope.items
  192. * },
  193. * controller: DialogController
  194. * });
  195. * function DialogController($scope, $mdDialog, items) {
  196. * $scope.items = items;
  197. * $scope.closeDialog = function() {
  198. * $mdDialog.hide();
  199. * }
  200. * }
  201. * }
  202. * }
  203. * })(angular);
  204. * </hljs>
  205. *
  206. * ### Pre-Rendered Dialogs
  207. * By using the `contentElement` option, it is possible to use an already existing element in the DOM.
  208. *
  209. * <hljs lang="js">
  210. * $scope.showPrerenderedDialog = function() {
  211. * $mdDialog.show({
  212. * contentElement: '#myStaticDialog',
  213. * parent: angular.element(document.body)
  214. * });
  215. * };
  216. * </hljs>
  217. *
  218. * When using a string as value, `$mdDialog` will automatically query the DOM for the specified CSS selector.
  219. *
  220. * <hljs lang="html">
  221. * <div style="visibility: hidden">
  222. * <div class="md-dialog-container" id="myStaticDialog">
  223. * <md-dialog>
  224. * This is a pre-rendered dialog.
  225. * </md-dialog>
  226. * </div>
  227. * </div>
  228. * </hljs>
  229. *
  230. * **Notice**: It is important, to use the `.md-dialog-container` as the content element, otherwise the dialog
  231. * will not show up.
  232. *
  233. * It also possible to use a DOM element for the `contentElement` option.
  234. * - `contentElement: document.querySelector('#myStaticDialog')`
  235. * - `contentElement: angular.element(TEMPLATE)`
  236. *
  237. * When using a `template` as content element, it will be not compiled upon open.
  238. * This allows you to compile the element yourself and use it each time the dialog opens.
  239. *
  240. * ### Custom Presets
  241. * Developers are also able to create their own preset, which can be easily used without repeating
  242. * their options each time.
  243. *
  244. * <hljs lang="js">
  245. * $mdDialogProvider.addPreset('testPreset', {
  246. * options: function() {
  247. * return {
  248. * template:
  249. * '<md-dialog>' +
  250. * 'This is a custom preset' +
  251. * '</md-dialog>',
  252. * controllerAs: 'dialog',
  253. * bindToController: true,
  254. * clickOutsideToClose: true,
  255. * escapeToClose: true
  256. * };
  257. * }
  258. * });
  259. * </hljs>
  260. *
  261. * After you created your preset at config phase, you can easily access it.
  262. *
  263. * <hljs lang="js">
  264. * $mdDialog.show(
  265. * $mdDialog.testPreset()
  266. * );
  267. * </hljs>
  268. *
  269. * ### JavaScript: promise API syntax, custom dialog template
  270. * <hljs lang="js">
  271. * (function(angular, undefined){
  272. * "use strict";
  273. *
  274. * angular
  275. * .module('demoApp', ['ngMaterial'])
  276. * .controller('EmployeeController', EmployeeEditor)
  277. * .controller('GreetingController', GreetingController);
  278. *
  279. * // Fictitious Employee Editor to show how to use simple and complex dialogs.
  280. *
  281. * function EmployeeEditor($scope, $mdDialog) {
  282. * var alert;
  283. *
  284. * $scope.showAlert = showAlert;
  285. * $scope.closeAlert = closeAlert;
  286. * $scope.showGreeting = showCustomGreeting;
  287. *
  288. * $scope.hasAlert = function() { return !!alert };
  289. * $scope.userName = $scope.userName || 'Bobby';
  290. *
  291. * // Dialog #1 - Show simple alert dialog and cache
  292. * // reference to dialog instance
  293. *
  294. * function showAlert() {
  295. * alert = $mdDialog.alert()
  296. * .title('Attention, ' + $scope.userName)
  297. * .textContent('This is an example of how easy dialogs can be!')
  298. * .ok('Close');
  299. *
  300. * $mdDialog
  301. * .show( alert )
  302. * .finally(function() {
  303. * alert = undefined;
  304. * });
  305. * }
  306. *
  307. * // Close the specified dialog instance and resolve with 'finished' flag
  308. * // Normally this is not needed, just use '$mdDialog.hide()' to close
  309. * // the most recent dialog popup.
  310. *
  311. * function closeAlert() {
  312. * $mdDialog.hide( alert, "finished" );
  313. * alert = undefined;
  314. * }
  315. *
  316. * // Dialog #2 - Demonstrate more complex dialogs construction and popup.
  317. *
  318. * function showCustomGreeting($event) {
  319. * $mdDialog.show({
  320. * targetEvent: $event,
  321. * template:
  322. * '<md-dialog>' +
  323. *
  324. * ' <md-dialog-content>Hello {{ employee }}!</md-dialog-content>' +
  325. *
  326. * ' <md-dialog-actions>' +
  327. * ' <md-button ng-click="closeDialog()" class="md-primary">' +
  328. * ' Close Greeting' +
  329. * ' </md-button>' +
  330. * ' </md-dialog-actions>' +
  331. * '</md-dialog>',
  332. * controller: 'GreetingController',
  333. * onComplete: afterShowAnimation,
  334. * locals: { employee: $scope.userName }
  335. * });
  336. *
  337. * // When the 'enter' animation finishes...
  338. *
  339. * function afterShowAnimation(scope, element, options) {
  340. * // post-show code here: DOM element focus, etc.
  341. * }
  342. * }
  343. *
  344. * // Dialog #3 - Demonstrate use of ControllerAs and passing $scope to dialog
  345. * // Here we used ng-controller="GreetingController as vm" and
  346. * // $scope.vm === <controller instance>
  347. *
  348. * function showCustomGreeting() {
  349. *
  350. * $mdDialog.show({
  351. * clickOutsideToClose: true,
  352. *
  353. * scope: $scope, // use parent scope in template
  354. * preserveScope: true, // do not forget this if use parent scope
  355. * // Since GreetingController is instantiated with ControllerAs syntax
  356. * // AND we are passing the parent '$scope' to the dialog, we MUST
  357. * // use 'vm.<xxx>' in the template markup
  358. *
  359. * template: '<md-dialog>' +
  360. * ' <md-dialog-content>' +
  361. * ' Hi There {{vm.employee}}' +
  362. * ' </md-dialog-content>' +
  363. * '</md-dialog>',
  364. *
  365. * controller: function DialogController($scope, $mdDialog) {
  366. * $scope.closeDialog = function() {
  367. * $mdDialog.hide();
  368. * }
  369. * }
  370. * });
  371. * }
  372. *
  373. * }
  374. *
  375. * // Greeting controller used with the more complex 'showCustomGreeting()' custom dialog
  376. *
  377. * function GreetingController($scope, $mdDialog, employee) {
  378. * // Assigned from construction <code>locals</code> options...
  379. * $scope.employee = employee;
  380. *
  381. * $scope.closeDialog = function() {
  382. * // Easily hides most recent dialog shown...
  383. * // no specific instance reference is needed.
  384. * $mdDialog.hide();
  385. * };
  386. * }
  387. *
  388. * })(angular);
  389. * </hljs>
  390. */
  391. /**
  392. * @ngdoc method
  393. * @name $mdDialog#alert
  394. *
  395. * @description
  396. * Builds a preconfigured dialog with the specified message.
  397. *
  398. * @returns {obj} an `$mdDialogPreset` with the chainable configuration methods:
  399. *
  400. * - $mdDialogPreset#title(string) - Sets the alert title.
  401. * - $mdDialogPreset#textContent(string) - Sets the alert message.
  402. * - $mdDialogPreset#htmlContent(string) - Sets the alert message as HTML. Requires ngSanitize
  403. * module to be loaded. HTML is not run through Angular's compiler.
  404. * - $mdDialogPreset#ok(string) - Sets the alert "Okay" button text.
  405. * - $mdDialogPreset#theme(string) - Sets the theme of the alert dialog.
  406. * - $mdDialogPreset#targetEvent(DOMClickEvent=) - A click's event object. When passed in as an option,
  407. * the location of the click will be used as the starting point for the opening animation
  408. * of the the dialog.
  409. *
  410. */
  411. /**
  412. * @ngdoc method
  413. * @name $mdDialog#confirm
  414. *
  415. * @description
  416. * Builds a preconfigured dialog with the specified message. You can call show and the promise returned
  417. * will be resolved only if the user clicks the confirm action on the dialog.
  418. *
  419. * @returns {obj} an `$mdDialogPreset` with the chainable configuration methods:
  420. *
  421. * Additionally, it supports the following methods:
  422. *
  423. * - $mdDialogPreset#title(string) - Sets the confirm title.
  424. * - $mdDialogPreset#textContent(string) - Sets the confirm message.
  425. * - $mdDialogPreset#htmlContent(string) - Sets the confirm message as HTML. Requires ngSanitize
  426. * module to be loaded. HTML is not run through Angular's compiler.
  427. * - $mdDialogPreset#ok(string) - Sets the confirm "Okay" button text.
  428. * - $mdDialogPreset#cancel(string) - Sets the confirm "Cancel" button text.
  429. * - $mdDialogPreset#theme(string) - Sets the theme of the confirm dialog.
  430. * - $mdDialogPreset#targetEvent(DOMClickEvent=) - A click's event object. When passed in as an option,
  431. * the location of the click will be used as the starting point for the opening animation
  432. * of the the dialog.
  433. *
  434. */
  435. /**
  436. * @ngdoc method
  437. * @name $mdDialog#prompt
  438. *
  439. * @description
  440. * Builds a preconfigured dialog with the specified message and input box. You can call show and the promise returned
  441. * will be resolved only if the user clicks the prompt action on the dialog, passing the input value as the first argument.
  442. *
  443. * @returns {obj} an `$mdDialogPreset` with the chainable configuration methods:
  444. *
  445. * Additionally, it supports the following methods:
  446. *
  447. * - $mdDialogPreset#title(string) - Sets the prompt title.
  448. * - $mdDialogPreset#textContent(string) - Sets the prompt message.
  449. * - $mdDialogPreset#htmlContent(string) - Sets the prompt message as HTML. Requires ngSanitize
  450. * module to be loaded. HTML is not run through Angular's compiler.
  451. * - $mdDialogPreset#placeholder(string) - Sets the placeholder text for the input.
  452. * - $mdDialogPreset#initialValue(string) - Sets the initial value for the prompt input.
  453. * - $mdDialogPreset#ok(string) - Sets the prompt "Okay" button text.
  454. * - $mdDialogPreset#cancel(string) - Sets the prompt "Cancel" button text.
  455. * - $mdDialogPreset#theme(string) - Sets the theme of the prompt dialog.
  456. * - $mdDialogPreset#targetEvent(DOMClickEvent=) - A click's event object. When passed in as an option,
  457. * the location of the click will be used as the starting point for the opening animation
  458. * of the the dialog.
  459. *
  460. */
  461. /**
  462. * @ngdoc method
  463. * @name $mdDialog#show
  464. *
  465. * @description
  466. * Show a dialog with the specified options.
  467. *
  468. * @param {object} optionsOrPreset Either provide an `$mdDialogPreset` returned from `alert()`, and
  469. * `confirm()`, or an options object with the following properties:
  470. * - `templateUrl` - `{string=}`: The url of a template that will be used as the content
  471. * of the dialog.
  472. * - `template` - `{string=}`: HTML template to show in the dialog. This **must** be trusted HTML
  473. * with respect to Angular's [$sce service](https://docs.angularjs.org/api/ng/service/$sce).
  474. * This template should **never** be constructed with any kind of user input or user data.
  475. * - `contentElement` - `{string|Element}`: Instead of using a template, which will be compiled each time a
  476. * dialog opens, you can also use a DOM element.<br/>
  477. * * When specifying an element, which is present on the DOM, `$mdDialog` will temporary fetch the element into
  478. * the dialog and restores it at the old DOM position upon close.
  479. * * When specifying a string, the string be used as a CSS selector, to lookup for the element in the DOM.
  480. * - `autoWrap` - `{boolean=}`: Whether or not to automatically wrap the template with a
  481. * `<md-dialog>` tag if one is not provided. Defaults to true. Can be disabled if you provide a
  482. * custom dialog directive.
  483. * - `targetEvent` - `{DOMClickEvent=}`: A click's event object. When passed in as an option,
  484. * the location of the click will be used as the starting point for the opening animation
  485. * of the the dialog.
  486. * - `openFrom` - `{string|Element|object}`: The query selector, DOM element or the Rect object
  487. * that is used to determine the bounds (top, left, height, width) from which the Dialog will
  488. * originate.
  489. * - `closeTo` - `{string|Element|object}`: The query selector, DOM element or the Rect object
  490. * that is used to determine the bounds (top, left, height, width) to which the Dialog will
  491. * target.
  492. * - `scope` - `{object=}`: the scope to link the template / controller to. If none is specified,
  493. * it will create a new isolate scope.
  494. * This scope will be destroyed when the dialog is removed unless `preserveScope` is set to true.
  495. * - `preserveScope` - `{boolean=}`: whether to preserve the scope when the element is removed. Default is false
  496. * - `disableParentScroll` - `{boolean=}`: Whether to disable scrolling while the dialog is open.
  497. * Default true.
  498. * - `hasBackdrop` - `{boolean=}`: Whether there should be an opaque backdrop behind the dialog.
  499. * Default true.
  500. * - `clickOutsideToClose` - `{boolean=}`: Whether the user can click outside the dialog to
  501. * close it. Default false.
  502. * - `escapeToClose` - `{boolean=}`: Whether the user can press escape to close the dialog.
  503. * Default true.
  504. * - `focusOnOpen` - `{boolean=}`: An option to override focus behavior on open. Only disable if
  505. * focusing some other way, as focus management is required for dialogs to be accessible.
  506. * Defaults to true.
  507. * - `controller` - `{function|string=}`: The controller to associate with the dialog. The controller
  508. * will be injected with the local `$mdDialog`, which passes along a scope for the dialog.
  509. * - `locals` - `{object=}`: An object containing key/value pairs. The keys will be used as names
  510. * of values to inject into the controller. For example, `locals: {three: 3}` would inject
  511. * `three` into the controller, with the value 3. If `bindToController` is true, they will be
  512. * copied to the controller instead.
  513. * - `bindToController` - `bool`: bind the locals to the controller, instead of passing them in.
  514. * - `resolve` - `{object=}`: Similar to locals, except it takes promises as values, and the
  515. * dialog will not open until all of the promises resolve.
  516. * - `controllerAs` - `{string=}`: An alias to assign the controller to on the scope.
  517. * - `parent` - `{element=}`: The element to append the dialog to. Defaults to appending
  518. * to the root element of the application.
  519. * - `onShowing` - `function(scope, element)`: Callback function used to announce the show() action is
  520. * starting.
  521. * - `onComplete` - `function(scope, element)`: Callback function used to announce when the show() action is
  522. * finished.
  523. * - `onRemoving` - `function(element, removePromise)`: Callback function used to announce the
  524. * close/hide() action is starting. This allows developers to run custom animations
  525. * in parallel the close animations.
  526. * - `fullscreen` `{boolean=}`: An option to toggle whether the dialog should show in fullscreen
  527. * or not. Defaults to `false`.
  528. * @returns {promise} A promise that can be resolved with `$mdDialog.hide()` or
  529. * rejected with `$mdDialog.cancel()`.
  530. */
  531. /**
  532. * @ngdoc method
  533. * @name $mdDialog#hide
  534. *
  535. * @description
  536. * Hide an existing dialog and resolve the promise returned from `$mdDialog.show()`.
  537. *
  538. * @param {*=} response An argument for the resolved promise.
  539. *
  540. * @returns {promise} A promise that is resolved when the dialog has been closed.
  541. */
  542. /**
  543. * @ngdoc method
  544. * @name $mdDialog#cancel
  545. *
  546. * @description
  547. * Hide an existing dialog and reject the promise returned from `$mdDialog.show()`.
  548. *
  549. * @param {*=} response An argument for the rejected promise.
  550. *
  551. * @returns {promise} A promise that is resolved when the dialog has been closed.
  552. */
  553. function MdDialogProvider($$interimElementProvider) {
  554. // Elements to capture and redirect focus when the user presses tab at the dialog boundary.
  555. advancedDialogOptions.$inject = ["$mdDialog", "$mdConstant"];
  556. dialogDefaultOptions.$inject = ["$mdDialog", "$mdAria", "$mdUtil", "$mdConstant", "$animate", "$document", "$window", "$rootElement", "$log", "$injector", "$mdTheming"];
  557. var topFocusTrap, bottomFocusTrap;
  558. return $$interimElementProvider('$mdDialog')
  559. .setDefaults({
  560. methods: ['disableParentScroll', 'hasBackdrop', 'clickOutsideToClose', 'escapeToClose',
  561. 'targetEvent', 'closeTo', 'openFrom', 'parent', 'fullscreen', 'contentElement'],
  562. options: dialogDefaultOptions
  563. })
  564. .addPreset('alert', {
  565. methods: ['title', 'htmlContent', 'textContent', 'content', 'ariaLabel', 'ok', 'theme',
  566. 'css'],
  567. options: advancedDialogOptions
  568. })
  569. .addPreset('confirm', {
  570. methods: ['title', 'htmlContent', 'textContent', 'content', 'ariaLabel', 'ok', 'cancel',
  571. 'theme', 'css'],
  572. options: advancedDialogOptions
  573. })
  574. .addPreset('prompt', {
  575. methods: ['title', 'htmlContent', 'textContent', 'initialValue', 'content', 'placeholder', 'ariaLabel',
  576. 'ok', 'cancel', 'theme', 'css'],
  577. options: advancedDialogOptions
  578. });
  579. /* ngInject */
  580. function advancedDialogOptions($mdDialog, $mdConstant) {
  581. return {
  582. template: [
  583. '<md-dialog md-theme="{{ dialog.theme }}" aria-label="{{ dialog.ariaLabel }}" ng-class="dialog.css">',
  584. ' <md-dialog-content class="md-dialog-content" role="document" tabIndex="-1">',
  585. ' <h2 class="md-title">{{ dialog.title }}</h2>',
  586. ' <div ng-if="::dialog.mdHtmlContent" class="md-dialog-content-body" ',
  587. ' ng-bind-html="::dialog.mdHtmlContent"></div>',
  588. ' <div ng-if="::!dialog.mdHtmlContent" class="md-dialog-content-body">',
  589. ' <p>{{::dialog.mdTextContent}}</p>',
  590. ' </div>',
  591. ' <md-input-container md-no-float ng-if="::dialog.$type == \'prompt\'" class="md-prompt-input-container">',
  592. ' <input ng-keypress="dialog.keypress($event)" md-autofocus ng-model="dialog.result" ' +
  593. ' placeholder="{{::dialog.placeholder}}">',
  594. ' </md-input-container>',
  595. ' </md-dialog-content>',
  596. ' <md-dialog-actions>',
  597. ' <md-button ng-if="dialog.$type === \'confirm\' || dialog.$type === \'prompt\'"' +
  598. ' ng-click="dialog.abort()" class="md-primary md-cancel-button">',
  599. ' {{ dialog.cancel }}',
  600. ' </md-button>',
  601. ' <md-button ng-click="dialog.hide()" class="md-primary md-confirm-button" md-autofocus="dialog.$type===\'alert\'">',
  602. ' {{ dialog.ok }}',
  603. ' </md-button>',
  604. ' </md-dialog-actions>',
  605. '</md-dialog>'
  606. ].join('').replace(/\s\s+/g, ''),
  607. controller: function mdDialogCtrl() {
  608. var isPrompt = this.$type == 'prompt';
  609. if (isPrompt && this.initialValue) {
  610. this.result = this.initialValue;
  611. }
  612. this.hide = function() {
  613. $mdDialog.hide(isPrompt ? this.result : true);
  614. };
  615. this.abort = function() {
  616. $mdDialog.cancel();
  617. };
  618. this.keypress = function($event) {
  619. if ($event.keyCode === $mdConstant.KEY_CODE.ENTER) {
  620. $mdDialog.hide(this.result);
  621. }
  622. };
  623. },
  624. controllerAs: 'dialog',
  625. bindToController: true,
  626. };
  627. }
  628. /* ngInject */
  629. function dialogDefaultOptions($mdDialog, $mdAria, $mdUtil, $mdConstant, $animate, $document, $window, $rootElement,
  630. $log, $injector, $mdTheming) {
  631. return {
  632. hasBackdrop: true,
  633. isolateScope: true,
  634. onCompiling: beforeCompile,
  635. onShow: onShow,
  636. onShowing: beforeShow,
  637. onRemove: onRemove,
  638. clickOutsideToClose: false,
  639. escapeToClose: true,
  640. targetEvent: null,
  641. contentElement: null,
  642. closeTo: null,
  643. openFrom: null,
  644. focusOnOpen: true,
  645. disableParentScroll: true,
  646. autoWrap: true,
  647. fullscreen: false,
  648. transformTemplate: function(template, options) {
  649. // Make the dialog container focusable, because otherwise the focus will be always redirected to
  650. // an element outside of the container, and the focus trap won't work probably..
  651. // Also the tabindex is needed for the `escapeToClose` functionality, because
  652. // the keyDown event can't be triggered when the focus is outside of the container.
  653. return '<div class="md-dialog-container" tabindex="-1">' + validatedTemplate(template) + '</div>';
  654. /**
  655. * The specified template should contain a <md-dialog> wrapper element....
  656. */
  657. function validatedTemplate(template) {
  658. if (options.autoWrap && !/<\/md-dialog>/g.test(template)) {
  659. return '<md-dialog>' + (template || '') + '</md-dialog>';
  660. } else {
  661. return template || '';
  662. }
  663. }
  664. }
  665. };
  666. function beforeCompile(options) {
  667. // Automatically apply the theme, if the user didn't specify a theme explicitly.
  668. // Those option changes need to be done, before the compilation has started, because otherwise
  669. // the option changes will be not available in the $mdCompilers locales.
  670. detectTheming(options);
  671. if (options.contentElement) {
  672. options.restoreContentElement = installContentElement(options);
  673. }
  674. }
  675. function beforeShow(scope, element, options, controller) {
  676. if (controller) {
  677. controller.mdHtmlContent = controller.htmlContent || options.htmlContent || '';
  678. controller.mdTextContent = controller.textContent || options.textContent ||
  679. controller.content || options.content || '';
  680. if (controller.mdHtmlContent && !$injector.has('$sanitize')) {
  681. throw Error('The ngSanitize module must be loaded in order to use htmlContent.');
  682. }
  683. if (controller.mdHtmlContent && controller.mdTextContent) {
  684. throw Error('md-dialog cannot have both `htmlContent` and `textContent`');
  685. }
  686. }
  687. }
  688. /** Show method for dialogs */
  689. function onShow(scope, element, options, controller) {
  690. angular.element($document[0].body).addClass('md-dialog-is-showing');
  691. var dialogElement = element.find('md-dialog');
  692. // Once a dialog has `ng-cloak` applied on his template the dialog animation will not work properly.
  693. // This is a very common problem, so we have to notify the developer about this.
  694. if (dialogElement.hasClass('ng-cloak')) {
  695. var message = '$mdDialog: using `<md-dialog ng-cloak >` will affect the dialog opening animations.';
  696. $log.warn( message, element[0] );
  697. }
  698. captureParentAndFromToElements(options);
  699. configureAria(dialogElement, options);
  700. showBackdrop(scope, element, options);
  701. activateListeners(element, options);
  702. return dialogPopIn(element, options)
  703. .then(function() {
  704. lockScreenReader(element, options);
  705. warnDeprecatedActions();
  706. focusOnOpen();
  707. });
  708. /**
  709. * Check to see if they used the deprecated .md-actions class and log a warning
  710. */
  711. function warnDeprecatedActions() {
  712. if (element[0].querySelector('.md-actions')) {
  713. $log.warn('Using a class of md-actions is deprecated, please use <md-dialog-actions>.');
  714. }
  715. }
  716. /**
  717. * For alerts, focus on content... otherwise focus on
  718. * the close button (or equivalent)
  719. */
  720. function focusOnOpen() {
  721. if (options.focusOnOpen) {
  722. var target = $mdUtil.findFocusTarget(element) || findCloseButton() || dialogElement;
  723. target.focus();
  724. }
  725. /**
  726. * If no element with class dialog-close, try to find the last
  727. * button child in md-actions and assume it is a close button.
  728. *
  729. * If we find no actions at all, log a warning to the console.
  730. */
  731. function findCloseButton() {
  732. var closeButton = element[0].querySelector('.dialog-close');
  733. if (!closeButton) {
  734. var actionButtons = element[0].querySelectorAll('.md-actions button, md-dialog-actions button');
  735. closeButton = actionButtons[actionButtons.length - 1];
  736. }
  737. return closeButton;
  738. }
  739. }
  740. }
  741. /**
  742. * Remove function for all dialogs
  743. */
  744. function onRemove(scope, element, options) {
  745. options.deactivateListeners();
  746. options.unlockScreenReader();
  747. options.hideBackdrop(options.$destroy);
  748. // Remove the focus traps that we added earlier for keeping focus within the dialog.
  749. if (topFocusTrap && topFocusTrap.parentNode) {
  750. topFocusTrap.parentNode.removeChild(topFocusTrap);
  751. }
  752. if (bottomFocusTrap && bottomFocusTrap.parentNode) {
  753. bottomFocusTrap.parentNode.removeChild(bottomFocusTrap);
  754. }
  755. // For navigation $destroy events, do a quick, non-animated removal,
  756. // but for normal closes (from clicks, etc) animate the removal
  757. return !!options.$destroy ? detachAndClean() : animateRemoval().then( detachAndClean );
  758. /**
  759. * For normal closes, animate the removal.
  760. * For forced closes (like $destroy events), skip the animations
  761. */
  762. function animateRemoval() {
  763. return dialogPopOut(element, options);
  764. }
  765. /**
  766. * Detach the element
  767. */
  768. function detachAndClean() {
  769. angular.element($document[0].body).removeClass('md-dialog-is-showing');
  770. // Only remove the element, if it's not provided through the contentElement option.
  771. if (!options.contentElement) {
  772. element.remove();
  773. } else {
  774. options.reverseContainerStretch();
  775. options.restoreContentElement();
  776. }
  777. if (!options.$destroy) options.origin.focus();
  778. }
  779. }
  780. function detectTheming(options) {
  781. // Only detect the theming, if the developer didn't specify the theme specifically.
  782. if (options.theme) return;
  783. options.theme = $mdTheming.defaultTheme();
  784. if (options.targetEvent && options.targetEvent.target) {
  785. var targetEl = angular.element(options.targetEvent.target);
  786. // Once the user specifies a targetEvent, we will automatically try to find the correct
  787. // nested theme.
  788. options.theme = (targetEl.controller('mdTheme') || {}).$mdTheme || options.theme;
  789. }
  790. }
  791. /**
  792. * Installs a content element to the current $$interimElement provider options.
  793. * @returns {Function} Function to restore the content element at its old DOM location.
  794. */
  795. function installContentElement(options) {
  796. var contentEl = options.contentElement;
  797. var restoreFn = null;
  798. if (angular.isString(contentEl)) {
  799. contentEl = document.querySelector(contentEl);
  800. restoreFn = createRestoreFn(contentEl);
  801. } else {
  802. contentEl = contentEl[0] || contentEl;
  803. // When the element is visible in the DOM, then we restore it at close of the dialog.
  804. // Otherwise it will be removed from the DOM after close.
  805. if (document.contains(contentEl)) {
  806. restoreFn = createRestoreFn(contentEl);
  807. } else {
  808. restoreFn = function() {
  809. contentEl.parentNode.removeChild(contentEl);
  810. }
  811. }
  812. }
  813. // Overwrite the options to use the content element.
  814. options.element = angular.element(contentEl);
  815. options.skipCompile = true;
  816. return restoreFn;
  817. function createRestoreFn(element) {
  818. var parent = element.parentNode;
  819. var nextSibling = element.nextElementSibling;
  820. return function() {
  821. if (!nextSibling) {
  822. // When the element didn't had any sibling, then it can be simply appended to the
  823. // parent, because it plays no role, which index it had before.
  824. parent.appendChild(element);
  825. } else {
  826. // When the element had a sibling, which marks the previous position of the element
  827. // in the DOM, we insert it correctly before the sibling, to have the same index as
  828. // before.
  829. parent.insertBefore(element, nextSibling);
  830. }
  831. }
  832. }
  833. }
  834. /**
  835. * Capture originator/trigger/from/to element information (if available)
  836. * and the parent container for the dialog; defaults to the $rootElement
  837. * unless overridden in the options.parent
  838. */
  839. function captureParentAndFromToElements(options) {
  840. options.origin = angular.extend({
  841. element: null,
  842. bounds: null,
  843. focus: angular.noop
  844. }, options.origin || {});
  845. options.parent = getDomElement(options.parent, $rootElement);
  846. options.closeTo = getBoundingClientRect(getDomElement(options.closeTo));
  847. options.openFrom = getBoundingClientRect(getDomElement(options.openFrom));
  848. if ( options.targetEvent ) {
  849. options.origin = getBoundingClientRect(options.targetEvent.target, options.origin);
  850. }
  851. /**
  852. * Identify the bounding RECT for the target element
  853. *
  854. */
  855. function getBoundingClientRect (element, orig) {
  856. var source = angular.element((element || {}));
  857. if (source && source.length) {
  858. // Compute and save the target element's bounding rect, so that if the
  859. // element is hidden when the dialog closes, we can shrink the dialog
  860. // back to the same position it expanded from.
  861. //
  862. // Checking if the source is a rect object or a DOM element
  863. var bounds = {top:0,left:0,height:0,width:0};
  864. var hasFn = angular.isFunction(source[0].getBoundingClientRect);
  865. return angular.extend(orig || {}, {
  866. element : hasFn ? source : undefined,
  867. bounds : hasFn ? source[0].getBoundingClientRect() : angular.extend({}, bounds, source[0]),
  868. focus : angular.bind(source, source.focus),
  869. });
  870. }
  871. }
  872. /**
  873. * If the specifier is a simple string selector, then query for
  874. * the DOM element.
  875. */
  876. function getDomElement(element, defaultElement) {
  877. if (angular.isString(element)) {
  878. element = $document[0].querySelector(element);
  879. }
  880. // If we have a reference to a raw dom element, always wrap it in jqLite
  881. return angular.element(element || defaultElement);
  882. }
  883. }
  884. /**
  885. * Listen for escape keys and outside clicks to auto close
  886. */
  887. function activateListeners(element, options) {
  888. var window = angular.element($window);
  889. var onWindowResize = $mdUtil.debounce(function() {
  890. stretchDialogContainerToViewport(element, options);
  891. }, 60);
  892. var removeListeners = [];
  893. var smartClose = function() {
  894. // Only 'confirm' dialogs have a cancel button... escape/clickOutside will
  895. // cancel or fallback to hide.
  896. var closeFn = ( options.$type == 'alert' ) ? $mdDialog.hide : $mdDialog.cancel;
  897. $mdUtil.nextTick(closeFn, true);
  898. };
  899. if (options.escapeToClose) {
  900. var parentTarget = options.parent;
  901. var keyHandlerFn = function(ev) {
  902. if (ev.keyCode === $mdConstant.KEY_CODE.ESCAPE) {
  903. ev.stopPropagation();
  904. ev.preventDefault();
  905. smartClose();
  906. }
  907. };
  908. // Add keydown listeners
  909. element.on('keydown', keyHandlerFn);
  910. parentTarget.on('keydown', keyHandlerFn);
  911. // Queue remove listeners function
  912. removeListeners.push(function() {
  913. element.off('keydown', keyHandlerFn);
  914. parentTarget.off('keydown', keyHandlerFn);
  915. });
  916. }
  917. // Register listener to update dialog on window resize
  918. window.on('resize', onWindowResize);
  919. removeListeners.push(function() {
  920. window.off('resize', onWindowResize);
  921. });
  922. if (options.clickOutsideToClose) {
  923. var target = element;
  924. var sourceElem;
  925. // Keep track of the element on which the mouse originally went down
  926. // so that we can only close the backdrop when the 'click' started on it.
  927. // A simple 'click' handler does not work,
  928. // it sets the target object as the element the mouse went down on.
  929. var mousedownHandler = function(ev) {
  930. sourceElem = ev.target;
  931. };
  932. // We check if our original element and the target is the backdrop
  933. // because if the original was the backdrop and the target was inside the dialog
  934. // we don't want to dialog to close.
  935. var mouseupHandler = function(ev) {
  936. if (sourceElem === target[0] && ev.target === target[0]) {
  937. ev.stopPropagation();
  938. ev.preventDefault();
  939. smartClose();
  940. }
  941. };
  942. // Add listeners
  943. target.on('mousedown', mousedownHandler);
  944. target.on('mouseup', mouseupHandler);
  945. // Queue remove listeners function
  946. removeListeners.push(function() {
  947. target.off('mousedown', mousedownHandler);
  948. target.off('mouseup', mouseupHandler);
  949. });
  950. }
  951. // Attach specific `remove` listener handler
  952. options.deactivateListeners = function() {
  953. removeListeners.forEach(function(removeFn) {
  954. removeFn();
  955. });
  956. options.deactivateListeners = null;
  957. };
  958. }
  959. /**
  960. * Show modal backdrop element...
  961. */
  962. function showBackdrop(scope, element, options) {
  963. if (options.disableParentScroll) {
  964. // !! DO this before creating the backdrop; since disableScrollAround()
  965. // configures the scroll offset; which is used by mdBackDrop postLink()
  966. options.restoreScroll = $mdUtil.disableScrollAround(element, options.parent);
  967. }
  968. if (options.hasBackdrop) {
  969. options.backdrop = $mdUtil.createBackdrop(scope, "md-dialog-backdrop md-opaque");
  970. $animate.enter(options.backdrop, options.parent);
  971. }
  972. /**
  973. * Hide modal backdrop element...
  974. */
  975. options.hideBackdrop = function hideBackdrop($destroy) {
  976. if (options.backdrop) {
  977. if ( !!$destroy ) options.backdrop.remove();
  978. else $animate.leave(options.backdrop);
  979. }
  980. if (options.disableParentScroll) {
  981. options.restoreScroll();
  982. delete options.restoreScroll;
  983. }
  984. options.hideBackdrop = null;
  985. };
  986. }
  987. /**
  988. * Inject ARIA-specific attributes appropriate for Dialogs
  989. */
  990. function configureAria(element, options) {
  991. var role = (options.$type === 'alert') ? 'alertdialog' : 'dialog';
  992. var dialogContent = element.find('md-dialog-content');
  993. var existingDialogId = element.attr('id');
  994. var dialogContentId = 'dialogContent_' + (existingDialogId || $mdUtil.nextUid());
  995. element.attr({
  996. 'role': role,
  997. 'tabIndex': '-1'
  998. });
  999. if (dialogContent.length === 0) {
  1000. dialogContent = element;
  1001. // If the dialog element already had an ID, don't clobber it.
  1002. if (existingDialogId) {
  1003. dialogContentId = existingDialogId;
  1004. }
  1005. }
  1006. dialogContent.attr('id', dialogContentId);
  1007. element.attr('aria-describedby', dialogContentId);
  1008. if (options.ariaLabel) {
  1009. $mdAria.expect(element, 'aria-label', options.ariaLabel);
  1010. }
  1011. else {
  1012. $mdAria.expectAsync(element, 'aria-label', function() {
  1013. var words = dialogContent.text().split(/\s+/);
  1014. if (words.length > 3) words = words.slice(0, 3).concat('...');
  1015. return words.join(' ');
  1016. });
  1017. }
  1018. // Set up elements before and after the dialog content to capture focus and
  1019. // redirect back into the dialog.
  1020. topFocusTrap = document.createElement('div');
  1021. topFocusTrap.classList.add('md-dialog-focus-trap');
  1022. topFocusTrap.tabIndex = 0;
  1023. bottomFocusTrap = topFocusTrap.cloneNode(false);
  1024. // When focus is about to move out of the dialog, we want to intercept it and redirect it
  1025. // back to the dialog element.
  1026. var focusHandler = function() {
  1027. element.focus();
  1028. };
  1029. topFocusTrap.addEventListener('focus', focusHandler);
  1030. bottomFocusTrap.addEventListener('focus', focusHandler);
  1031. // The top focus trap inserted immeidately before the md-dialog element (as a sibling).
  1032. // The bottom focus trap is inserted at the very end of the md-dialog element (as a child).
  1033. element[0].parentNode.insertBefore(topFocusTrap, element[0]);
  1034. element.after(bottomFocusTrap);
  1035. }
  1036. /**
  1037. * Prevents screen reader interaction behind modal window
  1038. * on swipe interfaces
  1039. */
  1040. function lockScreenReader(element, options) {
  1041. var isHidden = true;
  1042. // get raw DOM node
  1043. walkDOM(element[0]);
  1044. options.unlockScreenReader = function() {
  1045. isHidden = false;
  1046. walkDOM(element[0]);
  1047. options.unlockScreenReader = null;
  1048. };
  1049. /**
  1050. * Walk DOM to apply or remove aria-hidden on sibling nodes
  1051. * and parent sibling nodes
  1052. *
  1053. */
  1054. function walkDOM(element) {
  1055. while (element.parentNode) {
  1056. if (element === document.body) {
  1057. return;
  1058. }
  1059. var children = element.parentNode.children;
  1060. for (var i = 0; i < children.length; i++) {
  1061. // skip over child if it is an ascendant of the dialog
  1062. // or a script or style tag
  1063. if (element !== children[i] && !isNodeOneOf(children[i], ['SCRIPT', 'STYLE'])) {
  1064. children[i].setAttribute('aria-hidden', isHidden);
  1065. }
  1066. }
  1067. walkDOM(element = element.parentNode);
  1068. }
  1069. }
  1070. }
  1071. /**
  1072. * Ensure the dialog container fill-stretches to the viewport
  1073. */
  1074. function stretchDialogContainerToViewport(container, options) {
  1075. var isFixed = $window.getComputedStyle($document[0].body).position == 'fixed';
  1076. var backdrop = options.backdrop ? $window.getComputedStyle(options.backdrop[0]) : null;
  1077. var height = backdrop ? Math.min($document[0].body.clientHeight, Math.ceil(Math.abs(parseInt(backdrop.height, 10)))) : 0;
  1078. var previousStyles = {
  1079. top: container.css('top'),
  1080. height: container.css('height')
  1081. };
  1082. container.css({
  1083. top: (isFixed ? $mdUtil.scrollTop(options.parent) : 0) + 'px',
  1084. height: height ? height + 'px' : '100%'
  1085. });
  1086. return function() {
  1087. // Reverts the modified styles back to the previous values.
  1088. // This is needed for contentElements, which should have the same styles after close
  1089. // as before.
  1090. container.css(previousStyles);
  1091. };
  1092. }
  1093. /**
  1094. * Dialog open and pop-in animation
  1095. */
  1096. function dialogPopIn(container, options) {
  1097. // Add the `md-dialog-container` to the DOM
  1098. options.parent.append(container);
  1099. options.reverseContainerStretch = stretchDialogContainerToViewport(container, options);
  1100. var dialogEl = container.find('md-dialog');
  1101. var animator = $mdUtil.dom.animator;
  1102. var buildTranslateToOrigin = animator.calculateZoomToOrigin;
  1103. var translateOptions = {transitionInClass: 'md-transition-in', transitionOutClass: 'md-transition-out'};
  1104. var from = animator.toTransformCss(buildTranslateToOrigin(dialogEl, options.openFrom || options.origin));
  1105. var to = animator.toTransformCss(""); // defaults to center display (or parent or $rootElement)
  1106. dialogEl.toggleClass('md-dialog-fullscreen', !!options.fullscreen);
  1107. return animator
  1108. .translate3d(dialogEl, from, to, translateOptions)
  1109. .then(function(animateReversal) {
  1110. // Build a reversal translate function synced to this translation...
  1111. options.reverseAnimate = function() {
  1112. delete options.reverseAnimate;
  1113. if (options.closeTo) {
  1114. // Using the opposite classes to create a close animation to the closeTo element
  1115. translateOptions = {transitionInClass: 'md-transition-out', transitionOutClass: 'md-transition-in'};
  1116. from = to;
  1117. to = animator.toTransformCss(buildTranslateToOrigin(dialogEl, options.closeTo));
  1118. return animator
  1119. .translate3d(dialogEl, from, to,translateOptions);
  1120. }
  1121. return animateReversal(
  1122. to = animator.toTransformCss(
  1123. // in case the origin element has moved or is hidden,
  1124. // let's recalculate the translateCSS
  1125. buildTranslateToOrigin(dialogEl, options.origin)
  1126. )
  1127. );
  1128. };
  1129. // Function to revert the generated animation styles on the dialog element.
  1130. // Useful when using a contentElement instead of a template.
  1131. options.clearAnimate = function() {
  1132. delete options.clearAnimate;
  1133. // Remove the transition classes, added from $animateCSS, since those can't be removed
  1134. // by reversely running the animator.
  1135. dialogEl.removeClass([
  1136. translateOptions.transitionOutClass,
  1137. translateOptions.transitionInClass
  1138. ].join(' '));
  1139. // Run the animation reversely to remove the previous added animation styles.
  1140. return animator.translate3d(dialogEl, to, animator.toTransformCss(''), {});
  1141. };
  1142. return true;
  1143. });
  1144. }
  1145. /**
  1146. * Dialog close and pop-out animation
  1147. */
  1148. function dialogPopOut(container, options) {
  1149. return options.reverseAnimate().then(function() {
  1150. if (options.contentElement) {
  1151. // When we use a contentElement, we want the element to be the same as before.
  1152. // That means, that we have to clear all the animation properties, like transform.
  1153. options.clearAnimate();
  1154. }
  1155. });
  1156. }
  1157. /**
  1158. * Utility function to filter out raw DOM nodes
  1159. */
  1160. function isNodeOneOf(elem, nodeTypeArray) {
  1161. if (nodeTypeArray.indexOf(elem.nodeName) !== -1) {
  1162. return true;
  1163. }
  1164. }
  1165. }
  1166. }
  1167. ngmaterial.components.dialog = angular.module("material.components.dialog");