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