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.

559 lines
18 KiB

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