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.

1286 lines
46 KiB

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