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.

3545 lines
100 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.panel
  12. */
  13. MdPanelService['$inject'] = ["presets", "$rootElement", "$rootScope", "$injector", "$window"];
  14. angular
  15. .module('material.components.panel', [
  16. 'material.core',
  17. 'material.components.backdrop'
  18. ])
  19. .provider('$mdPanel', MdPanelProvider);
  20. /*****************************************************************************
  21. * PUBLIC DOCUMENTATION *
  22. *****************************************************************************/
  23. /**
  24. * @ngdoc service
  25. * @name $mdPanelProvider
  26. * @module material.components.panel
  27. *
  28. * @description
  29. * `$mdPanelProvider` allows users to create configuration presets that will be
  30. * stored within a cached presets object. When the configuration is needed, the
  31. * user can request the preset by passing it as the first parameter in the
  32. * `$mdPanel.create` or `$mdPanel.open` methods.
  33. *
  34. * @usage
  35. * <hljs lang="js">
  36. * (function(angular, undefined) {
  37. * 'use strict';
  38. *
  39. * angular
  40. * .module('demoApp', ['ngMaterial'])
  41. * .config(DemoConfig)
  42. * .controller('DemoCtrl', DemoCtrl)
  43. * .controller('DemoMenuCtrl', DemoMenuCtrl);
  44. *
  45. * function DemoConfig($mdPanelProvider) {
  46. * $mdPanelProvider.definePreset('demoPreset', {
  47. * attachTo: angular.element(document.body),
  48. * controller: DemoMenuCtrl,
  49. * controllerAs: 'ctrl',
  50. * template: '' +
  51. * '<div class="menu-panel" md-whiteframe="4">' +
  52. * ' <div class="menu-content">' +
  53. * ' <div class="menu-item" ng-repeat="item in ctrl.items">' +
  54. * ' <button class="md-button">' +
  55. * ' <span>{{item}}</span>' +
  56. * ' </button>' +
  57. * ' </div>' +
  58. * ' <md-divider></md-divider>' +
  59. * ' <div class="menu-item">' +
  60. * ' <button class="md-button" ng-click="ctrl.closeMenu()">' +
  61. * ' <span>Close Menu</span>' +
  62. * ' </button>' +
  63. * ' </div>' +
  64. * ' </div>' +
  65. * '</div>',
  66. * panelClass: 'menu-panel-container',
  67. * focusOnOpen: false,
  68. * zIndex: 100,
  69. * propagateContainerEvents: true,
  70. * groupName: 'menus'
  71. * });
  72. * }
  73. *
  74. * function PanelProviderCtrl($mdPanel) {
  75. * this.navigation = {
  76. * name: 'navigation',
  77. * items: [
  78. * 'Home',
  79. * 'About',
  80. * 'Contact'
  81. * ]
  82. * };
  83. * this.favorites = {
  84. * name: 'favorites',
  85. * items: [
  86. * 'Add to Favorites'
  87. * ]
  88. * };
  89. * this.more = {
  90. * name: 'more',
  91. * items: [
  92. * 'Account',
  93. * 'Sign Out'
  94. * ]
  95. * };
  96. *
  97. * $mdPanel.newPanelGroup('menus', {
  98. * maxOpen: 2
  99. * });
  100. *
  101. * this.showMenu = function($event, menu) {
  102. * $mdPanel.open('demoPreset', {
  103. * id: 'menu_' + menu.name,
  104. * position: $mdPanel.newPanelPosition()
  105. * .relativeTo($event.srcElement)
  106. * .addPanelPosition(
  107. * $mdPanel.xPosition.ALIGN_START,
  108. * $mdPanel.yPosition.BELOW
  109. * ),
  110. * locals: {
  111. * items: menu.items
  112. * },
  113. * openFrom: $event
  114. * });
  115. * };
  116. * }
  117. *
  118. * function PanelMenuCtrl(mdPanelRef) {
  119. * this.closeMenu = function() {
  120. * mdPanelRef && mdPanelRef.close();
  121. * };
  122. * }
  123. * })(angular);
  124. * </hljs>
  125. */
  126. /**
  127. * @ngdoc method
  128. * @name $mdPanelProvider#definePreset
  129. * @description
  130. * Takes the passed in preset name and preset configuration object and adds it
  131. * to the `_presets` object of the provider. This `_presets` object is then
  132. * passed along to the `$mdPanel` service.
  133. *
  134. * @param {string} name Preset name.
  135. * @param {!Object} preset Specific configuration object that can contain any
  136. * and all of the parameters avaialble within the `$mdPanel.create` method.
  137. * However, parameters that pertain to id, position, animation, and user
  138. * interaction are not allowed and will be removed from the preset
  139. * configuration.
  140. */
  141. /*****************************************************************************
  142. * MdPanel Service *
  143. *****************************************************************************/
  144. /**
  145. * @ngdoc service
  146. * @name $mdPanel
  147. * @module material.components.panel
  148. *
  149. * @description
  150. * `$mdPanel` is a robust, low-level service for creating floating panels on
  151. * the screen. It can be used to implement tooltips, dialogs, pop-ups, etc.
  152. *
  153. * @usage
  154. * <hljs lang="js">
  155. * (function(angular, undefined) {
  156. * 'use strict';
  157. *
  158. * angular
  159. * .module('demoApp', ['ngMaterial'])
  160. * .controller('DemoDialogController', DialogController);
  161. *
  162. * var panelRef;
  163. *
  164. * function showPanel($event) {
  165. * var panelPosition = $mdPanel.newPanelPosition()
  166. * .absolute()
  167. * .top('50%')
  168. * .left('50%');
  169. *
  170. * var panelAnimation = $mdPanel.newPanelAnimation()
  171. * .targetEvent($event)
  172. * .defaultAnimation('md-panel-animate-fly')
  173. * .closeTo('.show-button');
  174. *
  175. * var config = {
  176. * attachTo: angular.element(document.body),
  177. * controller: DialogController,
  178. * controllerAs: 'ctrl',
  179. * position: panelPosition,
  180. * animation: panelAnimation,
  181. * targetEvent: $event,
  182. * templateUrl: 'dialog-template.html',
  183. * clickOutsideToClose: true,
  184. * escapeToClose: true,
  185. * focusOnOpen: true
  186. * }
  187. *
  188. * $mdPanel.open(config)
  189. * .then(function(result) {
  190. * panelRef = result;
  191. * });
  192. * }
  193. *
  194. * function DialogController(MdPanelRef) {
  195. * function closeDialog() {
  196. * if (MdPanelRef) MdPanelRef.close();
  197. * }
  198. * }
  199. * })(angular);
  200. * </hljs>
  201. */
  202. /**
  203. * @ngdoc method
  204. * @name $mdPanel#create
  205. * @description
  206. * Creates a panel with the specified options.
  207. *
  208. * @param config {!Object=} Specific configuration object that may contain the
  209. * following properties:
  210. *
  211. * - `id` - `{string=}`: An ID to track the panel by. When an ID is provided,
  212. * the created panel is added to a tracked panels object. Any subsequent
  213. * requests made to create a panel with that ID are ignored. This is useful
  214. * in having the panel service not open multiple panels from the same user
  215. * interaction when there is no backdrop and events are propagated. Defaults
  216. * to an arbitrary string that is not tracked.
  217. * - `template` - `{string=}`: HTML template to show in the panel. This
  218. * **must** be trusted HTML with respect to Angulars
  219. * [$sce service](https://docs.angularjs.org/api/ng/service/$sce).
  220. * - `templateUrl` - `{string=}`: The URL that will be used as the content of
  221. * the panel.
  222. * - `contentElement` - `{(string|!angular.JQLite|!Element)=}`: Pre-compiled
  223. * element to be used as the panel's content.
  224. * - `controller` - `{(function|string)=}`: The controller to associate with
  225. * the panel. The controller can inject a reference to the returned
  226. * panelRef, which allows the panel to be closed, hidden, and shown. Any
  227. * fields passed in through locals or resolve will be bound to the
  228. * controller.
  229. * - `controllerAs` - `{string=}`: An alias to assign the controller to on
  230. * the scope.
  231. * - `bindToController` - `{boolean=}`: Binds locals to the controller
  232. * instead of passing them in. Defaults to true, as this is a best
  233. * practice.
  234. * - `locals` - `{Object=}`: An object containing key/value pairs. The keys
  235. * will be used as names of values to inject into the controller. For
  236. * example, `locals: {three: 3}` would inject `three` into the controller,
  237. * with the value 3.
  238. * - `resolve` - `{Object=}`: Similar to locals, except it takes promises as
  239. * values. The panel will not open until all of the promises resolve.
  240. * - `attachTo` - `{(string|!angular.JQLite|!Element)=}`: The element to
  241. * attach the panel to. Defaults to appending to the root element of the
  242. * application.
  243. * - `propagateContainerEvents` - `{boolean=}`: Whether pointer or touch
  244. * events should be allowed to propagate 'go through' the container, aka the
  245. * wrapper, of the panel. Defaults to false.
  246. * - `panelClass` - `{string=}`: A css class to apply to the panel element.
  247. * This class should define any borders, box-shadow, etc. for the panel.
  248. * - `zIndex` - `{number=}`: The z-index to place the panel at.
  249. * Defaults to 80.
  250. * - `position` - `{MdPanelPosition=}`: An MdPanelPosition object that
  251. * specifies the alignment of the panel. For more information, see
  252. * `MdPanelPosition`.
  253. * - `clickOutsideToClose` - `{boolean=}`: Whether the user can click
  254. * outside the panel to close it. Defaults to false.
  255. * - `escapeToClose` - `{boolean=}`: Whether the user can press escape to
  256. * close the panel. Defaults to false.
  257. * - `onCloseSuccess` - `{function(!panelRef, string)=}`: Function that is
  258. * called after the close successfully finishes. The first parameter passed
  259. * into this function is the current panelRef and the 2nd is an optional
  260. * string explaining the close reason. The currently supported closeReasons
  261. * can be found in the MdPanelRef.closeReasons enum. These are by default
  262. * passed along by the panel.
  263. * - `trapFocus` - `{boolean=}`: Whether focus should be trapped within the
  264. * panel. If `trapFocus` is true, the user will not be able to interact
  265. * with the rest of the page until the panel is dismissed. Defaults to
  266. * false.
  267. * - `focusOnOpen` - `{boolean=}`: An option to override focus behavior on
  268. * open. Only disable if focusing some other way, as focus management is
  269. * required for panels to be accessible. Defaults to true.
  270. * - `fullscreen` - `{boolean=}`: Whether the panel should be full screen.
  271. * Applies the class `._md-panel-fullscreen` to the panel on open. Defaults
  272. * to false.
  273. * - `animation` - `{MdPanelAnimation=}`: An MdPanelAnimation object that
  274. * specifies the animation of the panel. For more information, see
  275. * `MdPanelAnimation`.
  276. * - `hasBackdrop` - `{boolean=}`: Whether there should be an opaque backdrop
  277. * behind the panel. Defaults to false.
  278. * - `disableParentScroll` - `{boolean=}`: Whether the user can scroll the
  279. * page behind the panel. Defaults to false.
  280. * - `onDomAdded` - `{function=}`: Callback function used to announce when
  281. * the panel is added to the DOM.
  282. * - `onOpenComplete` - `{function=}`: Callback function used to announce
  283. * when the open() action is finished.
  284. * - `onRemoving` - `{function=}`: Callback function used to announce the
  285. * close/hide() action is starting.
  286. * - `onDomRemoved` - `{function=}`: Callback function used to announce when
  287. * the panel is removed from the DOM.
  288. * - `origin` - `{(string|!angular.JQLite|!Element)=}`: The element to focus
  289. * on when the panel closes. This is commonly the element which triggered
  290. * the opening of the panel. If you do not use `origin`, you need to control
  291. * the focus manually.
  292. * - `groupName` - `{(string|!Array<string>)=}`: A group name or an array of
  293. * group names. The group name is used for creating a group of panels. The
  294. * group is used for configuring the number of open panels and identifying
  295. * specific behaviors for groups. For instance, all tooltips could be
  296. * identified using the same groupName.
  297. *
  298. * @returns {!MdPanelRef} panelRef
  299. */
  300. /**
  301. * @ngdoc method
  302. * @name $mdPanel#open
  303. * @description
  304. * Calls the create method above, then opens the panel. This is a shortcut for
  305. * creating and then calling open manually. If custom methods need to be
  306. * called when the panel is added to the DOM or opened, do not use this method.
  307. * Instead create the panel, chain promises on the domAdded and openComplete
  308. * methods, and call open from the returned panelRef.
  309. *
  310. * @param {!Object=} config Specific configuration object that may contain
  311. * the properties defined in `$mdPanel.create`.
  312. * @returns {!angular.$q.Promise<!MdPanelRef>} panelRef A promise that resolves
  313. * to an instance of the panel.
  314. */
  315. /**
  316. * @ngdoc method
  317. * @name $mdPanel#newPanelPosition
  318. * @description
  319. * Returns a new instance of the MdPanelPosition object. Use this to create
  320. * the position config object.
  321. *
  322. * @returns {!MdPanelPosition} panelPosition
  323. */
  324. /**
  325. * @ngdoc method
  326. * @name $mdPanel#newPanelAnimation
  327. * @description
  328. * Returns a new instance of the MdPanelAnimation object. Use this to create
  329. * the animation config object.
  330. *
  331. * @returns {!MdPanelAnimation} panelAnimation
  332. */
  333. /**
  334. * @ngdoc method
  335. * @name $mdPanel#newPanelGroup
  336. * @description
  337. * Creates a panel group and adds it to a tracked list of panel groups.
  338. *
  339. * @param {string} groupName Name of the group to create.
  340. * @param {!Object=} config Specific configuration object that may contain the
  341. * following properties:
  342. *
  343. * - `maxOpen` - `{number=}`: The maximum number of panels that are allowed to
  344. * be open within a defined panel group.
  345. *
  346. * @returns {!Object<string,
  347. * {panels: !Array<!MdPanelRef>,
  348. * openPanels: !Array<!MdPanelRef>,
  349. * maxOpen: number}>} panelGroup
  350. */
  351. /**
  352. * @ngdoc method
  353. * @name $mdPanel#setGroupMaxOpen
  354. * @description
  355. * Sets the maximum number of panels in a group that can be opened at a given
  356. * time.
  357. *
  358. * @param {string} groupName The name of the group to configure.
  359. * @param {number} maxOpen The maximum number of panels that can be
  360. * opened. Infinity can be passed in to remove the maxOpen limit.
  361. */
  362. /*****************************************************************************
  363. * MdPanelRef *
  364. *****************************************************************************/
  365. /**
  366. * @ngdoc type
  367. * @name MdPanelRef
  368. * @module material.components.panel
  369. * @description
  370. * A reference to a created panel. This reference contains a unique id for the
  371. * panel, along with the following properties:
  372. *
  373. * - `id` - `{string}`: The unique id for the panel. This id is used to track
  374. * when a panel was interacted with.
  375. * - `config` - `{!Object=}`: The entire config object that was used in
  376. * create.
  377. * - `isAttached` - `{boolean}`: Whether the panel is attached to the DOM.
  378. * Visibility to the user does not factor into isAttached.
  379. * - `panelContainer` - `{angular.JQLite}`: The wrapper element containing the
  380. * panel. This property is added in order to have access to the `addClass`,
  381. * `removeClass`, `toggleClass`, etc methods.
  382. * - `panelEl` - `{angular.JQLite}`: The panel element. This property is added
  383. * in order to have access to the `addClass`, `removeClass`, `toggleClass`,
  384. * etc methods.
  385. */
  386. /**
  387. * @ngdoc method
  388. * @name MdPanelRef#open
  389. * @description
  390. * Attaches and shows the panel.
  391. *
  392. * @returns {!angular.$q.Promise} A promise that is resolved when the panel is
  393. * opened.
  394. */
  395. /**
  396. * @ngdoc method
  397. * @name MdPanelRef#close
  398. * @description
  399. * Hides and detaches the panel. Note that this will **not** destroy the panel.
  400. * If you don't intend on using the panel again, call the {@link #destroy
  401. * destroy} method afterwards.
  402. *
  403. * @returns {!angular.$q.Promise} A promise that is resolved when the panel is
  404. * closed.
  405. */
  406. /**
  407. * @ngdoc method
  408. * @name MdPanelRef#attach
  409. * @description
  410. * Create the panel elements and attach them to the DOM. The panel will be
  411. * hidden by default.
  412. *
  413. * @returns {!angular.$q.Promise} A promise that is resolved when the panel is
  414. * attached.
  415. */
  416. /**
  417. * @ngdoc method
  418. * @name MdPanelRef#detach
  419. * @description
  420. * Removes the panel from the DOM. This will NOT hide the panel before removing
  421. * it.
  422. *
  423. * @returns {!angular.$q.Promise} A promise that is resolved when the panel is
  424. * detached.
  425. */
  426. /**
  427. * @ngdoc method
  428. * @name MdPanelRef#show
  429. * @description
  430. * Shows the panel.
  431. *
  432. * @returns {!angular.$q.Promise} A promise that is resolved when the panel has
  433. * shown and animations are completed.
  434. */
  435. /**
  436. * @ngdoc method
  437. * @name MdPanelRef#hide
  438. * @description
  439. * Hides the panel.
  440. *
  441. * @returns {!angular.$q.Promise} A promise that is resolved when the panel has
  442. * hidden and animations are completed.
  443. */
  444. /**
  445. * @ngdoc method
  446. * @name MdPanelRef#destroy
  447. * @description
  448. * Destroys the panel. The panel cannot be opened again after this is called.
  449. */
  450. /**
  451. * @ngdoc method
  452. * @name MdPanelRef#addClass
  453. * @deprecated
  454. * This method is in the process of being deprecated in favor of using the panel
  455. * and container JQLite elements that are referenced in the MdPanelRef object.
  456. * Full deprecation is scheduled for material 1.2.
  457. * @description
  458. * Adds a class to the panel. DO NOT use this hide/show the panel.
  459. *
  460. * @param {string} newClass class to be added.
  461. * @param {boolean} toElement Whether or not to add the class to the panel
  462. * element instead of the container.
  463. */
  464. /**
  465. * @ngdoc method
  466. * @name MdPanelRef#removeClass
  467. * @deprecated
  468. * This method is in the process of being deprecated in favor of using the panel
  469. * and container JQLite elements that are referenced in the MdPanelRef object.
  470. * Full deprecation is scheduled for material 1.2.
  471. * @description
  472. * Removes a class from the panel. DO NOT use this to hide/show the panel.
  473. *
  474. * @param {string} oldClass Class to be removed.
  475. * @param {boolean} fromElement Whether or not to remove the class from the
  476. * panel element instead of the container.
  477. */
  478. /**
  479. * @ngdoc method
  480. * @name MdPanelRef#toggleClass
  481. * @deprecated
  482. * This method is in the process of being deprecated in favor of using the panel
  483. * and container JQLite elements that are referenced in the MdPanelRef object.
  484. * Full deprecation is scheduled for material 1.2.
  485. * @description
  486. * Toggles a class on the panel. DO NOT use this to hide/show the panel.
  487. *
  488. * @param {string} toggleClass Class to be toggled.
  489. * @param {boolean} onElement Whether or not to remove the class from the panel
  490. * element instead of the container.
  491. */
  492. /**
  493. * @ngdoc method
  494. * @name MdPanelRef#updatePosition
  495. * @description
  496. * Updates the position configuration of a panel. Use this to update the
  497. * position of a panel that is open, without having to close and re-open the
  498. * panel.
  499. *
  500. * @param {!MdPanelPosition} position
  501. */
  502. /**
  503. * @ngdoc method
  504. * @name MdPanelRef#addToGroup
  505. * @description
  506. * Adds a panel to a group if the panel does not exist within the group already.
  507. * A panel can only exist within a single group.
  508. *
  509. * @param {string} groupName The name of the group to add the panel to.
  510. */
  511. /**
  512. * @ngdoc method
  513. * @name MdPanelRef#removeFromGroup
  514. * @description
  515. * Removes a panel from a group if the panel exists within that group. The group
  516. * must be created ahead of time.
  517. *
  518. * @param {string} groupName The name of the group.
  519. */
  520. /**
  521. * @ngdoc method
  522. * @name MdPanelRef#registerInterceptor
  523. * @description
  524. * Registers an interceptor with the panel. The callback should return a promise,
  525. * which will allow the action to continue when it gets resolved, or will
  526. * prevent an action if it is rejected. The interceptors are called sequentially
  527. * and it reverse order. `type` must be one of the following
  528. * values available on `$mdPanel.interceptorTypes`:
  529. * * `CLOSE` - Gets called before the panel begins closing.
  530. *
  531. * @param {string} type Type of interceptor.
  532. * @param {!angular.$q.Promise<any>} callback Callback to be registered.
  533. * @returns {!MdPanelRef}
  534. */
  535. /**
  536. * @ngdoc method
  537. * @name MdPanelRef#removeInterceptor
  538. * @description
  539. * Removes a registered interceptor.
  540. *
  541. * @param {string} type Type of interceptor to be removed.
  542. * @param {function(): !angular.$q.Promise<any>} callback Interceptor to be removed.
  543. * @returns {!MdPanelRef}
  544. */
  545. /**
  546. * @ngdoc method
  547. * @name MdPanelRef#removeAllInterceptors
  548. * @description
  549. * Removes all interceptors. If a type is supplied, only the
  550. * interceptors of that type will be cleared.
  551. *
  552. * @param {string=} type Type of interceptors to be removed.
  553. * @returns {!MdPanelRef}
  554. */
  555. /**
  556. * @ngdoc method
  557. * @name MdPanelRef#updateAnimation
  558. * @description
  559. * Updates the animation configuration for a panel. You can use this to change
  560. * the panel's animation without having to re-create it.
  561. *
  562. * @param {!MdPanelAnimation} animation
  563. */
  564. /*****************************************************************************
  565. * MdPanelPosition *
  566. *****************************************************************************/
  567. /**
  568. * @ngdoc type
  569. * @name MdPanelPosition
  570. * @module material.components.panel
  571. * @description
  572. *
  573. * Object for configuring the position of the panel.
  574. *
  575. * @usage
  576. *
  577. * #### Centering the panel
  578. *
  579. * <hljs lang="js">
  580. * new MdPanelPosition().absolute().center();
  581. * </hljs>
  582. *
  583. * #### Overlapping the panel with an element
  584. *
  585. * <hljs lang="js">
  586. * new MdPanelPosition()
  587. * .relativeTo(someElement)
  588. * .addPanelPosition(
  589. * $mdPanel.xPosition.ALIGN_START,
  590. * $mdPanel.yPosition.ALIGN_TOPS
  591. * );
  592. * </hljs>
  593. *
  594. * #### Aligning the panel with the bottom of an element
  595. *
  596. * <hljs lang="js">
  597. * new MdPanelPosition()
  598. * .relativeTo(someElement)
  599. * .addPanelPosition($mdPanel.xPosition.CENTER, $mdPanel.yPosition.BELOW);
  600. * </hljs>
  601. */
  602. /**
  603. * @ngdoc method
  604. * @name MdPanelPosition#absolute
  605. * @description
  606. * Positions the panel absolutely relative to the parent element. If the parent
  607. * is document.body, this is equivalent to positioning the panel absolutely
  608. * within the viewport.
  609. *
  610. * @returns {!MdPanelPosition}
  611. */
  612. /**
  613. * @ngdoc method
  614. * @name MdPanelPosition#relativeTo
  615. * @description
  616. * Positions the panel relative to a specific element.
  617. *
  618. * @param {string|!Element|!angular.JQLite} element Query selector, DOM element,
  619. * or angular element to position the panel with respect to.
  620. * @returns {!MdPanelPosition}
  621. */
  622. /**
  623. * @ngdoc method
  624. * @name MdPanelPosition#top
  625. * @description
  626. * Sets the value of `top` for the panel. Clears any previously set vertical
  627. * position.
  628. *
  629. * @param {string=} top Value of `top`. Defaults to '0'.
  630. * @returns {!MdPanelPosition}
  631. */
  632. /**
  633. * @ngdoc method
  634. * @name MdPanelPosition#bottom
  635. * @description
  636. * Sets the value of `bottom` for the panel. Clears any previously set vertical
  637. * position.
  638. *
  639. * @param {string=} bottom Value of `bottom`. Defaults to '0'.
  640. * @returns {!MdPanelPosition}
  641. */
  642. /**
  643. * @ngdoc method
  644. * @name MdPanelPosition#start
  645. * @description
  646. * Sets the panel to the start of the page - `left` if `ltr` or `right` for
  647. * `rtl`. Clears any previously set horizontal position.
  648. *
  649. * @param {string=} start Value of position. Defaults to '0'.
  650. * @returns {!MdPanelPosition}
  651. */
  652. /**
  653. * @ngdoc method
  654. * @name MdPanelPosition#end
  655. * @description
  656. * Sets the panel to the end of the page - `right` if `ltr` or `left` for `rtl`.
  657. * Clears any previously set horizontal position.
  658. *
  659. * @param {string=} end Value of position. Defaults to '0'.
  660. * @returns {!MdPanelPosition}
  661. */
  662. /**
  663. * @ngdoc method
  664. * @name MdPanelPosition#left
  665. * @description
  666. * Sets the value of `left` for the panel. Clears any previously set
  667. * horizontal position.
  668. *
  669. * @param {string=} left Value of `left`. Defaults to '0'.
  670. * @returns {!MdPanelPosition}
  671. */
  672. /**
  673. * @ngdoc method
  674. * @name MdPanelPosition#right
  675. * @description
  676. * Sets the value of `right` for the panel. Clears any previously set
  677. * horizontal position.
  678. *
  679. * @param {string=} right Value of `right`. Defaults to '0'.
  680. * @returns {!MdPanelPosition}
  681. */
  682. /**
  683. * @ngdoc method
  684. * @name MdPanelPosition#centerHorizontally
  685. * @description
  686. * Centers the panel horizontally in the viewport. Clears any previously set
  687. * horizontal position.
  688. *
  689. * @returns {!MdPanelPosition}
  690. */
  691. /**
  692. * @ngdoc method
  693. * @name MdPanelPosition#centerVertically
  694. * @description
  695. * Centers the panel vertically in the viewport. Clears any previously set
  696. * vertical position.
  697. *
  698. * @returns {!MdPanelPosition}
  699. */
  700. /**
  701. * @ngdoc method
  702. * @name MdPanelPosition#center
  703. * @description
  704. * Centers the panel horizontally and vertically in the viewport. This is
  705. * equivalent to calling both `centerHorizontally` and `centerVertically`.
  706. * Clears any previously set horizontal and vertical positions.
  707. *
  708. * @returns {!MdPanelPosition}
  709. */
  710. /**
  711. * @ngdoc method
  712. * @name MdPanelPosition#addPanelPosition
  713. * @description
  714. * Sets the x and y position for the panel relative to another element. Can be
  715. * called multiple times to specify an ordered list of panel positions. The
  716. * first position which allows the panel to be completely on-screen will be
  717. * chosen; the last position will be chose whether it is on-screen or not.
  718. *
  719. * xPosition must be one of the following values available on
  720. * $mdPanel.xPosition:
  721. *
  722. *
  723. * CENTER | ALIGN_START | ALIGN_END | OFFSET_START | OFFSET_END
  724. *
  725. * <pre>
  726. * *************
  727. * * *
  728. * * PANEL *
  729. * * *
  730. * *************
  731. * A B C D E
  732. *
  733. * A: OFFSET_START (for LTR displays)
  734. * B: ALIGN_START (for LTR displays)
  735. * C: CENTER
  736. * D: ALIGN_END (for LTR displays)
  737. * E: OFFSET_END (for LTR displays)
  738. * </pre>
  739. *
  740. * yPosition must be one of the following values available on
  741. * $mdPanel.yPosition:
  742. *
  743. * CENTER | ALIGN_TOPS | ALIGN_BOTTOMS | ABOVE | BELOW
  744. *
  745. * <pre>
  746. * F
  747. * G *************
  748. * * *
  749. * H * PANEL *
  750. * * *
  751. * I *************
  752. * J
  753. *
  754. * F: BELOW
  755. * G: ALIGN_TOPS
  756. * H: CENTER
  757. * I: ALIGN_BOTTOMS
  758. * J: ABOVE
  759. * </pre>
  760. *
  761. * @param {string} xPosition
  762. * @param {string} yPosition
  763. * @returns {!MdPanelPosition}
  764. */
  765. /**
  766. * @ngdoc method
  767. * @name MdPanelPosition#withOffsetX
  768. * @description
  769. * Sets the value of the offset in the x-direction.
  770. *
  771. * @param {string} offsetX
  772. * @returns {!MdPanelPosition}
  773. */
  774. /**
  775. * @ngdoc method
  776. * @name MdPanelPosition#withOffsetY
  777. * @description
  778. * Sets the value of the offset in the y-direction.
  779. *
  780. * @param {string} offsetY
  781. * @returns {!MdPanelPosition}
  782. */
  783. /*****************************************************************************
  784. * MdPanelAnimation *
  785. *****************************************************************************/
  786. /**
  787. * @ngdoc type
  788. * @name MdPanelAnimation
  789. * @module material.components.panel
  790. * @description
  791. * Animation configuration object. To use, create an MdPanelAnimation with the
  792. * desired properties, then pass the object as part of $mdPanel creation.
  793. *
  794. * @usage
  795. *
  796. * <hljs lang="js">
  797. * var panelAnimation = new MdPanelAnimation()
  798. * .openFrom(myButtonEl)
  799. * .duration(1337)
  800. * .closeTo('.my-button')
  801. * .withAnimation($mdPanel.animation.SCALE);
  802. *
  803. * $mdPanel.create({
  804. * animation: panelAnimation
  805. * });
  806. * </hljs>
  807. */
  808. /**
  809. * @ngdoc method
  810. * @name MdPanelAnimation#openFrom
  811. * @description
  812. * Specifies where to start the open animation. `openFrom` accepts a
  813. * click event object, query selector, DOM element, or a Rect object that
  814. * is used to determine the bounds. When passed a click event, the location
  815. * of the click will be used as the position to start the animation.
  816. *
  817. * @param {string|!Element|!Event|{top: number, left: number}}
  818. * @returns {!MdPanelAnimation}
  819. */
  820. /**
  821. * @ngdoc method
  822. * @name MdPanelAnimation#closeTo
  823. * @description
  824. * Specifies where to animate the panel close. `closeTo` accepts a
  825. * query selector, DOM element, or a Rect object that is used to determine
  826. * the bounds.
  827. *
  828. * @param {string|!Element|{top: number, left: number}}
  829. * @returns {!MdPanelAnimation}
  830. */
  831. /**
  832. * @ngdoc method
  833. * @name MdPanelAnimation#withAnimation
  834. * @description
  835. * Specifies the animation class.
  836. *
  837. * There are several default animations that can be used:
  838. * ($mdPanel.animation)
  839. * SLIDE: The panel slides in and out from the specified
  840. * elements. It will not fade in or out.
  841. * SCALE: The panel scales in and out. Slide and fade are
  842. * included in this animation.
  843. * FADE: The panel fades in and out.
  844. *
  845. * Custom classes will by default fade in and out unless
  846. * "transition: opacity 1ms" is added to the to custom class.
  847. *
  848. * @param {string|{open: string, close: string}} cssClass
  849. * @returns {!MdPanelAnimation}
  850. */
  851. /**
  852. * @ngdoc method
  853. * @name MdPanelAnimation#duration
  854. * @description
  855. * Specifies the duration of the animation in milliseconds. The `duration`
  856. * method accepts either a number or an object with separate open and close
  857. * durations.
  858. *
  859. * @param {number|{open: number, close: number}} duration
  860. * @returns {!MdPanelAnimation}
  861. */
  862. /*****************************************************************************
  863. * PUBLIC DOCUMENTATION *
  864. *****************************************************************************/
  865. var MD_PANEL_Z_INDEX = 80;
  866. var MD_PANEL_HIDDEN = '_md-panel-hidden';
  867. var FOCUS_TRAP_TEMPLATE = angular.element(
  868. '<div class="_md-panel-focus-trap" tabindex="0"></div>');
  869. var _presets = {};
  870. /**
  871. * A provider that is used for creating presets for the panel API.
  872. * @final @constructor ngInject
  873. */
  874. function MdPanelProvider() {
  875. return {
  876. 'definePreset': definePreset,
  877. 'getAllPresets': getAllPresets,
  878. 'clearPresets': clearPresets,
  879. '$get': $getProvider()
  880. };
  881. }
  882. /**
  883. * Takes the passed in panel configuration object and adds it to the `_presets`
  884. * object at the specified name.
  885. * @param {string} name Name of the preset to set.
  886. * @param {!Object} preset Specific configuration object that can contain any
  887. * and all of the parameters avaialble within the `$mdPanel.create` method.
  888. * However, parameters that pertain to id, position, animation, and user
  889. * interaction are not allowed and will be removed from the preset
  890. * configuration.
  891. */
  892. function definePreset(name, preset) {
  893. if (!name || !preset) {
  894. throw new Error('mdPanelProvider: The panel preset definition is ' +
  895. 'malformed. The name and preset object are required.');
  896. } else if (_presets.hasOwnProperty(name)) {
  897. throw new Error('mdPanelProvider: The panel preset you have requested ' +
  898. 'has already been defined.');
  899. }
  900. // Delete any property on the preset that is not allowed.
  901. delete preset.id;
  902. delete preset.position;
  903. delete preset.animation;
  904. _presets[name] = preset;
  905. }
  906. /**
  907. * Gets a clone of the `_presets`.
  908. * @return {!Object}
  909. */
  910. function getAllPresets() {
  911. return angular.copy(_presets);
  912. }
  913. /**
  914. * Clears all of the stored presets.
  915. */
  916. function clearPresets() {
  917. _presets = {};
  918. }
  919. /**
  920. * Represents the `$get` method of the Angular provider. From here, a new
  921. * reference to the MdPanelService is returned where the needed arguments are
  922. * passed in including the MdPanelProvider `_presets`.
  923. * @param {!Object} _presets
  924. * @param {!angular.JQLite} $rootElement
  925. * @param {!angular.Scope} $rootScope
  926. * @param {!angular.$injector} $injector
  927. * @param {!angular.$window} $window
  928. */
  929. function $getProvider() {
  930. return [
  931. '$rootElement', '$rootScope', '$injector', '$window',
  932. function($rootElement, $rootScope, $injector, $window) {
  933. return new MdPanelService(_presets, $rootElement, $rootScope,
  934. $injector, $window);
  935. }
  936. ];
  937. }
  938. /*****************************************************************************
  939. * MdPanel Service *
  940. *****************************************************************************/
  941. /**
  942. * A service that is used for controlling/displaying panels on the screen.
  943. * @param {!Object} presets
  944. * @param {!angular.JQLite} $rootElement
  945. * @param {!angular.Scope} $rootScope
  946. * @param {!angular.$injector} $injector
  947. * @param {!angular.$window} $window
  948. * @final @constructor ngInject
  949. */
  950. function MdPanelService(presets, $rootElement, $rootScope, $injector, $window) {
  951. /**
  952. * Default config options for the panel.
  953. * Anything angular related needs to be done later. Therefore
  954. * scope: $rootScope.$new(true),
  955. * attachTo: $rootElement,
  956. * are added later.
  957. * @private {!Object}
  958. */
  959. this._defaultConfigOptions = {
  960. bindToController: true,
  961. clickOutsideToClose: false,
  962. disableParentScroll: false,
  963. escapeToClose: false,
  964. focusOnOpen: true,
  965. fullscreen: false,
  966. hasBackdrop: false,
  967. propagateContainerEvents: false,
  968. transformTemplate: angular.bind(this, this._wrapTemplate),
  969. trapFocus: false,
  970. zIndex: MD_PANEL_Z_INDEX
  971. };
  972. /** @private {!Object} */
  973. this._config = {};
  974. /** @private {!Object} */
  975. this._presets = presets;
  976. /** @private @const */
  977. this._$rootElement = $rootElement;
  978. /** @private @const */
  979. this._$rootScope = $rootScope;
  980. /** @private @const */
  981. this._$injector = $injector;
  982. /** @private @const */
  983. this._$window = $window;
  984. /** @private @const */
  985. this._$mdUtil = this._$injector.get('$mdUtil');
  986. /** @private {!Object<string, !MdPanelRef>} */
  987. this._trackedPanels = {};
  988. /**
  989. * @private {!Object<string,
  990. * {panels: !Array<!MdPanelRef>,
  991. * openPanels: !Array<!MdPanelRef>,
  992. * maxOpen: number}>}
  993. */
  994. this._groups = Object.create(null);
  995. /**
  996. * Default animations that can be used within the panel.
  997. * @type {enum}
  998. */
  999. this.animation = MdPanelAnimation.animation;
  1000. /**
  1001. * Possible values of xPosition for positioning the panel relative to
  1002. * another element.
  1003. * @type {enum}
  1004. */
  1005. this.xPosition = MdPanelPosition.xPosition;
  1006. /**
  1007. * Possible values of yPosition for positioning the panel relative to
  1008. * another element.
  1009. * @type {enum}
  1010. */
  1011. this.yPosition = MdPanelPosition.yPosition;
  1012. /**
  1013. * Possible values for the interceptors that can be registered on a panel.
  1014. * @type {enum}
  1015. */
  1016. this.interceptorTypes = MdPanelRef.interceptorTypes;
  1017. /**
  1018. * Possible values for closing of a panel.
  1019. * @type {enum}
  1020. */
  1021. this.closeReasons = MdPanelRef.closeReasons;
  1022. /**
  1023. * Possible values of absolute position.
  1024. * @type {enum}
  1025. */
  1026. this.absPosition = MdPanelPosition.absPosition;
  1027. }
  1028. /**
  1029. * Creates a panel with the specified options.
  1030. * @param {string=} preset Name of a preset configuration that can be used to
  1031. * extend the panel configuration.
  1032. * @param {!Object=} config Configuration object for the panel.
  1033. * @returns {!MdPanelRef}
  1034. */
  1035. MdPanelService.prototype.create = function(preset, config) {
  1036. if (typeof preset === 'string') {
  1037. preset = this._getPresetByName(preset);
  1038. } else if (typeof preset === 'object' &&
  1039. (angular.isUndefined(config) || !config)) {
  1040. config = preset;
  1041. preset = {};
  1042. }
  1043. preset = preset || {};
  1044. config = config || {};
  1045. // If the passed-in config contains an ID and the ID is within _trackedPanels,
  1046. // return the tracked panel after updating its config with the passed-in
  1047. // config.
  1048. if (angular.isDefined(config.id) && this._trackedPanels[config.id]) {
  1049. var trackedPanel = this._trackedPanels[config.id];
  1050. angular.extend(trackedPanel.config, config);
  1051. return trackedPanel;
  1052. }
  1053. // Combine the passed-in config, the _defaultConfigOptions, and the preset
  1054. // configuration into the `_config`.
  1055. this._config = angular.extend({
  1056. // If no ID is set within the passed-in config, then create an arbitrary ID.
  1057. id: config.id || 'panel_' + this._$mdUtil.nextUid(),
  1058. scope: this._$rootScope.$new(true),
  1059. attachTo: this._$rootElement
  1060. }, this._defaultConfigOptions, config, preset);
  1061. // Create the panelRef and add it to the `_trackedPanels` object.
  1062. var panelRef = new MdPanelRef(this._config, this._$injector);
  1063. this._trackedPanels[config.id] = panelRef;
  1064. // Add the panel to each of its requested groups.
  1065. if (this._config.groupName) {
  1066. if (angular.isString(this._config.groupName)) {
  1067. this._config.groupName = [this._config.groupName];
  1068. }
  1069. angular.forEach(this._config.groupName, function(group) {
  1070. panelRef.addToGroup(group);
  1071. });
  1072. }
  1073. this._config.scope.$on('$destroy', angular.bind(panelRef, panelRef.detach));
  1074. return panelRef;
  1075. };
  1076. /**
  1077. * Creates and opens a panel with the specified options.
  1078. * @param {string=} preset Name of a preset configuration that can be used to
  1079. * extend the panel configuration.
  1080. * @param {!Object=} config Configuration object for the panel.
  1081. * @returns {!angular.$q.Promise<!MdPanelRef>} The panel created from create.
  1082. */
  1083. MdPanelService.prototype.open = function(preset, config) {
  1084. var panelRef = this.create(preset, config);
  1085. return panelRef.open().then(function() {
  1086. return panelRef;
  1087. });
  1088. };
  1089. /**
  1090. * Gets a specific preset configuration object saved within `_presets`.
  1091. * @param {string} preset Name of the preset to search for.
  1092. * @returns {!Object} The preset configuration object.
  1093. */
  1094. MdPanelService.prototype._getPresetByName = function(preset) {
  1095. if (!this._presets[preset]) {
  1096. throw new Error('mdPanel: The panel preset configuration that you ' +
  1097. 'requested does not exist. Use the $mdPanelProvider to create a ' +
  1098. 'preset before requesting one.');
  1099. }
  1100. return this._presets[preset];
  1101. };
  1102. /**
  1103. * Returns a new instance of the MdPanelPosition. Use this to create the
  1104. * positioning object.
  1105. * @returns {!MdPanelPosition}
  1106. */
  1107. MdPanelService.prototype.newPanelPosition = function() {
  1108. return new MdPanelPosition(this._$injector);
  1109. };
  1110. /**
  1111. * Returns a new instance of the MdPanelAnimation. Use this to create the
  1112. * animation object.
  1113. * @returns {!MdPanelAnimation}
  1114. */
  1115. MdPanelService.prototype.newPanelAnimation = function() {
  1116. return new MdPanelAnimation(this._$injector);
  1117. };
  1118. /**
  1119. * Creates a panel group and adds it to a tracked list of panel groups.
  1120. * @param groupName {string} Name of the group to create.
  1121. * @param config {!Object=} Specific configuration object that may contain the
  1122. * following properties:
  1123. *
  1124. * - `maxOpen` - `{number=}`: The maximum number of panels that are allowed
  1125. * open within a defined panel group.
  1126. *
  1127. * @returns {!Object<string,
  1128. * {panels: !Array<!MdPanelRef>,
  1129. * openPanels: !Array<!MdPanelRef>,
  1130. * maxOpen: number}>} panelGroup
  1131. */
  1132. MdPanelService.prototype.newPanelGroup = function(groupName, config) {
  1133. if (!this._groups[groupName]) {
  1134. config = config || {};
  1135. var group = {
  1136. panels: [],
  1137. openPanels: [],
  1138. maxOpen: config.maxOpen > 0 ? config.maxOpen : Infinity
  1139. };
  1140. this._groups[groupName] = group;
  1141. }
  1142. return this._groups[groupName];
  1143. };
  1144. /**
  1145. * Sets the maximum number of panels in a group that can be opened at a given
  1146. * time.
  1147. * @param {string} groupName The name of the group to configure.
  1148. * @param {number} maxOpen The maximum number of panels that can be
  1149. * opened. Infinity can be passed in to remove the maxOpen limit.
  1150. */
  1151. MdPanelService.prototype.setGroupMaxOpen = function(groupName, maxOpen) {
  1152. if (this._groups[groupName]) {
  1153. this._groups[groupName].maxOpen = maxOpen;
  1154. } else {
  1155. throw new Error('mdPanel: Group does not exist yet. Call newPanelGroup().');
  1156. }
  1157. };
  1158. /**
  1159. * Determines if the current number of open panels within a group exceeds the
  1160. * limit of allowed open panels.
  1161. * @param {string} groupName The name of the group to check.
  1162. * @returns {boolean} true if open count does exceed maxOpen and false if not.
  1163. * @private
  1164. */
  1165. MdPanelService.prototype._openCountExceedsMaxOpen = function(groupName) {
  1166. if (this._groups[groupName]) {
  1167. var group = this._groups[groupName];
  1168. return group.maxOpen > 0 && group.openPanels.length > group.maxOpen;
  1169. }
  1170. return false;
  1171. };
  1172. /**
  1173. * Closes the first open panel within a specific group.
  1174. * @param {string} groupName The name of the group.
  1175. * @private
  1176. */
  1177. MdPanelService.prototype._closeFirstOpenedPanel = function(groupName) {
  1178. this._groups[groupName].openPanels[0].close();
  1179. };
  1180. /**
  1181. * Wraps the users template in two elements, md-panel-outer-wrapper, which
  1182. * covers the entire attachTo element, and md-panel, which contains only the
  1183. * template. This allows the panel control over positioning, animations,
  1184. * and similar properties.
  1185. * @param {string} origTemplate The original template.
  1186. * @returns {string} The wrapped template.
  1187. * @private
  1188. */
  1189. MdPanelService.prototype._wrapTemplate = function(origTemplate) {
  1190. var template = origTemplate || '';
  1191. // The panel should be initially rendered offscreen so we can calculate
  1192. // height and width for positioning.
  1193. return '' +
  1194. '<div class="md-panel-outer-wrapper">' +
  1195. ' <div class="md-panel" style="left: -9999px;">' + template + '</div>' +
  1196. '</div>';
  1197. };
  1198. /**
  1199. * Wraps a content element in a md-panel-outer wrapper and
  1200. * positions it off-screen. Allows for proper control over positoning
  1201. * and animations.
  1202. * @param {!angular.JQLite} contentElement Element to be wrapped.
  1203. * @return {!angular.JQLite} Wrapper element.
  1204. * @private
  1205. */
  1206. MdPanelService.prototype._wrapContentElement = function(contentElement) {
  1207. var wrapper = angular.element('<div class="md-panel-outer-wrapper">');
  1208. contentElement.addClass('md-panel').css('left', '-9999px');
  1209. wrapper.append(contentElement);
  1210. return wrapper;
  1211. };
  1212. /*****************************************************************************
  1213. * MdPanelRef *
  1214. *****************************************************************************/
  1215. /**
  1216. * A reference to a created panel. This reference contains a unique id for the
  1217. * panel, along with properties/functions used to control the panel.
  1218. * @param {!Object} config
  1219. * @param {!angular.$injector} $injector
  1220. * @final @constructor
  1221. */
  1222. function MdPanelRef(config, $injector) {
  1223. // Injected variables.
  1224. /** @private @const {!angular.$q} */
  1225. this._$q = $injector.get('$q');
  1226. /** @private @const {!angular.$mdCompiler} */
  1227. this._$mdCompiler = $injector.get('$mdCompiler');
  1228. /** @private @const {!angular.$mdConstant} */
  1229. this._$mdConstant = $injector.get('$mdConstant');
  1230. /** @private @const {!angular.$mdUtil} */
  1231. this._$mdUtil = $injector.get('$mdUtil');
  1232. /** @private @const {!angular.$mdTheming} */
  1233. this._$mdTheming = $injector.get('$mdTheming');
  1234. /** @private @const {!angular.Scope} */
  1235. this._$rootScope = $injector.get('$rootScope');
  1236. /** @private @const {!angular.$animate} */
  1237. this._$animate = $injector.get('$animate');
  1238. /** @private @const {!MdPanelRef} */
  1239. this._$mdPanel = $injector.get('$mdPanel');
  1240. /** @private @const {!angular.$log} */
  1241. this._$log = $injector.get('$log');
  1242. /** @private @const {!angular.$window} */
  1243. this._$window = $injector.get('$window');
  1244. /** @private @const {!Function} */
  1245. this._$$rAF = $injector.get('$$rAF');
  1246. // Public variables.
  1247. /**
  1248. * Unique id for the panelRef.
  1249. * @type {string}
  1250. */
  1251. this.id = config.id;
  1252. /** @type {!Object} */
  1253. this.config = config;
  1254. /** @type {!angular.JQLite|undefined} */
  1255. this.panelContainer;
  1256. /** @type {!angular.JQLite|undefined} */
  1257. this.panelEl;
  1258. /**
  1259. * Whether the panel is attached. This is synchronous. When attach is called,
  1260. * isAttached is set to true. When detach is called, isAttached is set to
  1261. * false.
  1262. * @type {boolean}
  1263. */
  1264. this.isAttached = false;
  1265. // Private variables.
  1266. /** @private {Array<function()>} */
  1267. this._removeListeners = [];
  1268. /** @private {!angular.JQLite|undefined} */
  1269. this._topFocusTrap;
  1270. /** @private {!angular.JQLite|undefined} */
  1271. this._bottomFocusTrap;
  1272. /** @private {!$mdPanel|undefined} */
  1273. this._backdropRef;
  1274. /** @private {Function?} */
  1275. this._restoreScroll = null;
  1276. /**
  1277. * Keeps track of all the panel interceptors.
  1278. * @private {!Object}
  1279. */
  1280. this._interceptors = Object.create(null);
  1281. /**
  1282. * Cleanup function, provided by `$mdCompiler` and assigned after the element
  1283. * has been compiled. When `contentElement` is used, the function is used to
  1284. * restore the element to it's proper place in the DOM.
  1285. * @private {!Function}
  1286. */
  1287. this._compilerCleanup = null;
  1288. /**
  1289. * Cache for saving and restoring element inline styles, CSS classes etc.
  1290. * @type {{styles: string, classes: string}}
  1291. */
  1292. this._restoreCache = {
  1293. styles: '',
  1294. classes: ''
  1295. };
  1296. }
  1297. MdPanelRef.interceptorTypes = {
  1298. CLOSE: 'onClose'
  1299. };
  1300. /**
  1301. * Opens an already created and configured panel. If the panel is already
  1302. * visible, does nothing.
  1303. * @returns {!angular.$q.Promise<!MdPanelRef>} A promise that is resolved when
  1304. * the panel is opened and animations finish.
  1305. */
  1306. MdPanelRef.prototype.open = function() {
  1307. var self = this;
  1308. return this._$q(function(resolve, reject) {
  1309. var done = self._done(resolve, self);
  1310. var show = self._simpleBind(self.show, self);
  1311. var checkGroupMaxOpen = function() {
  1312. if (self.config.groupName) {
  1313. angular.forEach(self.config.groupName, function(group) {
  1314. if (self._$mdPanel._openCountExceedsMaxOpen(group)) {
  1315. self._$mdPanel._closeFirstOpenedPanel(group);
  1316. }
  1317. });
  1318. }
  1319. };
  1320. self.attach()
  1321. .then(show)
  1322. .then(checkGroupMaxOpen)
  1323. .then(done)
  1324. .catch(reject);
  1325. });
  1326. };
  1327. /**
  1328. * Closes the panel.
  1329. * @param {string} closeReason The event type that triggered the close.
  1330. * @returns {!angular.$q.Promise<!MdPanelRef>} A promise that is resolved when
  1331. * the panel is closed and animations finish.
  1332. */
  1333. MdPanelRef.prototype.close = function(closeReason) {
  1334. var self = this;
  1335. return this._$q(function(resolve, reject) {
  1336. self._callInterceptors(MdPanelRef.interceptorTypes.CLOSE).then(function() {
  1337. var done = self._done(resolve, self);
  1338. var detach = self._simpleBind(self.detach, self);
  1339. var onCloseSuccess = self.config['onCloseSuccess'] || angular.noop;
  1340. onCloseSuccess = angular.bind(self, onCloseSuccess, self, closeReason);
  1341. self.hide()
  1342. .then(detach)
  1343. .then(done)
  1344. .then(onCloseSuccess)
  1345. .catch(reject);
  1346. }, reject);
  1347. });
  1348. };
  1349. /**
  1350. * Attaches the panel. The panel will be hidden afterwards.
  1351. * @returns {!angular.$q.Promise<!MdPanelRef>} A promise that is resolved when
  1352. * the panel is attached.
  1353. */
  1354. MdPanelRef.prototype.attach = function() {
  1355. if (this.isAttached && this.panelEl) {
  1356. return this._$q.when(this);
  1357. }
  1358. var self = this;
  1359. return this._$q(function(resolve, reject) {
  1360. var done = self._done(resolve, self);
  1361. var onDomAdded = self.config['onDomAdded'] || angular.noop;
  1362. var addListeners = function(response) {
  1363. self.isAttached = true;
  1364. self._addEventListeners();
  1365. return response;
  1366. };
  1367. self._$q.all([
  1368. self._createBackdrop(),
  1369. self._createPanel()
  1370. .then(addListeners)
  1371. .catch(reject)
  1372. ]).then(onDomAdded)
  1373. .then(done)
  1374. .catch(reject);
  1375. });
  1376. };
  1377. /**
  1378. * Only detaches the panel. Will NOT hide the panel first.
  1379. * @returns {!angular.$q.Promise<!MdPanelRef>} A promise that is resolved when
  1380. * the panel is detached.
  1381. */
  1382. MdPanelRef.prototype.detach = function() {
  1383. if (!this.isAttached) {
  1384. return this._$q.when(this);
  1385. }
  1386. var self = this;
  1387. var onDomRemoved = self.config['onDomRemoved'] || angular.noop;
  1388. var detachFn = function() {
  1389. self._removeEventListeners();
  1390. // Remove the focus traps that we added earlier for keeping focus within
  1391. // the panel.
  1392. if (self._topFocusTrap && self._topFocusTrap.parentNode) {
  1393. self._topFocusTrap.parentNode.removeChild(self._topFocusTrap);
  1394. }
  1395. if (self._bottomFocusTrap && self._bottomFocusTrap.parentNode) {
  1396. self._bottomFocusTrap.parentNode.removeChild(self._bottomFocusTrap);
  1397. }
  1398. if (self._restoreCache.classes) {
  1399. self.panelEl[0].className = self._restoreCache.classes;
  1400. }
  1401. // Either restore the saved styles or clear the ones set by mdPanel.
  1402. self.panelEl[0].style.cssText = self._restoreCache.styles || '';
  1403. self._compilerCleanup();
  1404. self.panelContainer.remove();
  1405. self.isAttached = false;
  1406. return self._$q.when(self);
  1407. };
  1408. if (this._restoreScroll) {
  1409. this._restoreScroll();
  1410. this._restoreScroll = null;
  1411. }
  1412. return this._$q(function(resolve, reject) {
  1413. var done = self._done(resolve, self);
  1414. self._$q.all([
  1415. detachFn(),
  1416. self._backdropRef ? self._backdropRef.detach() : true
  1417. ]).then(onDomRemoved)
  1418. .then(done)
  1419. .catch(reject);
  1420. });
  1421. };
  1422. /**
  1423. * Destroys the panel. The Panel cannot be opened again after this.
  1424. */
  1425. MdPanelRef.prototype.destroy = function() {
  1426. var self = this;
  1427. if (this.config.groupName) {
  1428. angular.forEach(this.config.groupName, function(group) {
  1429. self.removeFromGroup(group);
  1430. });
  1431. }
  1432. this.config.scope.$destroy();
  1433. this.config.locals = null;
  1434. this._interceptors = null;
  1435. };
  1436. /**
  1437. * Shows the panel.
  1438. * @returns {!angular.$q.Promise<!MdPanelRef>} A promise that is resolved when
  1439. * the panel has shown and animations finish.
  1440. */
  1441. MdPanelRef.prototype.show = function() {
  1442. if (!this.panelContainer) {
  1443. return this._$q(function(resolve, reject) {
  1444. reject('mdPanel: Panel does not exist yet. Call open() or attach().');
  1445. });
  1446. }
  1447. if (!this.panelContainer.hasClass(MD_PANEL_HIDDEN)) {
  1448. return this._$q.when(this);
  1449. }
  1450. var self = this;
  1451. var animatePromise = function() {
  1452. self.panelContainer.removeClass(MD_PANEL_HIDDEN);
  1453. return self._animateOpen();
  1454. };
  1455. return this._$q(function(resolve, reject) {
  1456. var done = self._done(resolve, self);
  1457. var onOpenComplete = self.config['onOpenComplete'] || angular.noop;
  1458. var addToGroupOpen = function() {
  1459. if (self.config.groupName) {
  1460. angular.forEach(self.config.groupName, function(group) {
  1461. self._$mdPanel._groups[group].openPanels.push(self);
  1462. });
  1463. }
  1464. };
  1465. self._$q.all([
  1466. self._backdropRef ? self._backdropRef.show() : self,
  1467. animatePromise().then(function() { self._focusOnOpen(); }, reject)
  1468. ]).then(onOpenComplete)
  1469. .then(addToGroupOpen)
  1470. .then(done)
  1471. .catch(reject);
  1472. });
  1473. };
  1474. /**
  1475. * Hides the panel.
  1476. * @returns {!angular.$q.Promise<!MdPanelRef>} A promise that is resolved when
  1477. * the panel has hidden and animations finish.
  1478. */
  1479. MdPanelRef.prototype.hide = function() {
  1480. if (!this.panelContainer) {
  1481. return this._$q(function(resolve, reject) {
  1482. reject('mdPanel: Panel does not exist yet. Call open() or attach().');
  1483. });
  1484. }
  1485. if (this.panelContainer.hasClass(MD_PANEL_HIDDEN)) {
  1486. return this._$q.when(this);
  1487. }
  1488. var self = this;
  1489. return this._$q(function(resolve, reject) {
  1490. var done = self._done(resolve, self);
  1491. var onRemoving = self.config['onRemoving'] || angular.noop;
  1492. var hidePanel = function() {
  1493. self.panelContainer.addClass(MD_PANEL_HIDDEN);
  1494. };
  1495. var removeFromGroupOpen = function() {
  1496. if (self.config.groupName) {
  1497. var group, index;
  1498. angular.forEach(self.config.groupName, function(group) {
  1499. group = self._$mdPanel._groups[group];
  1500. index = group.openPanels.indexOf(self);
  1501. if (index > -1) {
  1502. group.openPanels.splice(index, 1);
  1503. }
  1504. });
  1505. }
  1506. };
  1507. var focusOnOrigin = function() {
  1508. var origin = self.config['origin'];
  1509. if (origin) {
  1510. getElement(origin).focus();
  1511. }
  1512. };
  1513. self._$q.all([
  1514. self._backdropRef ? self._backdropRef.hide() : self,
  1515. self._animateClose()
  1516. .then(onRemoving)
  1517. .then(hidePanel)
  1518. .then(removeFromGroupOpen)
  1519. .then(focusOnOrigin)
  1520. .catch(reject)
  1521. ]).then(done, reject);
  1522. });
  1523. };
  1524. /**
  1525. * Add a class to the panel. DO NOT use this to hide/show the panel.
  1526. * @deprecated
  1527. * This method is in the process of being deprecated in favor of using the panel
  1528. * and container JQLite elements that are referenced in the MdPanelRef object.
  1529. * Full deprecation is scheduled for material 1.2.
  1530. *
  1531. * @param {string} newClass Class to be added.
  1532. * @param {boolean} toElement Whether or not to add the class to the panel
  1533. * element instead of the container.
  1534. */
  1535. MdPanelRef.prototype.addClass = function(newClass, toElement) {
  1536. this._$log.warn(
  1537. 'mdPanel: The addClass method is in the process of being deprecated. ' +
  1538. 'Full deprecation is scheduled for the Angular Material 1.2 release. ' +
  1539. 'To achieve the same results, use the panelContainer or panelEl ' +
  1540. 'JQLite elements that are referenced in MdPanelRef.');
  1541. if (!this.panelContainer) {
  1542. throw new Error(
  1543. 'mdPanel: Panel does not exist yet. Call open() or attach().');
  1544. }
  1545. if (!toElement && !this.panelContainer.hasClass(newClass)) {
  1546. this.panelContainer.addClass(newClass);
  1547. } else if (toElement && !this.panelEl.hasClass(newClass)) {
  1548. this.panelEl.addClass(newClass);
  1549. }
  1550. };
  1551. /**
  1552. * Remove a class from the panel. DO NOT use this to hide/show the panel.
  1553. * @deprecated
  1554. * This method is in the process of being deprecated in favor of using the panel
  1555. * and container JQLite elements that are referenced in the MdPanelRef object.
  1556. * Full deprecation is scheduled for material 1.2.
  1557. *
  1558. * @param {string} oldClass Class to be removed.
  1559. * @param {boolean} fromElement Whether or not to remove the class from the
  1560. * panel element instead of the container.
  1561. */
  1562. MdPanelRef.prototype.removeClass = function(oldClass, fromElement) {
  1563. this._$log.warn(
  1564. 'mdPanel: The removeClass method is in the process of being deprecated. ' +
  1565. 'Full deprecation is scheduled for the Angular Material 1.2 release. ' +
  1566. 'To achieve the same results, use the panelContainer or panelEl ' +
  1567. 'JQLite elements that are referenced in MdPanelRef.');
  1568. if (!this.panelContainer) {
  1569. throw new Error(
  1570. 'mdPanel: Panel does not exist yet. Call open() or attach().');
  1571. }
  1572. if (!fromElement && this.panelContainer.hasClass(oldClass)) {
  1573. this.panelContainer.removeClass(oldClass);
  1574. } else if (fromElement && this.panelEl.hasClass(oldClass)) {
  1575. this.panelEl.removeClass(oldClass);
  1576. }
  1577. };
  1578. /**
  1579. * Toggle a class on the panel. DO NOT use this to hide/show the panel.
  1580. * @deprecated
  1581. * This method is in the process of being deprecated in favor of using the panel
  1582. * and container JQLite elements that are referenced in the MdPanelRef object.
  1583. * Full deprecation is scheduled for material 1.2.
  1584. *
  1585. * @param {string} toggleClass The class to toggle.
  1586. * @param {boolean} onElement Whether or not to toggle the class on the panel
  1587. * element instead of the container.
  1588. */
  1589. MdPanelRef.prototype.toggleClass = function(toggleClass, onElement) {
  1590. this._$log.warn(
  1591. 'mdPanel: The toggleClass method is in the process of being deprecated. ' +
  1592. 'Full deprecation is scheduled for the Angular Material 1.2 release. ' +
  1593. 'To achieve the same results, use the panelContainer or panelEl ' +
  1594. 'JQLite elements that are referenced in MdPanelRef.');
  1595. if (!this.panelContainer) {
  1596. throw new Error(
  1597. 'mdPanel: Panel does not exist yet. Call open() or attach().');
  1598. }
  1599. if (!onElement) {
  1600. this.panelContainer.toggleClass(toggleClass);
  1601. } else {
  1602. this.panelEl.toggleClass(toggleClass);
  1603. }
  1604. };
  1605. /**
  1606. * Compiles the panel, according to the passed in config and appends it to
  1607. * the DOM. Helps normalize differences in the compilation process between
  1608. * using a string template and a content element.
  1609. * @returns {!angular.$q.Promise<!MdPanelRef>} Promise that is resolved when
  1610. * the element has been compiled and added to the DOM.
  1611. * @private
  1612. */
  1613. MdPanelRef.prototype._compile = function() {
  1614. var self = this;
  1615. // Compile the element via $mdCompiler. Note that when using a
  1616. // contentElement, the element isn't actually being compiled, rather the
  1617. // compiler saves it's place in the DOM and provides a way of restoring it.
  1618. return self._$mdCompiler.compile(self.config).then(function(compileData) {
  1619. var config = self.config;
  1620. if (config.contentElement) {
  1621. var panelEl = compileData.element;
  1622. // Since mdPanel modifies the inline styles and CSS classes, we need
  1623. // to save them in order to be able to restore on close.
  1624. self._restoreCache.styles = panelEl[0].style.cssText;
  1625. self._restoreCache.classes = panelEl[0].className;
  1626. self.panelContainer = self._$mdPanel._wrapContentElement(panelEl);
  1627. self.panelEl = panelEl;
  1628. } else {
  1629. self.panelContainer = compileData.link(config['scope']);
  1630. self.panelEl = angular.element(
  1631. self.panelContainer[0].querySelector('.md-panel')
  1632. );
  1633. }
  1634. // Save a reference to the cleanup function from the compiler.
  1635. self._compilerCleanup = compileData.cleanup;
  1636. // Attach the panel to the proper place in the DOM.
  1637. getElement(self.config['attachTo']).append(self.panelContainer);
  1638. return self;
  1639. });
  1640. };
  1641. /**
  1642. * Creates a panel and adds it to the dom.
  1643. * @returns {!angular.$q.Promise} A promise that is resolved when the panel is
  1644. * created.
  1645. * @private
  1646. */
  1647. MdPanelRef.prototype._createPanel = function() {
  1648. var self = this;
  1649. return this._$q(function(resolve, reject) {
  1650. if (!self.config.locals) {
  1651. self.config.locals = {};
  1652. }
  1653. self.config.locals.mdPanelRef = self;
  1654. self._compile().then(function() {
  1655. if (self.config['disableParentScroll']) {
  1656. self._restoreScroll = self._$mdUtil.disableScrollAround(
  1657. null,
  1658. self.panelContainer,
  1659. { disableScrollMask: true }
  1660. );
  1661. }
  1662. // Add a custom CSS class to the panel element.
  1663. if (self.config['panelClass']) {
  1664. self.panelEl.addClass(self.config['panelClass']);
  1665. }
  1666. // Handle click and touch events for the panel container.
  1667. if (self.config['propagateContainerEvents']) {
  1668. self.panelContainer.css('pointer-events', 'none');
  1669. }
  1670. // Panel may be outside the $rootElement, tell ngAnimate to animate
  1671. // regardless.
  1672. if (self._$animate.pin) {
  1673. self._$animate.pin(
  1674. self.panelContainer,
  1675. getElement(self.config['attachTo'])
  1676. );
  1677. }
  1678. self._configureTrapFocus();
  1679. self._addStyles().then(function() {
  1680. resolve(self);
  1681. }, reject);
  1682. }, reject);
  1683. });
  1684. };
  1685. /**
  1686. * Adds the styles for the panel, such as positioning and z-index. Also,
  1687. * themes the panel element and panel container using `$mdTheming`.
  1688. * @returns {!angular.$q.Promise<!MdPanelRef>}
  1689. * @private
  1690. */
  1691. MdPanelRef.prototype._addStyles = function() {
  1692. var self = this;
  1693. return this._$q(function(resolve) {
  1694. self.panelContainer.css('z-index', self.config['zIndex']);
  1695. self.panelEl.css('z-index', self.config['zIndex'] + 1);
  1696. var hideAndResolve = function() {
  1697. // Theme the element and container.
  1698. self._setTheming();
  1699. // Remove left: -9999px and add hidden class.
  1700. self.panelEl.css('left', '');
  1701. self.panelContainer.addClass(MD_PANEL_HIDDEN);
  1702. resolve(self);
  1703. };
  1704. if (self.config['fullscreen']) {
  1705. self.panelEl.addClass('_md-panel-fullscreen');
  1706. hideAndResolve();
  1707. return; // Don't setup positioning.
  1708. }
  1709. var positionConfig = self.config['position'];
  1710. if (!positionConfig) {
  1711. hideAndResolve();
  1712. return; // Don't setup positioning.
  1713. }
  1714. // Wait for angular to finish processing the template
  1715. self._$rootScope['$$postDigest'](function() {
  1716. // Position it correctly. This is necessary so that the panel will have a
  1717. // defined height and width.
  1718. self._updatePosition(true);
  1719. // Theme the element and container.
  1720. self._setTheming();
  1721. resolve(self);
  1722. });
  1723. });
  1724. };
  1725. /**
  1726. * Sets the `$mdTheming` classes on the `panelContainer` and `panelEl`.
  1727. * @private
  1728. */
  1729. MdPanelRef.prototype._setTheming = function() {
  1730. this._$mdTheming(this.panelEl);
  1731. this._$mdTheming(this.panelContainer);
  1732. };
  1733. /**
  1734. * Updates the position configuration of a panel
  1735. * @param {!MdPanelPosition} position
  1736. */
  1737. MdPanelRef.prototype.updatePosition = function(position) {
  1738. if (!this.panelContainer) {
  1739. throw new Error(
  1740. 'mdPanel: Panel does not exist yet. Call open() or attach().');
  1741. }
  1742. this.config['position'] = position;
  1743. this._updatePosition();
  1744. };
  1745. /**
  1746. * Calculates and updates the position of the panel.
  1747. * @param {boolean=} init
  1748. * @private
  1749. */
  1750. MdPanelRef.prototype._updatePosition = function(init) {
  1751. var positionConfig = this.config['position'];
  1752. if (positionConfig) {
  1753. positionConfig._setPanelPosition(this.panelEl);
  1754. // Hide the panel now that position is known.
  1755. if (init) {
  1756. this.panelContainer.addClass(MD_PANEL_HIDDEN);
  1757. }
  1758. this.panelEl.css(
  1759. MdPanelPosition.absPosition.TOP,
  1760. positionConfig.getTop()
  1761. );
  1762. this.panelEl.css(
  1763. MdPanelPosition.absPosition.BOTTOM,
  1764. positionConfig.getBottom()
  1765. );
  1766. this.panelEl.css(
  1767. MdPanelPosition.absPosition.LEFT,
  1768. positionConfig.getLeft()
  1769. );
  1770. this.panelEl.css(
  1771. MdPanelPosition.absPosition.RIGHT,
  1772. positionConfig.getRight()
  1773. );
  1774. }
  1775. };
  1776. /**
  1777. * Focuses on the panel or the first focus target.
  1778. * @private
  1779. */
  1780. MdPanelRef.prototype._focusOnOpen = function() {
  1781. if (this.config['focusOnOpen']) {
  1782. // Wait for the template to finish rendering to guarantee md-autofocus has
  1783. // finished adding the class md-autofocus, otherwise the focusable element
  1784. // isn't available to focus.
  1785. var self = this;
  1786. this._$rootScope['$$postDigest'](function() {
  1787. var target = self._$mdUtil.findFocusTarget(self.panelEl) ||
  1788. self.panelEl;
  1789. target.focus();
  1790. });
  1791. }
  1792. };
  1793. /**
  1794. * Shows the backdrop.
  1795. * @returns {!angular.$q.Promise} A promise that is resolved when the backdrop
  1796. * is created and attached.
  1797. * @private
  1798. */
  1799. MdPanelRef.prototype._createBackdrop = function() {
  1800. if (this.config.hasBackdrop) {
  1801. if (!this._backdropRef) {
  1802. var backdropAnimation = this._$mdPanel.newPanelAnimation()
  1803. .openFrom(this.config.attachTo)
  1804. .withAnimation({
  1805. open: '_md-opaque-enter',
  1806. close: '_md-opaque-leave'
  1807. });
  1808. if (this.config.animation) {
  1809. backdropAnimation.duration(this.config.animation._rawDuration);
  1810. }
  1811. var backdropConfig = {
  1812. animation: backdropAnimation,
  1813. attachTo: this.config.attachTo,
  1814. focusOnOpen: false,
  1815. panelClass: '_md-panel-backdrop',
  1816. zIndex: this.config.zIndex - 1
  1817. };
  1818. this._backdropRef = this._$mdPanel.create(backdropConfig);
  1819. }
  1820. if (!this._backdropRef.isAttached) {
  1821. return this._backdropRef.attach();
  1822. }
  1823. }
  1824. };
  1825. /**
  1826. * Listen for escape keys and outside clicks to auto close.
  1827. * @private
  1828. */
  1829. MdPanelRef.prototype._addEventListeners = function() {
  1830. this._configureEscapeToClose();
  1831. this._configureClickOutsideToClose();
  1832. this._configureScrollListener();
  1833. };
  1834. /**
  1835. * Remove event listeners added in _addEventListeners.
  1836. * @private
  1837. */
  1838. MdPanelRef.prototype._removeEventListeners = function() {
  1839. this._removeListeners && this._removeListeners.forEach(function(removeFn) {
  1840. removeFn();
  1841. });
  1842. this._removeListeners = [];
  1843. };
  1844. /**
  1845. * Setup the escapeToClose event listeners.
  1846. * @private
  1847. */
  1848. MdPanelRef.prototype._configureEscapeToClose = function() {
  1849. if (this.config['escapeToClose']) {
  1850. var parentTarget = getElement(this.config['attachTo']);
  1851. var self = this;
  1852. var keyHandlerFn = function(ev) {
  1853. if (ev.keyCode === self._$mdConstant.KEY_CODE.ESCAPE) {
  1854. ev.stopPropagation();
  1855. ev.preventDefault();
  1856. self.close(MdPanelRef.closeReasons.ESCAPE);
  1857. }
  1858. };
  1859. // Add keydown listeners
  1860. this.panelContainer.on('keydown', keyHandlerFn);
  1861. parentTarget.on('keydown', keyHandlerFn);
  1862. // Queue remove listeners function
  1863. this._removeListeners.push(function() {
  1864. self.panelContainer.off('keydown', keyHandlerFn);
  1865. parentTarget.off('keydown', keyHandlerFn);
  1866. });
  1867. }
  1868. };
  1869. /**
  1870. * Setup the clickOutsideToClose event listeners.
  1871. * @private
  1872. */
  1873. MdPanelRef.prototype._configureClickOutsideToClose = function() {
  1874. if (this.config['clickOutsideToClose']) {
  1875. var target = this.config['propagateContainerEvents'] ?
  1876. angular.element(document.body) :
  1877. this.panelContainer;
  1878. var sourceEl;
  1879. // Keep track of the element on which the mouse originally went down
  1880. // so that we can only close the backdrop when the 'click' started on it.
  1881. // A simple 'click' handler does not work, it sets the target object as the
  1882. // element the mouse went down on.
  1883. var mousedownHandler = function(ev) {
  1884. sourceEl = ev.target;
  1885. };
  1886. // We check if our original element and the target is the backdrop
  1887. // because if the original was the backdrop and the target was inside the
  1888. // panel we don't want to panel to close.
  1889. var self = this;
  1890. var mouseupHandler = function(ev) {
  1891. if (self.config['propagateContainerEvents']) {
  1892. // We check if the sourceEl of the event is the panel element or one
  1893. // of it's children. If it is not, then close the panel.
  1894. if (sourceEl !== self.panelEl[0] && !self.panelEl[0].contains(sourceEl)) {
  1895. self.close();
  1896. }
  1897. } else if (sourceEl === target[0] && ev.target === target[0]) {
  1898. ev.stopPropagation();
  1899. ev.preventDefault();
  1900. self.close(MdPanelRef.closeReasons.CLICK_OUTSIDE);
  1901. }
  1902. };
  1903. // Add listeners
  1904. target.on('mousedown', mousedownHandler);
  1905. target.on('mouseup', mouseupHandler);
  1906. // Queue remove listeners function
  1907. this._removeListeners.push(function() {
  1908. target.off('mousedown', mousedownHandler);
  1909. target.off('mouseup', mouseupHandler);
  1910. });
  1911. }
  1912. };
  1913. /**
  1914. * Configures the listeners for updating the panel position on scroll.
  1915. * @private
  1916. */
  1917. MdPanelRef.prototype._configureScrollListener = function() {
  1918. // No need to bind the event if scrolling is disabled.
  1919. if (!this.config['disableParentScroll']) {
  1920. var updatePosition = angular.bind(this, this._updatePosition);
  1921. var debouncedUpdatePosition = this._$$rAF.throttle(updatePosition);
  1922. var self = this;
  1923. var onScroll = function() {
  1924. debouncedUpdatePosition();
  1925. };
  1926. // Add listeners.
  1927. this._$window.addEventListener('scroll', onScroll, true);
  1928. // Queue remove listeners function.
  1929. this._removeListeners.push(function() {
  1930. self._$window.removeEventListener('scroll', onScroll, true);
  1931. });
  1932. }
  1933. };
  1934. /**
  1935. * Setup the focus traps. These traps will wrap focus when tabbing past the
  1936. * panel. When shift-tabbing, the focus will stick in place.
  1937. * @private
  1938. */
  1939. MdPanelRef.prototype._configureTrapFocus = function() {
  1940. // Focus doesn't remain inside of the panel without this.
  1941. this.panelEl.attr('tabIndex', '-1');
  1942. if (this.config['trapFocus']) {
  1943. var element = this.panelEl;
  1944. // Set up elements before and after the panel to capture focus and
  1945. // redirect back into the panel.
  1946. this._topFocusTrap = FOCUS_TRAP_TEMPLATE.clone()[0];
  1947. this._bottomFocusTrap = FOCUS_TRAP_TEMPLATE.clone()[0];
  1948. // When focus is about to move out of the panel, we want to intercept it
  1949. // and redirect it back to the panel element.
  1950. var focusHandler = function() {
  1951. element.focus();
  1952. };
  1953. this._topFocusTrap.addEventListener('focus', focusHandler);
  1954. this._bottomFocusTrap.addEventListener('focus', focusHandler);
  1955. // Queue remove listeners function
  1956. this._removeListeners.push(this._simpleBind(function() {
  1957. this._topFocusTrap.removeEventListener('focus', focusHandler);
  1958. this._bottomFocusTrap.removeEventListener('focus', focusHandler);
  1959. }, this));
  1960. // The top focus trap inserted immediately before the md-panel element (as
  1961. // a sibling). The bottom focus trap inserted immediately after the
  1962. // md-panel element (as a sibling).
  1963. element[0].parentNode.insertBefore(this._topFocusTrap, element[0]);
  1964. element.after(this._bottomFocusTrap);
  1965. }
  1966. };
  1967. /**
  1968. * Updates the animation of a panel.
  1969. * @param {!MdPanelAnimation} animation
  1970. */
  1971. MdPanelRef.prototype.updateAnimation = function(animation) {
  1972. this.config['animation'] = animation;
  1973. if (this._backdropRef) {
  1974. this._backdropRef.config.animation.duration(animation._rawDuration);
  1975. }
  1976. };
  1977. /**
  1978. * Animate the panel opening.
  1979. * @returns {!angular.$q.Promise} A promise that is resolved when the panel has
  1980. * animated open.
  1981. * @private
  1982. */
  1983. MdPanelRef.prototype._animateOpen = function() {
  1984. this.panelContainer.addClass('md-panel-is-showing');
  1985. var animationConfig = this.config['animation'];
  1986. if (!animationConfig) {
  1987. // Promise is in progress, return it.
  1988. this.panelContainer.addClass('_md-panel-shown');
  1989. return this._$q.when(this);
  1990. }
  1991. var self = this;
  1992. return this._$q(function(resolve) {
  1993. var done = self._done(resolve, self);
  1994. var warnAndOpen = function() {
  1995. self._$log.warn(
  1996. 'mdPanel: MdPanel Animations failed. ' +
  1997. 'Showing panel without animating.');
  1998. done();
  1999. };
  2000. animationConfig.animateOpen(self.panelEl)
  2001. .then(done, warnAndOpen);
  2002. });
  2003. };
  2004. /**
  2005. * Animate the panel closing.
  2006. * @returns {!angular.$q.Promise} A promise that is resolved when the panel has
  2007. * animated closed.
  2008. * @private
  2009. */
  2010. MdPanelRef.prototype._animateClose = function() {
  2011. var animationConfig = this.config['animation'];
  2012. if (!animationConfig) {
  2013. this.panelContainer.removeClass('md-panel-is-showing');
  2014. this.panelContainer.removeClass('_md-panel-shown');
  2015. return this._$q.when(this);
  2016. }
  2017. var self = this;
  2018. return this._$q(function(resolve) {
  2019. var done = function() {
  2020. self.panelContainer.removeClass('md-panel-is-showing');
  2021. resolve(self);
  2022. };
  2023. var warnAndClose = function() {
  2024. self._$log.warn(
  2025. 'mdPanel: MdPanel Animations failed. ' +
  2026. 'Hiding panel without animating.');
  2027. done();
  2028. };
  2029. animationConfig.animateClose(self.panelEl)
  2030. .then(done, warnAndClose);
  2031. });
  2032. };
  2033. /**
  2034. * Registers a interceptor with the panel. The callback should return a promise,
  2035. * which will allow the action to continue when it gets resolved, or will
  2036. * prevent an action if it is rejected.
  2037. * @param {string} type Type of interceptor.
  2038. * @param {!angular.$q.Promise<!any>} callback Callback to be registered.
  2039. * @returns {!MdPanelRef}
  2040. */
  2041. MdPanelRef.prototype.registerInterceptor = function(type, callback) {
  2042. var error = null;
  2043. if (!angular.isString(type)) {
  2044. error = 'Interceptor type must be a string, instead got ' + typeof type;
  2045. } else if (!angular.isFunction(callback)) {
  2046. error = 'Interceptor callback must be a function, instead got ' + typeof callback;
  2047. }
  2048. if (error) {
  2049. throw new Error('MdPanel: ' + error);
  2050. }
  2051. var interceptors = this._interceptors[type] = this._interceptors[type] || [];
  2052. if (interceptors.indexOf(callback) === -1) {
  2053. interceptors.push(callback);
  2054. }
  2055. return this;
  2056. };
  2057. /**
  2058. * Removes a registered interceptor.
  2059. * @param {string} type Type of interceptor to be removed.
  2060. * @param {Function} callback Interceptor to be removed.
  2061. * @returns {!MdPanelRef}
  2062. */
  2063. MdPanelRef.prototype.removeInterceptor = function(type, callback) {
  2064. var index = this._interceptors[type] ?
  2065. this._interceptors[type].indexOf(callback) : -1;
  2066. if (index > -1) {
  2067. this._interceptors[type].splice(index, 1);
  2068. }
  2069. return this;
  2070. };
  2071. /**
  2072. * Removes all interceptors.
  2073. * @param {string=} type Type of interceptors to be removed.
  2074. * If ommited, all interceptors types will be removed.
  2075. * @returns {!MdPanelRef}
  2076. */
  2077. MdPanelRef.prototype.removeAllInterceptors = function(type) {
  2078. if (type) {
  2079. this._interceptors[type] = [];
  2080. } else {
  2081. this._interceptors = Object.create(null);
  2082. }
  2083. return this;
  2084. };
  2085. /**
  2086. * Invokes all the interceptors of a certain type sequantially in
  2087. * reverse order. Works in a similar way to `$q.all`, except it
  2088. * respects the order of the functions.
  2089. * @param {string} type Type of interceptors to be invoked.
  2090. * @returns {!angular.$q.Promise<!MdPanelRef>}
  2091. * @private
  2092. */
  2093. MdPanelRef.prototype._callInterceptors = function(type) {
  2094. var self = this;
  2095. var $q = self._$q;
  2096. var interceptors = self._interceptors && self._interceptors[type] || [];
  2097. return interceptors.reduceRight(function(promise, interceptor) {
  2098. var isPromiseLike = interceptor && angular.isFunction(interceptor.then);
  2099. var response = isPromiseLike ? interceptor : null;
  2100. /**
  2101. * For interceptors to reject/cancel subsequent portions of the chain, simply
  2102. * return a `$q.reject(<value>)`
  2103. */
  2104. return promise.then(function() {
  2105. if (!response) {
  2106. try {
  2107. response = interceptor(self);
  2108. } catch(e) {
  2109. response = $q.reject(e);
  2110. }
  2111. }
  2112. return response;
  2113. });
  2114. }, $q.resolve(self));
  2115. };
  2116. /**
  2117. * Faster, more basic than angular.bind
  2118. * http://jsperf.com/angular-bind-vs-custom-vs-native
  2119. * @param {function} callback
  2120. * @param {!Object} self
  2121. * @return {function} Callback function with a bound self.
  2122. */
  2123. MdPanelRef.prototype._simpleBind = function(callback, self) {
  2124. return function(value) {
  2125. return callback.apply(self, value);
  2126. };
  2127. };
  2128. /**
  2129. * @param {function} callback
  2130. * @param {!Object} self
  2131. * @return {function} Callback function with a self param.
  2132. */
  2133. MdPanelRef.prototype._done = function(callback, self) {
  2134. return function() {
  2135. callback(self);
  2136. };
  2137. };
  2138. /**
  2139. * Adds a panel to a group if the panel does not exist within the group already.
  2140. * A panel can only exist within a single group.
  2141. * @param {string} groupName The name of the group.
  2142. */
  2143. MdPanelRef.prototype.addToGroup = function(groupName) {
  2144. if (!this._$mdPanel._groups[groupName]) {
  2145. this._$mdPanel.newPanelGroup(groupName);
  2146. }
  2147. var group = this._$mdPanel._groups[groupName];
  2148. var index = group.panels.indexOf(this);
  2149. if (index < 0) {
  2150. group.panels.push(this);
  2151. }
  2152. };
  2153. /**
  2154. * Removes a panel from a group if the panel exists within that group. The group
  2155. * must be created ahead of time.
  2156. * @param {string} groupName The name of the group.
  2157. */
  2158. MdPanelRef.prototype.removeFromGroup = function(groupName) {
  2159. if (!this._$mdPanel._groups[groupName]) {
  2160. throw new Error('mdPanel: The group ' + groupName + ' does not exist.');
  2161. }
  2162. var group = this._$mdPanel._groups[groupName];
  2163. var index = group.panels.indexOf(this);
  2164. if (index > -1) {
  2165. group.panels.splice(index, 1);
  2166. }
  2167. };
  2168. /**
  2169. * Possible default closeReasons for the close function.
  2170. * @enum {string}
  2171. */
  2172. MdPanelRef.closeReasons = {
  2173. CLICK_OUTSIDE: 'clickOutsideToClose',
  2174. ESCAPE: 'escapeToClose',
  2175. };
  2176. /*****************************************************************************
  2177. * MdPanelPosition *
  2178. *****************************************************************************/
  2179. /**
  2180. * Position configuration object. To use, create an MdPanelPosition with the
  2181. * desired properties, then pass the object as part of $mdPanel creation.
  2182. *
  2183. * Example:
  2184. *
  2185. * var panelPosition = new MdPanelPosition()
  2186. * .relativeTo(myButtonEl)
  2187. * .addPanelPosition(
  2188. * $mdPanel.xPosition.CENTER,
  2189. * $mdPanel.yPosition.ALIGN_TOPS
  2190. * );
  2191. *
  2192. * $mdPanel.create({
  2193. * position: panelPosition
  2194. * });
  2195. *
  2196. * @param {!angular.$injector} $injector
  2197. * @final @constructor
  2198. */
  2199. function MdPanelPosition($injector) {
  2200. /** @private @const {!angular.$window} */
  2201. this._$window = $injector.get('$window');
  2202. /** @private {boolean} */
  2203. this._isRTL = $injector.get('$mdUtil').bidi() === 'rtl';
  2204. /** @private @const {!angular.$mdConstant} */
  2205. this._$mdConstant = $injector.get('$mdConstant');
  2206. /** @private {boolean} */
  2207. this._absolute = false;
  2208. /** @private {!angular.JQLite} */
  2209. this._relativeToEl;
  2210. /** @private {string} */
  2211. this._top = '';
  2212. /** @private {string} */
  2213. this._bottom = '';
  2214. /** @private {string} */
  2215. this._left = '';
  2216. /** @private {string} */
  2217. this._right = '';
  2218. /** @private {!Array<string>} */
  2219. this._translateX = [];
  2220. /** @private {!Array<string>} */
  2221. this._translateY = [];
  2222. /** @private {!Array<{x:string, y:string}>} */
  2223. this._positions = [];
  2224. /** @private {?{x:string, y:string}} */
  2225. this._actualPosition;
  2226. }
  2227. /**
  2228. * Possible values of xPosition.
  2229. * @enum {string}
  2230. */
  2231. MdPanelPosition.xPosition = {
  2232. CENTER: 'center',
  2233. ALIGN_START: 'align-start',
  2234. ALIGN_END: 'align-end',
  2235. OFFSET_START: 'offset-start',
  2236. OFFSET_END: 'offset-end'
  2237. };
  2238. /**
  2239. * Possible values of yPosition.
  2240. * @enum {string}
  2241. */
  2242. MdPanelPosition.yPosition = {
  2243. CENTER: 'center',
  2244. ALIGN_TOPS: 'align-tops',
  2245. ALIGN_BOTTOMS: 'align-bottoms',
  2246. ABOVE: 'above',
  2247. BELOW: 'below'
  2248. };
  2249. /**
  2250. * Possible values of absolute position.
  2251. * @enum {string}
  2252. */
  2253. MdPanelPosition.absPosition = {
  2254. TOP: 'top',
  2255. RIGHT: 'right',
  2256. BOTTOM: 'bottom',
  2257. LEFT: 'left'
  2258. };
  2259. /**
  2260. * Margin between the edges of a panel and the viewport.
  2261. * @const {number}
  2262. */
  2263. MdPanelPosition.viewportMargin = 8;
  2264. /**
  2265. * Sets absolute positioning for the panel.
  2266. * @return {!MdPanelPosition}
  2267. */
  2268. MdPanelPosition.prototype.absolute = function() {
  2269. this._absolute = true;
  2270. return this;
  2271. };
  2272. /**
  2273. * Sets the value of a position for the panel. Clears any previously set
  2274. * position.
  2275. * @param {string} position Position to set
  2276. * @param {string=} value Value of the position. Defaults to '0'.
  2277. * @returns {!MdPanelPosition}
  2278. * @private
  2279. */
  2280. MdPanelPosition.prototype._setPosition = function(position, value) {
  2281. if (position === MdPanelPosition.absPosition.RIGHT ||
  2282. position === MdPanelPosition.absPosition.LEFT) {
  2283. this._left = this._right = '';
  2284. } else if (
  2285. position === MdPanelPosition.absPosition.BOTTOM ||
  2286. position === MdPanelPosition.absPosition.TOP) {
  2287. this._top = this._bottom = '';
  2288. } else {
  2289. var positions = Object.keys(MdPanelPosition.absPosition).join()
  2290. .toLowerCase();
  2291. throw new Error('mdPanel: Position must be one of ' + positions + '.');
  2292. }
  2293. this['_' + position] = angular.isString(value) ? value : '0';
  2294. return this;
  2295. };
  2296. /**
  2297. * Sets the value of `top` for the panel. Clears any previously set vertical
  2298. * position.
  2299. * @param {string=} top Value of `top`. Defaults to '0'.
  2300. * @returns {!MdPanelPosition}
  2301. */
  2302. MdPanelPosition.prototype.top = function(top) {
  2303. return this._setPosition(MdPanelPosition.absPosition.TOP, top);
  2304. };
  2305. /**
  2306. * Sets the value of `bottom` for the panel. Clears any previously set vertical
  2307. * position.
  2308. * @param {string=} bottom Value of `bottom`. Defaults to '0'.
  2309. * @returns {!MdPanelPosition}
  2310. */
  2311. MdPanelPosition.prototype.bottom = function(bottom) {
  2312. return this._setPosition(MdPanelPosition.absPosition.BOTTOM, bottom);
  2313. };
  2314. /**
  2315. * Sets the panel to the start of the page - `left` if `ltr` or `right` for
  2316. * `rtl`. Clears any previously set horizontal position.
  2317. * @param {string=} start Value of position. Defaults to '0'.
  2318. * @returns {!MdPanelPosition}
  2319. */
  2320. MdPanelPosition.prototype.start = function(start) {
  2321. var position = this._isRTL ? MdPanelPosition.absPosition.RIGHT : MdPanelPosition.absPosition.LEFT;
  2322. return this._setPosition(position, start);
  2323. };
  2324. /**
  2325. * Sets the panel to the end of the page - `right` if `ltr` or `left` for `rtl`.
  2326. * Clears any previously set horizontal position.
  2327. * @param {string=} end Value of position. Defaults to '0'.
  2328. * @returns {!MdPanelPosition}
  2329. */
  2330. MdPanelPosition.prototype.end = function(end) {
  2331. var position = this._isRTL ? MdPanelPosition.absPosition.LEFT : MdPanelPosition.absPosition.RIGHT;
  2332. return this._setPosition(position, end);
  2333. };
  2334. /**
  2335. * Sets the value of `left` for the panel. Clears any previously set
  2336. * horizontal position.
  2337. * @param {string=} left Value of `left`. Defaults to '0'.
  2338. * @returns {!MdPanelPosition}
  2339. */
  2340. MdPanelPosition.prototype.left = function(left) {
  2341. return this._setPosition(MdPanelPosition.absPosition.LEFT, left);
  2342. };
  2343. /**
  2344. * Sets the value of `right` for the panel. Clears any previously set
  2345. * horizontal position.
  2346. * @param {string=} right Value of `right`. Defaults to '0'.
  2347. * @returns {!MdPanelPosition}
  2348. */
  2349. MdPanelPosition.prototype.right = function(right) {
  2350. return this._setPosition(MdPanelPosition.absPosition.RIGHT, right);
  2351. };
  2352. /**
  2353. * Centers the panel horizontally in the viewport. Clears any previously set
  2354. * horizontal position.
  2355. * @returns {!MdPanelPosition}
  2356. */
  2357. MdPanelPosition.prototype.centerHorizontally = function() {
  2358. this._left = '50%';
  2359. this._right = '';
  2360. this._translateX = ['-50%'];
  2361. return this;
  2362. };
  2363. /**
  2364. * Centers the panel vertically in the viewport. Clears any previously set
  2365. * vertical position.
  2366. * @returns {!MdPanelPosition}
  2367. */
  2368. MdPanelPosition.prototype.centerVertically = function() {
  2369. this._top = '50%';
  2370. this._bottom = '';
  2371. this._translateY = ['-50%'];
  2372. return this;
  2373. };
  2374. /**
  2375. * Centers the panel horizontally and vertically in the viewport. This is
  2376. * equivalent to calling both `centerHorizontally` and `centerVertically`.
  2377. * Clears any previously set horizontal and vertical positions.
  2378. * @returns {!MdPanelPosition}
  2379. */
  2380. MdPanelPosition.prototype.center = function() {
  2381. return this.centerHorizontally().centerVertically();
  2382. };
  2383. /**
  2384. * Sets element for relative positioning.
  2385. * @param {string|!Element|!angular.JQLite} element Query selector, DOM element,
  2386. * or angular element to set the panel relative to.
  2387. * @returns {!MdPanelPosition}
  2388. */
  2389. MdPanelPosition.prototype.relativeTo = function(element) {
  2390. this._absolute = false;
  2391. this._relativeToEl = getElement(element);
  2392. return this;
  2393. };
  2394. /**
  2395. * Sets the x and y positions for the panel relative to another element.
  2396. * @param {string} xPosition must be one of the MdPanelPosition.xPosition
  2397. * values.
  2398. * @param {string} yPosition must be one of the MdPanelPosition.yPosition
  2399. * values.
  2400. * @returns {!MdPanelPosition}
  2401. */
  2402. MdPanelPosition.prototype.addPanelPosition = function(xPosition, yPosition) {
  2403. if (!this._relativeToEl) {
  2404. throw new Error('mdPanel: addPanelPosition can only be used with ' +
  2405. 'relative positioning. Set relativeTo first.');
  2406. }
  2407. this._validateXPosition(xPosition);
  2408. this._validateYPosition(yPosition);
  2409. this._positions.push({
  2410. x: xPosition,
  2411. y: yPosition,
  2412. });
  2413. return this;
  2414. };
  2415. /**
  2416. * Ensures that yPosition is a valid position name. Throw an exception if not.
  2417. * @param {string} yPosition
  2418. */
  2419. MdPanelPosition.prototype._validateYPosition = function(yPosition) {
  2420. // empty is ok
  2421. if (yPosition == null) {
  2422. return;
  2423. }
  2424. var positionKeys = Object.keys(MdPanelPosition.yPosition);
  2425. var positionValues = [];
  2426. for (var key, i = 0; key = positionKeys[i]; i++) {
  2427. var position = MdPanelPosition.yPosition[key];
  2428. positionValues.push(position);
  2429. if (position === yPosition) {
  2430. return;
  2431. }
  2432. }
  2433. throw new Error('mdPanel: Panel y position only accepts the following ' +
  2434. 'values:\n' + positionValues.join(' | '));
  2435. };
  2436. /**
  2437. * Ensures that xPosition is a valid position name. Throw an exception if not.
  2438. * @param {string} xPosition
  2439. */
  2440. MdPanelPosition.prototype._validateXPosition = function(xPosition) {
  2441. // empty is ok
  2442. if (xPosition == null) {
  2443. return;
  2444. }
  2445. var positionKeys = Object.keys(MdPanelPosition.xPosition);
  2446. var positionValues = [];
  2447. for (var key, i = 0; key = positionKeys[i]; i++) {
  2448. var position = MdPanelPosition.xPosition[key];
  2449. positionValues.push(position);
  2450. if (position === xPosition) {
  2451. return;
  2452. }
  2453. }
  2454. throw new Error('mdPanel: Panel x Position only accepts the following ' +
  2455. 'values:\n' + positionValues.join(' | '));
  2456. };
  2457. /**
  2458. * Sets the value of the offset in the x-direction. This will add to any
  2459. * previously set offsets.
  2460. * @param {string|function(MdPanelPosition): string} offsetX
  2461. * @returns {!MdPanelPosition}
  2462. */
  2463. MdPanelPosition.prototype.withOffsetX = function(offsetX) {
  2464. this._translateX.push(offsetX);
  2465. return this;
  2466. };
  2467. /**
  2468. * Sets the value of the offset in the y-direction. This will add to any
  2469. * previously set offsets.
  2470. * @param {string|function(MdPanelPosition): string} offsetY
  2471. * @returns {!MdPanelPosition}
  2472. */
  2473. MdPanelPosition.prototype.withOffsetY = function(offsetY) {
  2474. this._translateY.push(offsetY);
  2475. return this;
  2476. };
  2477. /**
  2478. * Gets the value of `top` for the panel.
  2479. * @returns {string}
  2480. */
  2481. MdPanelPosition.prototype.getTop = function() {
  2482. return this._top;
  2483. };
  2484. /**
  2485. * Gets the value of `bottom` for the panel.
  2486. * @returns {string}
  2487. */
  2488. MdPanelPosition.prototype.getBottom = function() {
  2489. return this._bottom;
  2490. };
  2491. /**
  2492. * Gets the value of `left` for the panel.
  2493. * @returns {string}
  2494. */
  2495. MdPanelPosition.prototype.getLeft = function() {
  2496. return this._left;
  2497. };
  2498. /**
  2499. * Gets the value of `right` for the panel.
  2500. * @returns {string}
  2501. */
  2502. MdPanelPosition.prototype.getRight = function() {
  2503. return this._right;
  2504. };
  2505. /**
  2506. * Gets the value of `transform` for the panel.
  2507. * @returns {string}
  2508. */
  2509. MdPanelPosition.prototype.getTransform = function() {
  2510. var translateX = this._reduceTranslateValues('translateX', this._translateX);
  2511. var translateY = this._reduceTranslateValues('translateY', this._translateY);
  2512. // It's important to trim the result, because the browser will ignore the set
  2513. // operation if the string contains only whitespace.
  2514. return (translateX + ' ' + translateY).trim();
  2515. };
  2516. /**
  2517. * Sets the `transform` value for a panel element.
  2518. * @param {!angular.JQLite} panelEl
  2519. * @returns {!angular.JQLite}
  2520. * @private
  2521. */
  2522. MdPanelPosition.prototype._setTransform = function(panelEl) {
  2523. return panelEl.css(this._$mdConstant.CSS.TRANSFORM, this.getTransform());
  2524. };
  2525. /**
  2526. * True if the panel is completely on-screen with this positioning; false
  2527. * otherwise.
  2528. * @param {!angular.JQLite} panelEl
  2529. * @return {boolean}
  2530. * @private
  2531. */
  2532. MdPanelPosition.prototype._isOnscreen = function(panelEl) {
  2533. // this works because we always use fixed positioning for the panel,
  2534. // which is relative to the viewport.
  2535. var left = parseInt(this.getLeft());
  2536. var top = parseInt(this.getTop());
  2537. if (this._translateX.length || this._translateY.length) {
  2538. var prefixedTransform = this._$mdConstant.CSS.TRANSFORM;
  2539. var offsets = getComputedTranslations(panelEl, prefixedTransform);
  2540. left += offsets.x;
  2541. top += offsets.y;
  2542. }
  2543. var right = left + panelEl[0].offsetWidth;
  2544. var bottom = top + panelEl[0].offsetHeight;
  2545. return (left >= 0) &&
  2546. (top >= 0) &&
  2547. (bottom <= this._$window.innerHeight) &&
  2548. (right <= this._$window.innerWidth);
  2549. };
  2550. /**
  2551. * Gets the first x/y position that can fit on-screen.
  2552. * @returns {{x: string, y: string}}
  2553. */
  2554. MdPanelPosition.prototype.getActualPosition = function() {
  2555. return this._actualPosition;
  2556. };
  2557. /**
  2558. * Reduces a list of translate values to a string that can be used within
  2559. * transform.
  2560. * @param {string} translateFn
  2561. * @param {!Array<string>} values
  2562. * @returns {string}
  2563. * @private
  2564. */
  2565. MdPanelPosition.prototype._reduceTranslateValues =
  2566. function(translateFn, values) {
  2567. return values.map(function(translation) {
  2568. // TODO(crisbeto): this should add the units after #9609 is merged.
  2569. var translationValue = angular.isFunction(translation) ?
  2570. translation(this) : translation;
  2571. return translateFn + '(' + translationValue + ')';
  2572. }, this).join(' ');
  2573. };
  2574. /**
  2575. * Sets the panel position based on the created panel element and best x/y
  2576. * positioning.
  2577. * @param {!angular.JQLite} panelEl
  2578. * @private
  2579. */
  2580. MdPanelPosition.prototype._setPanelPosition = function(panelEl) {
  2581. // Remove the "position adjusted" class in case it has been added before.
  2582. panelEl.removeClass('_md-panel-position-adjusted');
  2583. // Only calculate the position if necessary.
  2584. if (this._absolute) {
  2585. this._setTransform(panelEl);
  2586. return;
  2587. }
  2588. if (this._actualPosition) {
  2589. this._calculatePanelPosition(panelEl, this._actualPosition);
  2590. this._setTransform(panelEl);
  2591. this._constrainToViewport(panelEl);
  2592. return;
  2593. }
  2594. for (var i = 0; i < this._positions.length; i++) {
  2595. this._actualPosition = this._positions[i];
  2596. this._calculatePanelPosition(panelEl, this._actualPosition);
  2597. this._setTransform(panelEl);
  2598. if (this._isOnscreen(panelEl)) {
  2599. return;
  2600. }
  2601. }
  2602. this._constrainToViewport(panelEl);
  2603. };
  2604. /**
  2605. * Constrains a panel's position to the viewport.
  2606. * @param {!angular.JQLite} panelEl
  2607. * @private
  2608. */
  2609. MdPanelPosition.prototype._constrainToViewport = function(panelEl) {
  2610. var margin = MdPanelPosition.viewportMargin;
  2611. var initialTop = this._top;
  2612. var initialLeft = this._left;
  2613. if (this.getTop()) {
  2614. var top = parseInt(this.getTop());
  2615. var bottom = panelEl[0].offsetHeight + top;
  2616. var viewportHeight = this._$window.innerHeight;
  2617. if (top < margin) {
  2618. this._top = margin + 'px';
  2619. } else if (bottom > viewportHeight) {
  2620. this._top = top - (bottom - viewportHeight + margin) + 'px';
  2621. }
  2622. }
  2623. if (this.getLeft()) {
  2624. var left = parseInt(this.getLeft());
  2625. var right = panelEl[0].offsetWidth + left;
  2626. var viewportWidth = this._$window.innerWidth;
  2627. if (left < margin) {
  2628. this._left = margin + 'px';
  2629. } else if (right > viewportWidth) {
  2630. this._left = left - (right - viewportWidth + margin) + 'px';
  2631. }
  2632. }
  2633. // Class that can be used to re-style the panel if it was repositioned.
  2634. panelEl.toggleClass(
  2635. '_md-panel-position-adjusted',
  2636. this._top !== initialTop || this._left !== initialLeft
  2637. );
  2638. };
  2639. /**
  2640. * Switches between 'start' and 'end'.
  2641. * @param {string} position Horizontal position of the panel
  2642. * @returns {string} Reversed position
  2643. * @private
  2644. */
  2645. MdPanelPosition.prototype._reverseXPosition = function(position) {
  2646. if (position === MdPanelPosition.xPosition.CENTER) {
  2647. return;
  2648. }
  2649. var start = 'start';
  2650. var end = 'end';
  2651. return position.indexOf(start) > -1 ? position.replace(start, end) : position.replace(end, start);
  2652. };
  2653. /**
  2654. * Handles horizontal positioning in rtl or ltr environments.
  2655. * @param {string} position Horizontal position of the panel
  2656. * @returns {string} The correct position according the page direction
  2657. * @private
  2658. */
  2659. MdPanelPosition.prototype._bidi = function(position) {
  2660. return this._isRTL ? this._reverseXPosition(position) : position;
  2661. };
  2662. /**
  2663. * Calculates the panel position based on the created panel element and the
  2664. * provided positioning.
  2665. * @param {!angular.JQLite} panelEl
  2666. * @param {!{x:string, y:string}} position
  2667. * @private
  2668. */
  2669. MdPanelPosition.prototype._calculatePanelPosition = function(panelEl, position) {
  2670. var panelBounds = panelEl[0].getBoundingClientRect();
  2671. var panelWidth = panelBounds.width;
  2672. var panelHeight = panelBounds.height;
  2673. var targetBounds = this._relativeToEl[0].getBoundingClientRect();
  2674. var targetLeft = targetBounds.left;
  2675. var targetRight = targetBounds.right;
  2676. var targetWidth = targetBounds.width;
  2677. switch (this._bidi(position.x)) {
  2678. case MdPanelPosition.xPosition.OFFSET_START:
  2679. this._left = targetLeft - panelWidth + 'px';
  2680. break;
  2681. case MdPanelPosition.xPosition.ALIGN_END:
  2682. this._left = targetRight - panelWidth + 'px';
  2683. break;
  2684. case MdPanelPosition.xPosition.CENTER:
  2685. var left = targetLeft + (0.5 * targetWidth) - (0.5 * panelWidth);
  2686. this._left = left + 'px';
  2687. break;
  2688. case MdPanelPosition.xPosition.ALIGN_START:
  2689. this._left = targetLeft + 'px';
  2690. break;
  2691. case MdPanelPosition.xPosition.OFFSET_END:
  2692. this._left = targetRight + 'px';
  2693. break;
  2694. }
  2695. var targetTop = targetBounds.top;
  2696. var targetBottom = targetBounds.bottom;
  2697. var targetHeight = targetBounds.height;
  2698. switch (position.y) {
  2699. case MdPanelPosition.yPosition.ABOVE:
  2700. this._top = targetTop - panelHeight + 'px';
  2701. break;
  2702. case MdPanelPosition.yPosition.ALIGN_BOTTOMS:
  2703. this._top = targetBottom - panelHeight + 'px';
  2704. break;
  2705. case MdPanelPosition.yPosition.CENTER:
  2706. var top = targetTop + (0.5 * targetHeight) - (0.5 * panelHeight);
  2707. this._top = top + 'px';
  2708. break;
  2709. case MdPanelPosition.yPosition.ALIGN_TOPS:
  2710. this._top = targetTop + 'px';
  2711. break;
  2712. case MdPanelPosition.yPosition.BELOW:
  2713. this._top = targetBottom + 'px';
  2714. break;
  2715. }
  2716. };
  2717. /*****************************************************************************
  2718. * MdPanelAnimation *
  2719. *****************************************************************************/
  2720. /**
  2721. * Animation configuration object. To use, create an MdPanelAnimation with the
  2722. * desired properties, then pass the object as part of $mdPanel creation.
  2723. *
  2724. * Example:
  2725. *
  2726. * var panelAnimation = new MdPanelAnimation()
  2727. * .openFrom(myButtonEl)
  2728. * .closeTo('.my-button')
  2729. * .withAnimation($mdPanel.animation.SCALE);
  2730. *
  2731. * $mdPanel.create({
  2732. * animation: panelAnimation
  2733. * });
  2734. *
  2735. * @param {!angular.$injector} $injector
  2736. * @final @constructor
  2737. */
  2738. function MdPanelAnimation($injector) {
  2739. /** @private @const {!angular.$mdUtil} */
  2740. this._$mdUtil = $injector.get('$mdUtil');
  2741. /**
  2742. * @private {{element: !angular.JQLite|undefined, bounds: !DOMRect}|
  2743. * undefined}
  2744. */
  2745. this._openFrom;
  2746. /**
  2747. * @private {{element: !angular.JQLite|undefined, bounds: !DOMRect}|
  2748. * undefined}
  2749. */
  2750. this._closeTo;
  2751. /** @private {string|{open: string, close: string}} */
  2752. this._animationClass = '';
  2753. /** @private {number} */
  2754. this._openDuration;
  2755. /** @private {number} */
  2756. this._closeDuration;
  2757. /** @private {number|{open: number, close: number}} */
  2758. this._rawDuration;
  2759. }
  2760. /**
  2761. * Possible default animations.
  2762. * @enum {string}
  2763. */
  2764. MdPanelAnimation.animation = {
  2765. SLIDE: 'md-panel-animate-slide',
  2766. SCALE: 'md-panel-animate-scale',
  2767. FADE: 'md-panel-animate-fade'
  2768. };
  2769. /**
  2770. * Specifies where to start the open animation. `openFrom` accepts a
  2771. * click event object, query selector, DOM element, or a Rect object that
  2772. * is used to determine the bounds. When passed a click event, the location
  2773. * of the click will be used as the position to start the animation.
  2774. * @param {string|!Element|!Event|{top: number, left: number}} openFrom
  2775. * @returns {!MdPanelAnimation}
  2776. */
  2777. MdPanelAnimation.prototype.openFrom = function(openFrom) {
  2778. // Check if 'openFrom' is an Event.
  2779. openFrom = openFrom.target ? openFrom.target : openFrom;
  2780. this._openFrom = this._getPanelAnimationTarget(openFrom);
  2781. if (!this._closeTo) {
  2782. this._closeTo = this._openFrom;
  2783. }
  2784. return this;
  2785. };
  2786. /**
  2787. * Specifies where to animate the panel close. `closeTo` accepts a
  2788. * query selector, DOM element, or a Rect object that is used to determine
  2789. * the bounds.
  2790. * @param {string|!Element|{top: number, left: number}} closeTo
  2791. * @returns {!MdPanelAnimation}
  2792. */
  2793. MdPanelAnimation.prototype.closeTo = function(closeTo) {
  2794. this._closeTo = this._getPanelAnimationTarget(closeTo);
  2795. return this;
  2796. };
  2797. /**
  2798. * Specifies the duration of the animation in milliseconds.
  2799. * @param {number|{open: number, close: number}} duration
  2800. * @returns {!MdPanelAnimation}
  2801. */
  2802. MdPanelAnimation.prototype.duration = function(duration) {
  2803. if (duration) {
  2804. if (angular.isNumber(duration)) {
  2805. this._openDuration = this._closeDuration = toSeconds(duration);
  2806. } else if (angular.isObject(duration)) {
  2807. this._openDuration = toSeconds(duration.open);
  2808. this._closeDuration = toSeconds(duration.close);
  2809. }
  2810. }
  2811. // Save the original value so it can be passed to the backdrop.
  2812. this._rawDuration = duration;
  2813. return this;
  2814. function toSeconds(value) {
  2815. if (angular.isNumber(value)) return value / 1000;
  2816. }
  2817. };
  2818. /**
  2819. * Returns the element and bounds for the animation target.
  2820. * @param {string|!Element|{top: number, left: number}} location
  2821. * @returns {{element: !angular.JQLite|undefined, bounds: !DOMRect}}
  2822. * @private
  2823. */
  2824. MdPanelAnimation.prototype._getPanelAnimationTarget = function(location) {
  2825. if (angular.isDefined(location.top) || angular.isDefined(location.left)) {
  2826. return {
  2827. element: undefined,
  2828. bounds: {
  2829. top: location.top || 0,
  2830. left: location.left || 0
  2831. }
  2832. };
  2833. } else {
  2834. return this._getBoundingClientRect(getElement(location));
  2835. }
  2836. };
  2837. /**
  2838. * Specifies the animation class.
  2839. *
  2840. * There are several default animations that can be used:
  2841. * (MdPanelAnimation.animation)
  2842. * SLIDE: The panel slides in and out from the specified
  2843. * elements.
  2844. * SCALE: The panel scales in and out.
  2845. * FADE: The panel fades in and out.
  2846. *
  2847. * @param {string|{open: string, close: string}} cssClass
  2848. * @returns {!MdPanelAnimation}
  2849. */
  2850. MdPanelAnimation.prototype.withAnimation = function(cssClass) {
  2851. this._animationClass = cssClass;
  2852. return this;
  2853. };
  2854. /**
  2855. * Animate the panel open.
  2856. * @param {!angular.JQLite} panelEl
  2857. * @returns {!angular.$q.Promise} A promise that is resolved when the open
  2858. * animation is complete.
  2859. */
  2860. MdPanelAnimation.prototype.animateOpen = function(panelEl) {
  2861. var animator = this._$mdUtil.dom.animator;
  2862. this._fixBounds(panelEl);
  2863. var animationOptions = {};
  2864. // Include the panel transformations when calculating the animations.
  2865. var panelTransform = panelEl[0].style.transform || '';
  2866. var openFrom = animator.toTransformCss(panelTransform);
  2867. var openTo = animator.toTransformCss(panelTransform);
  2868. switch (this._animationClass) {
  2869. case MdPanelAnimation.animation.SLIDE:
  2870. // Slide should start with opacity: 1.
  2871. panelEl.css('opacity', '1');
  2872. animationOptions = {
  2873. transitionInClass: '_md-panel-animate-enter'
  2874. };
  2875. var openSlide = animator.calculateSlideToOrigin(
  2876. panelEl, this._openFrom) || '';
  2877. openFrom = animator.toTransformCss(openSlide + ' ' + panelTransform);
  2878. break;
  2879. case MdPanelAnimation.animation.SCALE:
  2880. animationOptions = {
  2881. transitionInClass: '_md-panel-animate-enter'
  2882. };
  2883. var openScale = animator.calculateZoomToOrigin(
  2884. panelEl, this._openFrom) || '';
  2885. openFrom = animator.toTransformCss(openScale + ' ' + panelTransform);
  2886. break;
  2887. case MdPanelAnimation.animation.FADE:
  2888. animationOptions = {
  2889. transitionInClass: '_md-panel-animate-enter'
  2890. };
  2891. break;
  2892. default:
  2893. if (angular.isString(this._animationClass)) {
  2894. animationOptions = {
  2895. transitionInClass: this._animationClass
  2896. };
  2897. } else {
  2898. animationOptions = {
  2899. transitionInClass: this._animationClass['open'],
  2900. transitionOutClass: this._animationClass['close'],
  2901. };
  2902. }
  2903. }
  2904. animationOptions.duration = this._openDuration;
  2905. return animator
  2906. .translate3d(panelEl, openFrom, openTo, animationOptions);
  2907. };
  2908. /**
  2909. * Animate the panel close.
  2910. * @param {!angular.JQLite} panelEl
  2911. * @returns {!angular.$q.Promise} A promise that resolves when the close
  2912. * animation is complete.
  2913. */
  2914. MdPanelAnimation.prototype.animateClose = function(panelEl) {
  2915. var animator = this._$mdUtil.dom.animator;
  2916. var reverseAnimationOptions = {};
  2917. // Include the panel transformations when calculating the animations.
  2918. var panelTransform = panelEl[0].style.transform || '';
  2919. var closeFrom = animator.toTransformCss(panelTransform);
  2920. var closeTo = animator.toTransformCss(panelTransform);
  2921. switch (this._animationClass) {
  2922. case MdPanelAnimation.animation.SLIDE:
  2923. // Slide should start with opacity: 1.
  2924. panelEl.css('opacity', '1');
  2925. reverseAnimationOptions = {
  2926. transitionInClass: '_md-panel-animate-leave'
  2927. };
  2928. var closeSlide = animator.calculateSlideToOrigin(
  2929. panelEl, this._closeTo) || '';
  2930. closeTo = animator.toTransformCss(closeSlide + ' ' + panelTransform);
  2931. break;
  2932. case MdPanelAnimation.animation.SCALE:
  2933. reverseAnimationOptions = {
  2934. transitionInClass: '_md-panel-animate-scale-out _md-panel-animate-leave'
  2935. };
  2936. var closeScale = animator.calculateZoomToOrigin(
  2937. panelEl, this._closeTo) || '';
  2938. closeTo = animator.toTransformCss(closeScale + ' ' + panelTransform);
  2939. break;
  2940. case MdPanelAnimation.animation.FADE:
  2941. reverseAnimationOptions = {
  2942. transitionInClass: '_md-panel-animate-fade-out _md-panel-animate-leave'
  2943. };
  2944. break;
  2945. default:
  2946. if (angular.isString(this._animationClass)) {
  2947. reverseAnimationOptions = {
  2948. transitionOutClass: this._animationClass
  2949. };
  2950. } else {
  2951. reverseAnimationOptions = {
  2952. transitionInClass: this._animationClass['close'],
  2953. transitionOutClass: this._animationClass['open']
  2954. };
  2955. }
  2956. }
  2957. reverseAnimationOptions.duration = this._closeDuration;
  2958. return animator
  2959. .translate3d(panelEl, closeFrom, closeTo, reverseAnimationOptions);
  2960. };
  2961. /**
  2962. * Set the height and width to match the panel if not provided.
  2963. * @param {!angular.JQLite} panelEl
  2964. * @private
  2965. */
  2966. MdPanelAnimation.prototype._fixBounds = function(panelEl) {
  2967. var panelWidth = panelEl[0].offsetWidth;
  2968. var panelHeight = panelEl[0].offsetHeight;
  2969. if (this._openFrom && this._openFrom.bounds.height == null) {
  2970. this._openFrom.bounds.height = panelHeight;
  2971. }
  2972. if (this._openFrom && this._openFrom.bounds.width == null) {
  2973. this._openFrom.bounds.width = panelWidth;
  2974. }
  2975. if (this._closeTo && this._closeTo.bounds.height == null) {
  2976. this._closeTo.bounds.height = panelHeight;
  2977. }
  2978. if (this._closeTo && this._closeTo.bounds.width == null) {
  2979. this._closeTo.bounds.width = panelWidth;
  2980. }
  2981. };
  2982. /**
  2983. * Identify the bounding RECT for the target element.
  2984. * @param {!angular.JQLite} element
  2985. * @returns {{element: !angular.JQLite|undefined, bounds: !DOMRect}}
  2986. * @private
  2987. */
  2988. MdPanelAnimation.prototype._getBoundingClientRect = function(element) {
  2989. if (element instanceof angular.element) {
  2990. return {
  2991. element: element,
  2992. bounds: element[0].getBoundingClientRect()
  2993. };
  2994. }
  2995. };
  2996. /*****************************************************************************
  2997. * Util Methods *
  2998. *****************************************************************************/
  2999. /**
  3000. * Returns the angular element associated with a css selector or element.
  3001. * @param el {string|!angular.JQLite|!Element}
  3002. * @returns {!angular.JQLite}
  3003. */
  3004. function getElement(el) {
  3005. var queryResult = angular.isString(el) ?
  3006. document.querySelector(el) : el;
  3007. return angular.element(queryResult);
  3008. }
  3009. /**
  3010. * Gets the computed values for an element's translateX and translateY in px.
  3011. * @param {!angular.JQLite|!Element} el
  3012. * @param {string} property
  3013. * @return {{x: number, y: number}}
  3014. */
  3015. function getComputedTranslations(el, property) {
  3016. // The transform being returned by `getComputedStyle` is in the format:
  3017. // `matrix(a, b, c, d, translateX, translateY)` if defined and `none`
  3018. // if the element doesn't have a transform.
  3019. var transform = getComputedStyle(el[0] || el)[property];
  3020. var openIndex = transform.indexOf('(');
  3021. var closeIndex = transform.lastIndexOf(')');
  3022. var output = { x: 0, y: 0 };
  3023. if (openIndex > -1 && closeIndex > -1) {
  3024. var parsedValues = transform
  3025. .substring(openIndex + 1, closeIndex)
  3026. .split(', ')
  3027. .slice(-2);
  3028. output.x = parseInt(parsedValues[0]);
  3029. output.y = parseInt(parsedValues[1]);
  3030. }
  3031. return output;
  3032. }
  3033. })(window, window.angular);