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.

535 lines
17 KiB

  1. /*!
  2. * Angular Material Design
  3. * https://github.com/angular/material
  4. * @license MIT
  5. * v1.1.1
  6. */
  7. (function( window, angular, undefined ){
  8. "use strict";
  9. /**
  10. * @ngdoc module
  11. * @name material.components.sidenav
  12. *
  13. * @description
  14. * A Sidenav QP component.
  15. */
  16. SidenavService.$inject = ["$mdComponentRegistry", "$mdUtil", "$q", "$log"];
  17. SidenavDirective.$inject = ["$mdMedia", "$mdUtil", "$mdConstant", "$mdTheming", "$animate", "$compile", "$parse", "$log", "$q", "$document"];
  18. SidenavController.$inject = ["$scope", "$element", "$attrs", "$mdComponentRegistry", "$q"];
  19. angular
  20. .module('material.components.sidenav', [
  21. 'material.core',
  22. 'material.components.backdrop'
  23. ])
  24. .factory('$mdSidenav', SidenavService )
  25. .directive('mdSidenav', SidenavDirective)
  26. .directive('mdSidenavFocus', SidenavFocusDirective)
  27. .controller('$mdSidenavController', SidenavController);
  28. /**
  29. * @ngdoc service
  30. * @name $mdSidenav
  31. * @module material.components.sidenav
  32. *
  33. * @description
  34. * `$mdSidenav` makes it easy to interact with multiple sidenavs
  35. * in an app. When looking up a sidenav instance, you can either look
  36. * it up synchronously or wait for it to be initializied asynchronously.
  37. * This is done by passing the second argument to `$mdSidenav`.
  38. *
  39. * @usage
  40. * <hljs lang="js">
  41. * // Async lookup for sidenav instance; will resolve when the instance is available
  42. * $mdSidenav(componentId, true).then(function(instance) {
  43. * $log.debug( componentId + "is now ready" );
  44. * });
  45. * // Sync lookup for sidenav instance; this will resolve immediately.
  46. * $mdSidenav(componentId).then(function(instance) {
  47. * $log.debug( componentId + "is now ready" );
  48. * });
  49. * // Async toggle the given sidenav;
  50. * // when instance is known ready and lazy lookup is not needed.
  51. * $mdSidenav(componentId)
  52. * .toggle()
  53. * .then(function(){
  54. * $log.debug('toggled');
  55. * });
  56. * // Async open the given sidenav
  57. * $mdSidenav(componentId)
  58. * .open()
  59. * .then(function(){
  60. * $log.debug('opened');
  61. * });
  62. * // Async close the given sidenav
  63. * $mdSidenav(componentId)
  64. * .close()
  65. * .then(function(){
  66. * $log.debug('closed');
  67. * });
  68. * // Sync check to see if the specified sidenav is set to be open
  69. * $mdSidenav(componentId).isOpen();
  70. * // Sync check to whether given sidenav is locked open
  71. * // If this is true, the sidenav will be open regardless of close()
  72. * $mdSidenav(componentId).isLockedOpen();
  73. * // On close callback to handle close, backdrop click or escape key pressed
  74. * // Callback happens BEFORE the close action occurs.
  75. * $mdSidenav(componentId).onClose(function () {
  76. * $log.debug('closing');
  77. * });
  78. * </hljs>
  79. */
  80. function SidenavService($mdComponentRegistry, $mdUtil, $q, $log) {
  81. var errorMsg = "SideNav '{0}' is not available! Did you use md-component-id='{0}'?";
  82. var service = {
  83. find : findInstance, // sync - returns proxy API
  84. waitFor : waitForInstance // async - returns promise
  85. };
  86. /**
  87. * Service API that supports three (3) usages:
  88. * $mdSidenav().find("left") // sync (must already exist) or returns undefined
  89. * $mdSidenav("left").toggle(); // sync (must already exist) or returns reject promise;
  90. * $mdSidenav("left",true).then( function(left){ // async returns instance when available
  91. * left.toggle();
  92. * });
  93. */
  94. return function(handle, enableWait) {
  95. if ( angular.isUndefined(handle) ) return service;
  96. var shouldWait = enableWait === true;
  97. var instance = service.find(handle, shouldWait);
  98. return !instance && shouldWait ? service.waitFor(handle) :
  99. !instance && angular.isUndefined(enableWait) ? addLegacyAPI(service, handle) : instance;
  100. };
  101. /**
  102. * For failed instance/handle lookups, older-clients expect an response object with noops
  103. * that include `rejected promise APIs`
  104. */
  105. function addLegacyAPI(service, handle) {
  106. var falseFn = function() { return false; };
  107. var rejectFn = function() {
  108. return $q.when($mdUtil.supplant(errorMsg, [handle || ""]));
  109. };
  110. return angular.extend({
  111. isLockedOpen : falseFn,
  112. isOpen : falseFn,
  113. toggle : rejectFn,
  114. open : rejectFn,
  115. close : rejectFn,
  116. onClose : angular.noop,
  117. then : function(callback) {
  118. return waitForInstance(handle)
  119. .then(callback || angular.noop);
  120. }
  121. }, service);
  122. }
  123. /**
  124. * Synchronously lookup the controller instance for the specified sidNav instance which has been
  125. * registered with the markup `md-component-id`
  126. */
  127. function findInstance(handle, shouldWait) {
  128. var instance = $mdComponentRegistry.get(handle);
  129. if (!instance && !shouldWait) {
  130. // Report missing instance
  131. $log.error( $mdUtil.supplant(errorMsg, [handle || ""]) );
  132. // The component has not registered itself... most like NOT yet created
  133. // return null to indicate that the Sidenav is not in the DOM
  134. return undefined;
  135. }
  136. return instance;
  137. }
  138. /**
  139. * Asynchronously wait for the component instantiation,
  140. * Deferred lookup of component instance using $component registry
  141. */
  142. function waitForInstance(handle) {
  143. return $mdComponentRegistry.when(handle).catch($log.error);
  144. }
  145. }
  146. /**
  147. * @ngdoc directive
  148. * @name mdSidenavFocus
  149. * @module material.components.sidenav
  150. *
  151. * @restrict A
  152. *
  153. * @description
  154. * `mdSidenavFocus` provides a way to specify the focused element when a sidenav opens.
  155. * This is completely optional, as the sidenav itself is focused by default.
  156. *
  157. * @usage
  158. * <hljs lang="html">
  159. * <md-sidenav>
  160. * <form>
  161. * <md-input-container>
  162. * <label for="testInput">Label</label>
  163. * <input id="testInput" type="text" md-sidenav-focus>
  164. * </md-input-container>
  165. * </form>
  166. * </md-sidenav>
  167. * </hljs>
  168. **/
  169. function SidenavFocusDirective() {
  170. return {
  171. restrict: 'A',
  172. require: '^mdSidenav',
  173. link: function(scope, element, attr, sidenavCtrl) {
  174. // @see $mdUtil.findFocusTarget(...)
  175. }
  176. };
  177. }
  178. /**
  179. * @ngdoc directive
  180. * @name mdSidenav
  181. * @module material.components.sidenav
  182. * @restrict E
  183. *
  184. * @description
  185. *
  186. * A Sidenav component that can be opened and closed programatically.
  187. *
  188. * By default, upon opening it will slide out on top of the main content area.
  189. *
  190. * For keyboard and screen reader accessibility, focus is sent to the sidenav wrapper by default.
  191. * It can be overridden with the `md-autofocus` directive on the child element you want focused.
  192. *
  193. * @usage
  194. * <hljs lang="html">
  195. * <div layout="row" ng-controller="MyController">
  196. * <md-sidenav md-component-id="left" class="md-sidenav-left">
  197. * Left Nav!
  198. * </md-sidenav>
  199. *
  200. * <md-content>
  201. * Center Content
  202. * <md-button ng-click="openLeftMenu()">
  203. * Open Left Menu
  204. * </md-button>
  205. * </md-content>
  206. *
  207. * <md-sidenav md-component-id="right"
  208. * md-is-locked-open="$mdMedia('min-width: 333px')"
  209. * class="md-sidenav-right">
  210. * <form>
  211. * <md-input-container>
  212. * <label for="testInput">Test input</label>
  213. * <input id="testInput" type="text"
  214. * ng-model="data" md-autofocus>
  215. * </md-input-container>
  216. * </form>
  217. * </md-sidenav>
  218. * </div>
  219. * </hljs>
  220. *
  221. * <hljs lang="js">
  222. * var app = angular.module('myApp', ['ngMaterial']);
  223. * app.controller('MyController', function($scope, $mdSidenav) {
  224. * $scope.openLeftMenu = function() {
  225. * $mdSidenav('left').toggle();
  226. * };
  227. * });
  228. * </hljs>
  229. *
  230. * @param {expression=} md-is-open A model bound to whether the sidenav is opened.
  231. * @param {boolean=} md-disable-backdrop When present in the markup, the sidenav will not show a backdrop.
  232. * @param {string=} md-component-id componentId to use with $mdSidenav service.
  233. * @param {expression=} md-is-locked-open When this expression evaluates to true,
  234. * the sidenav 'locks open': it falls into the content's flow instead
  235. * of appearing over it. This overrides the `md-is-open` attribute.
  236. * @param {string=} md-disable-scroll-target Selector, pointing to an element, whose scrolling will
  237. * be disabled when the sidenav is opened. By default this is the sidenav's direct parent.
  238. *
  239. * The $mdMedia() service is exposed to the is-locked-open attribute, which
  240. * can be given a media query or one of the `sm`, `gt-sm`, `md`, `gt-md`, `lg` or `gt-lg` presets.
  241. * Examples:
  242. *
  243. * - `<md-sidenav md-is-locked-open="shouldLockOpen"></md-sidenav>`
  244. * - `<md-sidenav md-is-locked-open="$mdMedia('min-width: 1000px')"></md-sidenav>`
  245. * - `<md-sidenav md-is-locked-open="$mdMedia('sm')"></md-sidenav>` (locks open on small screens)
  246. */
  247. function SidenavDirective($mdMedia, $mdUtil, $mdConstant, $mdTheming, $animate, $compile, $parse, $log, $q, $document) {
  248. return {
  249. restrict: 'E',
  250. scope: {
  251. isOpen: '=?mdIsOpen'
  252. },
  253. controller: '$mdSidenavController',
  254. compile: function(element) {
  255. element.addClass('md-closed');
  256. element.attr('tabIndex', '-1');
  257. return postLink;
  258. }
  259. };
  260. /**
  261. * Directive Post Link function...
  262. */
  263. function postLink(scope, element, attr, sidenavCtrl) {
  264. var lastParentOverFlow;
  265. var backdrop;
  266. var disableScrollTarget = null;
  267. var triggeringElement = null;
  268. var previousContainerStyles;
  269. var promise = $q.when(true);
  270. var isLockedOpenParsed = $parse(attr.mdIsLockedOpen);
  271. var isLocked = function() {
  272. return isLockedOpenParsed(scope.$parent, {
  273. $media: function(arg) {
  274. $log.warn("$media is deprecated for is-locked-open. Use $mdMedia instead.");
  275. return $mdMedia(arg);
  276. },
  277. $mdMedia: $mdMedia
  278. });
  279. };
  280. if (attr.mdDisableScrollTarget) {
  281. disableScrollTarget = $document[0].querySelector(attr.mdDisableScrollTarget);
  282. if (disableScrollTarget) {
  283. disableScrollTarget = angular.element(disableScrollTarget);
  284. } else {
  285. $log.warn($mdUtil.supplant('mdSidenav: couldn\'t find element matching ' +
  286. 'selector "{selector}". Falling back to parent.', { selector: attr.mdDisableScrollTarget }));
  287. }
  288. }
  289. if (!disableScrollTarget) {
  290. disableScrollTarget = element.parent();
  291. }
  292. // Only create the backdrop if the backdrop isn't disabled.
  293. if (!attr.hasOwnProperty('mdDisableBackdrop')) {
  294. backdrop = $mdUtil.createBackdrop(scope, "md-sidenav-backdrop md-opaque ng-enter");
  295. }
  296. element.addClass('_md'); // private md component indicator for styling
  297. $mdTheming(element);
  298. // The backdrop should inherit the sidenavs theme,
  299. // because the backdrop will take its parent theme by default.
  300. if ( backdrop ) $mdTheming.inherit(backdrop, element);
  301. element.on('$destroy', function() {
  302. backdrop && backdrop.remove();
  303. sidenavCtrl.destroy();
  304. });
  305. scope.$on('$destroy', function(){
  306. backdrop && backdrop.remove();
  307. });
  308. scope.$watch(isLocked, updateIsLocked);
  309. scope.$watch('isOpen', updateIsOpen);
  310. // Publish special accessor for the Controller instance
  311. sidenavCtrl.$toggleOpen = toggleOpen;
  312. /**
  313. * Toggle the DOM classes to indicate `locked`
  314. * @param isLocked
  315. */
  316. function updateIsLocked(isLocked, oldValue) {
  317. scope.isLockedOpen = isLocked;
  318. if (isLocked === oldValue) {
  319. element.toggleClass('md-locked-open', !!isLocked);
  320. } else {
  321. $animate[isLocked ? 'addClass' : 'removeClass'](element, 'md-locked-open');
  322. }
  323. if (backdrop) {
  324. backdrop.toggleClass('md-locked-open', !!isLocked);
  325. }
  326. }
  327. /**
  328. * Toggle the SideNav view and attach/detach listeners
  329. * @param isOpen
  330. */
  331. function updateIsOpen(isOpen) {
  332. // Support deprecated md-sidenav-focus attribute as fallback
  333. var focusEl = $mdUtil.findFocusTarget(element) || $mdUtil.findFocusTarget(element,'[md-sidenav-focus]') || element;
  334. var parent = element.parent();
  335. parent[isOpen ? 'on' : 'off']('keydown', onKeyDown);
  336. if (backdrop) backdrop[isOpen ? 'on' : 'off']('click', close);
  337. var restorePositioning = updateContainerPositions(parent, isOpen);
  338. if ( isOpen ) {
  339. // Capture upon opening..
  340. triggeringElement = $document[0].activeElement;
  341. }
  342. disableParentScroll(isOpen);
  343. return promise = $q.all([
  344. isOpen && backdrop ? $animate.enter(backdrop, parent) : backdrop ?
  345. $animate.leave(backdrop) : $q.when(true),
  346. $animate[isOpen ? 'removeClass' : 'addClass'](element, 'md-closed')
  347. ]).then(function() {
  348. // Perform focus when animations are ALL done...
  349. if (scope.isOpen) {
  350. focusEl && focusEl.focus();
  351. }
  352. // Restores the positioning on the sidenav and backdrop.
  353. restorePositioning && restorePositioning();
  354. });
  355. }
  356. function updateContainerPositions(parent, willOpen) {
  357. var drawerEl = element[0];
  358. var scrollTop = parent[0].scrollTop;
  359. if (willOpen && scrollTop) {
  360. previousContainerStyles = {
  361. top: drawerEl.style.top,
  362. bottom: drawerEl.style.bottom,
  363. height: drawerEl.style.height
  364. };
  365. // When the parent is scrolled down, then we want to be able to show the sidenav at the current scroll
  366. // position. We're moving the sidenav down to the correct scroll position and apply the height of the
  367. // parent, to increase the performance. Using 100% as height, will impact the performance heavily.
  368. var positionStyle = {
  369. top: scrollTop + 'px',
  370. bottom: 'auto',
  371. height: parent[0].clientHeight + 'px'
  372. };
  373. // Apply the new position styles to the sidenav and backdrop.
  374. element.css(positionStyle);
  375. backdrop.css(positionStyle);
  376. }
  377. // When the sidenav is closing and we have previous defined container styles,
  378. // then we return a restore function, which resets the sidenav and backdrop.
  379. if (!willOpen && previousContainerStyles) {
  380. return function() {
  381. drawerEl.style.top = previousContainerStyles.top;
  382. drawerEl.style.bottom = previousContainerStyles.bottom;
  383. drawerEl.style.height = previousContainerStyles.height;
  384. backdrop[0].style.top = null;
  385. backdrop[0].style.bottom = null;
  386. backdrop[0].style.height = null;
  387. previousContainerStyles = null;
  388. };
  389. }
  390. }
  391. /**
  392. * Prevent parent scrolling (when the SideNav is open)
  393. */
  394. function disableParentScroll(disabled) {
  395. if ( disabled && !lastParentOverFlow ) {
  396. lastParentOverFlow = disableScrollTarget.css('overflow');
  397. disableScrollTarget.css('overflow', 'hidden');
  398. } else if (angular.isDefined(lastParentOverFlow)) {
  399. disableScrollTarget.css('overflow', lastParentOverFlow);
  400. lastParentOverFlow = undefined;
  401. }
  402. }
  403. /**
  404. * Toggle the sideNav view and publish a promise to be resolved when
  405. * the view animation finishes.
  406. *
  407. * @param isOpen
  408. * @returns {*}
  409. */
  410. function toggleOpen( isOpen ) {
  411. if (scope.isOpen == isOpen ) {
  412. return $q.when(true);
  413. } else {
  414. if (scope.isOpen && sidenavCtrl.onCloseCb) sidenavCtrl.onCloseCb();
  415. return $q(function(resolve){
  416. // Toggle value to force an async `updateIsOpen()` to run
  417. scope.isOpen = isOpen;
  418. $mdUtil.nextTick(function() {
  419. // When the current `updateIsOpen()` animation finishes
  420. promise.then(function(result) {
  421. if ( !scope.isOpen ) {
  422. // reset focus to originating element (if available) upon close
  423. triggeringElement && triggeringElement.focus();
  424. triggeringElement = null;
  425. }
  426. resolve(result);
  427. });
  428. });
  429. });
  430. }
  431. }
  432. /**
  433. * Auto-close sideNav when the `escape` key is pressed.
  434. * @param evt
  435. */
  436. function onKeyDown(ev) {
  437. var isEscape = (ev.keyCode === $mdConstant.KEY_CODE.ESCAPE);
  438. return isEscape ? close(ev) : $q.when(true);
  439. }
  440. /**
  441. * With backdrop `clicks` or `escape` key-press, immediately
  442. * apply the CSS close transition... Then notify the controller
  443. * to close() and perform its own actions.
  444. */
  445. function close(ev) {
  446. ev.preventDefault();
  447. return sidenavCtrl.close();
  448. }
  449. }
  450. }
  451. /*
  452. * @private
  453. * @ngdoc controller
  454. * @name SidenavController
  455. * @module material.components.sidenav
  456. *
  457. */
  458. function SidenavController($scope, $element, $attrs, $mdComponentRegistry, $q) {
  459. var self = this;
  460. // Use Default internal method until overridden by directive postLink
  461. // Synchronous getters
  462. self.isOpen = function() { return !!$scope.isOpen; };
  463. self.isLockedOpen = function() { return !!$scope.isLockedOpen; };
  464. // Synchronous setters
  465. self.onClose = function (callback) {
  466. self.onCloseCb = callback;
  467. return self;
  468. };
  469. // Async actions
  470. self.open = function() { return self.$toggleOpen( true ); };
  471. self.close = function() { return self.$toggleOpen( false ); };
  472. self.toggle = function() { return self.$toggleOpen( !$scope.isOpen ); };
  473. self.$toggleOpen = function(value) { return $q.when($scope.isOpen = value); };
  474. self.destroy = $mdComponentRegistry.register(self, $attrs.mdComponentId);
  475. }
  476. })(window, window.angular);