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.

1095 lines
37 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.menu');
  8. goog.require('ngmaterial.components.backdrop');
  9. goog.require('ngmaterial.core');
  10. /**
  11. * @ngdoc module
  12. * @name material.components.menu
  13. */
  14. angular.module('material.components.menu', [
  15. 'material.core',
  16. 'material.components.backdrop'
  17. ]);
  18. MenuController['$inject'] = ["$mdMenu", "$attrs", "$element", "$scope", "$mdUtil", "$timeout", "$rootScope", "$q", "$log"];
  19. angular
  20. .module('material.components.menu')
  21. .controller('mdMenuCtrl', MenuController);
  22. /**
  23. * ngInject
  24. */
  25. function MenuController($mdMenu, $attrs, $element, $scope, $mdUtil, $timeout, $rootScope, $q, $log) {
  26. var prefixer = $mdUtil.prefixer();
  27. var menuContainer;
  28. var self = this;
  29. var triggerElement;
  30. this.nestLevel = parseInt($attrs.mdNestLevel, 10) || 0;
  31. /**
  32. * Called by our linking fn to provide access to the menu-content
  33. * element removed during link
  34. */
  35. this.init = function init(setMenuContainer, opts) {
  36. opts = opts || {};
  37. menuContainer = setMenuContainer;
  38. // Default element for ARIA attributes has the ngClick or ngMouseenter expression
  39. triggerElement = $element[0].querySelector(prefixer.buildSelector(['ng-click', 'ng-mouseenter']));
  40. triggerElement.setAttribute('aria-expanded', 'false');
  41. this.isInMenuBar = opts.isInMenuBar;
  42. this.nestedMenus = $mdUtil.nodesToArray(menuContainer[0].querySelectorAll('.md-nested-menu'));
  43. menuContainer.on('$mdInterimElementRemove', function() {
  44. self.isOpen = false;
  45. $mdUtil.nextTick(function(){ self.onIsOpenChanged(self.isOpen);});
  46. });
  47. $mdUtil.nextTick(function(){ self.onIsOpenChanged(self.isOpen);});
  48. var menuContainerId = 'menu_container_' + $mdUtil.nextUid();
  49. menuContainer.attr('id', menuContainerId);
  50. angular.element(triggerElement).attr({
  51. 'aria-owns': menuContainerId,
  52. 'aria-haspopup': 'true'
  53. });
  54. $scope.$on('$destroy', angular.bind(this, function() {
  55. this.disableHoverListener();
  56. $mdMenu.destroy();
  57. }));
  58. menuContainer.on('$destroy', function() {
  59. $mdMenu.destroy();
  60. });
  61. };
  62. var openMenuTimeout, menuItems, deregisterScopeListeners = [];
  63. this.enableHoverListener = function() {
  64. deregisterScopeListeners.push($rootScope.$on('$mdMenuOpen', function(event, el) {
  65. if (menuContainer[0].contains(el[0])) {
  66. self.currentlyOpenMenu = el.controller('mdMenu');
  67. self.isAlreadyOpening = false;
  68. self.currentlyOpenMenu.registerContainerProxy(self.triggerContainerProxy.bind(self));
  69. }
  70. }));
  71. deregisterScopeListeners.push($rootScope.$on('$mdMenuClose', function(event, el) {
  72. if (menuContainer[0].contains(el[0])) {
  73. self.currentlyOpenMenu = undefined;
  74. }
  75. }));
  76. menuItems = angular.element($mdUtil.nodesToArray(menuContainer[0].children[0].children));
  77. menuItems.on('mouseenter', self.handleMenuItemHover);
  78. menuItems.on('mouseleave', self.handleMenuItemMouseLeave);
  79. };
  80. this.disableHoverListener = function() {
  81. while (deregisterScopeListeners.length) {
  82. deregisterScopeListeners.shift()();
  83. }
  84. menuItems && menuItems.off('mouseenter', self.handleMenuItemHover);
  85. menuItems && menuItems.off('mouseleave', self.handleMenuItemMouseLeave);
  86. };
  87. this.handleMenuItemHover = function(event) {
  88. if (self.isAlreadyOpening) return;
  89. var nestedMenu = (
  90. event.target.querySelector('md-menu')
  91. || $mdUtil.getClosest(event.target, 'MD-MENU')
  92. );
  93. openMenuTimeout = $timeout(function() {
  94. if (nestedMenu) {
  95. nestedMenu = angular.element(nestedMenu).controller('mdMenu');
  96. }
  97. if (self.currentlyOpenMenu && self.currentlyOpenMenu != nestedMenu) {
  98. var closeTo = self.nestLevel + 1;
  99. self.currentlyOpenMenu.close(true, { closeTo: closeTo });
  100. self.isAlreadyOpening = !!nestedMenu;
  101. nestedMenu && nestedMenu.open();
  102. } else if (nestedMenu && !nestedMenu.isOpen && nestedMenu.open) {
  103. self.isAlreadyOpening = !!nestedMenu;
  104. nestedMenu && nestedMenu.open();
  105. }
  106. }, nestedMenu ? 100 : 250);
  107. var focusableTarget = event.currentTarget.querySelector('.md-button:not([disabled])');
  108. focusableTarget && focusableTarget.focus();
  109. };
  110. this.handleMenuItemMouseLeave = function() {
  111. if (openMenuTimeout) {
  112. $timeout.cancel(openMenuTimeout);
  113. openMenuTimeout = undefined;
  114. }
  115. };
  116. /**
  117. * Uses the $mdMenu interim element service to open the menu contents
  118. */
  119. this.open = function openMenu(ev) {
  120. ev && ev.stopPropagation();
  121. ev && ev.preventDefault();
  122. if (self.isOpen) return;
  123. self.enableHoverListener();
  124. self.isOpen = true;
  125. $mdUtil.nextTick(function(){ self.onIsOpenChanged(self.isOpen);});
  126. triggerElement = triggerElement || (ev ? ev.target : $element[0]);
  127. triggerElement.setAttribute('aria-expanded', 'true');
  128. $scope.$emit('$mdMenuOpen', $element);
  129. $mdMenu.show({
  130. scope: $scope,
  131. mdMenuCtrl: self,
  132. nestLevel: self.nestLevel,
  133. element: menuContainer,
  134. target: triggerElement,
  135. preserveElement: true,
  136. parent: 'body'
  137. }).finally(function() {
  138. triggerElement.setAttribute('aria-expanded', 'false');
  139. self.disableHoverListener();
  140. });
  141. };
  142. this.onIsOpenChanged = function(isOpen) {
  143. if (isOpen) {
  144. menuContainer.attr('aria-hidden', 'false');
  145. $element[0].classList.add('md-open');
  146. angular.forEach(self.nestedMenus, function(el) {
  147. el.classList.remove('md-open');
  148. });
  149. } else {
  150. menuContainer.attr('aria-hidden', 'true');
  151. $element[0].classList.remove('md-open');
  152. }
  153. $scope.$mdMenuIsOpen = self.isOpen;
  154. };
  155. this.focusMenuContainer = function focusMenuContainer() {
  156. var focusTarget = menuContainer[0]
  157. .querySelector(prefixer.buildSelector(['md-menu-focus-target', 'md-autofocus']));
  158. if (!focusTarget) focusTarget = menuContainer[0].querySelector('.md-button:not([disabled])');
  159. focusTarget.focus();
  160. };
  161. this.registerContainerProxy = function registerContainerProxy(handler) {
  162. this.containerProxy = handler;
  163. };
  164. this.triggerContainerProxy = function triggerContainerProxy(ev) {
  165. this.containerProxy && this.containerProxy(ev);
  166. };
  167. this.destroy = function() {
  168. return self.isOpen ? $mdMenu.destroy() : $q.when(false);
  169. };
  170. // Use the $mdMenu interim element service to close the menu contents
  171. this.close = function closeMenu(skipFocus, closeOpts) {
  172. if ( !self.isOpen ) return;
  173. self.isOpen = false;
  174. $mdUtil.nextTick(function(){ self.onIsOpenChanged(self.isOpen);});
  175. var eventDetails = angular.extend({}, closeOpts, { skipFocus: skipFocus });
  176. $scope.$emit('$mdMenuClose', $element, eventDetails);
  177. $mdMenu.hide(null, closeOpts);
  178. if (!skipFocus) {
  179. var el = self.restoreFocusTo || $element.find('button')[0];
  180. if (el instanceof angular.element) el = el[0];
  181. if (el) el.focus();
  182. }
  183. };
  184. /**
  185. * Build a nice object out of our string attribute which specifies the
  186. * target mode for left and top positioning
  187. */
  188. this.positionMode = function positionMode() {
  189. var attachment = ($attrs.mdPositionMode || 'target').split(' ');
  190. // If attachment is a single item, duplicate it for our second value.
  191. // ie. 'target' -> 'target target'
  192. if (attachment.length == 1) {
  193. attachment.push(attachment[0]);
  194. }
  195. return {
  196. left: attachment[0],
  197. top: attachment[1]
  198. };
  199. };
  200. /**
  201. * Build a nice object out of our string attribute which specifies
  202. * the offset of top and left in pixels.
  203. */
  204. this.offsets = function offsets() {
  205. var position = ($attrs.mdOffset || '0 0').split(' ').map(parseFloat);
  206. if (position.length == 2) {
  207. return {
  208. left: position[0],
  209. top: position[1]
  210. };
  211. } else if (position.length == 1) {
  212. return {
  213. top: position[0],
  214. left: position[0]
  215. };
  216. } else {
  217. throw Error('Invalid offsets specified. Please follow format <x, y> or <n>');
  218. }
  219. };
  220. // Functionality that is exposed in the view.
  221. $scope.$mdMenu = {
  222. open: this.open,
  223. close: this.close
  224. };
  225. // Deprecated APIs
  226. $scope.$mdOpenMenu = angular.bind(this, function() {
  227. $log.warn('mdMenu: The $mdOpenMenu method is deprecated. Please use `$mdMenu.open`.');
  228. return this.open.apply(this, arguments);
  229. });
  230. }
  231. /**
  232. * @ngdoc directive
  233. * @name mdMenu
  234. * @module material.components.menu
  235. * @restrict E
  236. * @description
  237. *
  238. * Menus are elements that open when clicked. They are useful for displaying
  239. * additional options within the context of an action.
  240. *
  241. * Every `md-menu` must specify exactly two child elements. The first element is what is
  242. * left in the DOM and is used to open the menu. This element is called the trigger element.
  243. * The trigger element's scope has access to `$mdMenu.open($event)`
  244. * which it may call to open the menu. By passing $event as argument, the
  245. * corresponding event is stopped from propagating up the DOM-tree. Similarly, `$mdMenu.close()`
  246. * can be used to close the menu.
  247. *
  248. * The second element is the `md-menu-content` element which represents the
  249. * contents of the menu when it is open. Typically this will contain `md-menu-item`s,
  250. * but you can do custom content as well.
  251. *
  252. * <hljs lang="html">
  253. * <md-menu>
  254. * <!-- Trigger element is a md-button with an icon -->
  255. * <md-button ng-click="$mdMenu.open($event)" class="md-icon-button" aria-label="Open sample menu">
  256. * <md-icon md-svg-icon="call:phone"></md-icon>
  257. * </md-button>
  258. * <md-menu-content>
  259. * <md-menu-item><md-button ng-click="doSomething()">Do Something</md-button></md-menu-item>
  260. * </md-menu-content>
  261. * </md-menu>
  262. * </hljs>
  263. * ## Sizing Menus
  264. *
  265. * The width of the menu when it is open may be specified by specifying a `width`
  266. * attribute on the `md-menu-content` element.
  267. * See the [Material Design Spec](https://material.google.com/components/menus.html#menus-simple-menus)
  268. * for more information.
  269. *
  270. *
  271. * ## Aligning Menus
  272. *
  273. * When a menu opens, it is important that the content aligns with the trigger element.
  274. * Failure to align menus can result in jarring experiences for users as content
  275. * suddenly shifts. To help with this, `md-menu` provides serveral APIs to help
  276. * with alignment.
  277. *
  278. * ### Target Mode
  279. *
  280. * By default, `md-menu` will attempt to align the `md-menu-content` by aligning
  281. * designated child elements in both the trigger and the menu content.
  282. *
  283. * To specify the alignment element in the `trigger` you can use the `md-menu-origin`
  284. * attribute on a child element. If no `md-menu-origin` is specified, the `md-menu`
  285. * will be used as the origin element.
  286. *
  287. * Similarly, the `md-menu-content` may specify a `md-menu-align-target` for a
  288. * `md-menu-item` to specify the node that it should try and align with.
  289. *
  290. * In this example code, we specify an icon to be our origin element, and an
  291. * icon in our menu content to be our alignment target. This ensures that both
  292. * icons are aligned when the menu opens.
  293. *
  294. * <hljs lang="html">
  295. * <md-menu>
  296. * <md-button ng-click="$mdMenu.open($event)" class="md-icon-button" aria-label="Open some menu">
  297. * <md-icon md-menu-origin md-svg-icon="call:phone"></md-icon>
  298. * </md-button>
  299. * <md-menu-content>
  300. * <md-menu-item>
  301. * <md-button ng-click="doSomething()" aria-label="Do something">
  302. * <md-icon md-menu-align-target md-svg-icon="call:phone"></md-icon>
  303. * Do Something
  304. * </md-button>
  305. * </md-menu-item>
  306. * </md-menu-content>
  307. * </md-menu>
  308. * </hljs>
  309. *
  310. * Sometimes we want to specify alignment on the right side of an element, for example
  311. * if we have a menu on the right side a toolbar, we want to right align our menu content.
  312. *
  313. * We can specify the origin by using the `md-position-mode` attribute on both
  314. * the `x` and `y` axis. Right now only the `x-axis` has more than one option.
  315. * You may specify the default mode of `target target` or
  316. * `target-right target` to specify a right-oriented alignment target. See the
  317. * position section of the demos for more examples.
  318. *
  319. * ### Menu Offsets
  320. *
  321. * It is sometimes unavoidable to need to have a deeper level of control for
  322. * the positioning of a menu to ensure perfect alignment. `md-menu` provides
  323. * the `md-offset` attribute to allow pixel level specificty of adjusting the
  324. * exact positioning.
  325. *
  326. * This offset is provided in the format of `x y` or `n` where `n` will be used
  327. * in both the `x` and `y` axis.
  328. *
  329. * For example, to move a menu by `2px` down from the top, we can use:
  330. * <hljs lang="html">
  331. * <md-menu md-offset="0 2">
  332. * <!-- menu-content -->
  333. * </md-menu>
  334. * </hljs>
  335. *
  336. * ### Auto Focus
  337. * By default, when a menu opens, `md-menu` focuses the first button in the menu content.
  338. *
  339. * But sometimes you would like to focus another specific menu item instead of the first.<br/>
  340. * This can be done by applying the `md-autofocus` directive on the given element.
  341. *
  342. * <hljs lang="html">
  343. * <md-menu-item>
  344. * <md-button md-autofocus ng-click="doSomething()">
  345. * Auto Focus
  346. * </md-button>
  347. * </md-menu-item>
  348. * </hljs>
  349. *
  350. *
  351. * ### Preventing close
  352. *
  353. * Sometimes you would like to be able to click on a menu item without having the menu
  354. * close. To do this, ngMaterial exposes the `md-prevent-menu-close` attribute which
  355. * can be added to a button inside a menu to stop the menu from automatically closing.
  356. * You can then close the menu either by using `$mdMenu.close()` in the template,
  357. * or programatically by injecting `$mdMenu` and calling `$mdMenu.hide()`.
  358. *
  359. * <hljs lang="html">
  360. * <md-menu-content ng-mouseleave="$mdMenu.close()">
  361. * <md-menu-item>
  362. * <md-button ng-click="doSomething()" aria-label="Do something" md-prevent-menu-close="md-prevent-menu-close">
  363. * <md-icon md-menu-align-target md-svg-icon="call:phone"></md-icon>
  364. * Do Something
  365. * </md-button>
  366. * </md-menu-item>
  367. * </md-menu-content>
  368. * </hljs>
  369. *
  370. * @usage
  371. * <hljs lang="html">
  372. * <md-menu>
  373. * <md-button ng-click="$mdMenu.open($event)" class="md-icon-button">
  374. * <md-icon md-svg-icon="call:phone"></md-icon>
  375. * </md-button>
  376. * <md-menu-content>
  377. * <md-menu-item><md-button ng-click="doSomething()">Do Something</md-button></md-menu-item>
  378. * </md-menu-content>
  379. * </md-menu>
  380. * </hljs>
  381. *
  382. * @param {string} md-position-mode The position mode in the form of
  383. * `x`, `y`. Default value is `target`,`target`. Right now the `x` axis
  384. * also supports `target-right`.
  385. * @param {string} md-offset An offset to apply to the dropdown after positioning
  386. * `x`, `y`. Default value is `0`,`0`.
  387. *
  388. */
  389. MenuDirective['$inject'] = ["$mdUtil"];
  390. angular
  391. .module('material.components.menu')
  392. .directive('mdMenu', MenuDirective);
  393. /**
  394. * ngInject
  395. */
  396. function MenuDirective($mdUtil) {
  397. var INVALID_PREFIX = 'Invalid HTML for md-menu: ';
  398. return {
  399. restrict: 'E',
  400. require: ['mdMenu', '?^mdMenuBar'],
  401. controller: 'mdMenuCtrl', // empty function to be built by link
  402. scope: true,
  403. compile: compile
  404. };
  405. function compile(templateElement) {
  406. templateElement.addClass('md-menu');
  407. var triggerEl = templateElement.children()[0];
  408. var contentEl = templateElement.children()[1];
  409. var prefixer = $mdUtil.prefixer();
  410. if (!prefixer.hasAttribute(triggerEl, 'ng-click')) {
  411. triggerEl = triggerEl
  412. .querySelector(prefixer.buildSelector(['ng-click', 'ng-mouseenter'])) || triggerEl;
  413. }
  414. var isButtonTrigger = triggerEl.nodeName === 'MD-BUTTON' || triggerEl.nodeName === 'BUTTON';
  415. if (triggerEl && isButtonTrigger && !triggerEl.hasAttribute('type')) {
  416. triggerEl.setAttribute('type', 'button');
  417. }
  418. if (!triggerEl) {
  419. throw Error(INVALID_PREFIX + 'Expected the menu to have a trigger element.');
  420. }
  421. if (!contentEl || contentEl.nodeName !== 'MD-MENU-CONTENT') {
  422. throw Error(INVALID_PREFIX + 'Expected the menu to contain a `md-menu-content` element.');
  423. }
  424. // Default element for ARIA attributes has the ngClick or ngMouseenter expression
  425. triggerEl && triggerEl.setAttribute('aria-haspopup', 'true');
  426. var nestedMenus = templateElement[0].querySelectorAll('md-menu');
  427. var nestingDepth = parseInt(templateElement[0].getAttribute('md-nest-level'), 10) || 0;
  428. if (nestedMenus) {
  429. angular.forEach($mdUtil.nodesToArray(nestedMenus), function(menuEl) {
  430. if (!menuEl.hasAttribute('md-position-mode')) {
  431. menuEl.setAttribute('md-position-mode', 'cascade');
  432. }
  433. menuEl.classList.add('_md-nested-menu');
  434. menuEl.setAttribute('md-nest-level', nestingDepth + 1);
  435. });
  436. }
  437. return link;
  438. }
  439. function link(scope, element, attr, ctrls) {
  440. var mdMenuCtrl = ctrls[0];
  441. var isInMenuBar = !!ctrls[1];
  442. // Move everything into a md-menu-container and pass it to the controller
  443. var menuContainer = angular.element( '<div class="_md md-open-menu-container md-whiteframe-z2"></div>');
  444. var menuContents = element.children()[1];
  445. element.addClass('_md'); // private md component indicator for styling
  446. if (!menuContents.hasAttribute('role')) {
  447. menuContents.setAttribute('role', 'menu');
  448. }
  449. menuContainer.append(menuContents);
  450. element.on('$destroy', function() {
  451. menuContainer.remove();
  452. });
  453. element.append(menuContainer);
  454. menuContainer[0].style.display = 'none';
  455. mdMenuCtrl.init(menuContainer, { isInMenuBar: isInMenuBar });
  456. }
  457. }
  458. MenuProvider['$inject'] = ["$$interimElementProvider"];angular
  459. .module('material.components.menu')
  460. .provider('$mdMenu', MenuProvider);
  461. /*
  462. * Interim element provider for the menu.
  463. * Handles behavior for a menu while it is open, including:
  464. * - handling animating the menu opening/closing
  465. * - handling key/mouse events on the menu element
  466. * - handling enabling/disabling scroll while the menu is open
  467. * - handling redrawing during resizes and orientation changes
  468. *
  469. */
  470. function MenuProvider($$interimElementProvider) {
  471. menuDefaultOptions['$inject'] = ["$mdUtil", "$mdTheming", "$mdConstant", "$document", "$window", "$q", "$$rAF", "$animateCss", "$animate", "$log"];
  472. var MENU_EDGE_MARGIN = 8;
  473. return $$interimElementProvider('$mdMenu')
  474. .setDefaults({
  475. methods: ['target'],
  476. options: menuDefaultOptions
  477. });
  478. /* ngInject */
  479. function menuDefaultOptions($mdUtil, $mdTheming, $mdConstant, $document, $window, $q, $$rAF,
  480. $animateCss, $animate, $log) {
  481. var prefixer = $mdUtil.prefixer();
  482. var animator = $mdUtil.dom.animator;
  483. return {
  484. parent: 'body',
  485. onShow: onShow,
  486. onRemove: onRemove,
  487. hasBackdrop: true,
  488. disableParentScroll: true,
  489. skipCompile: true,
  490. preserveScope: true,
  491. multiple: true,
  492. themable: true
  493. };
  494. /**
  495. * Show modal backdrop element...
  496. * @returns {function(): void} A function that removes this backdrop
  497. */
  498. function showBackdrop(scope, element, options) {
  499. if (options.nestLevel) return angular.noop;
  500. // If we are not within a dialog...
  501. if (options.disableParentScroll && !$mdUtil.getClosest(options.target, 'MD-DIALOG')) {
  502. // !! DO this before creating the backdrop; since disableScrollAround()
  503. // configures the scroll offset; which is used by mdBackDrop postLink()
  504. options.restoreScroll = $mdUtil.disableScrollAround(options.element, options.parent);
  505. } else {
  506. options.disableParentScroll = false;
  507. }
  508. if (options.hasBackdrop) {
  509. options.backdrop = $mdUtil.createBackdrop(scope, "md-menu-backdrop md-click-catcher");
  510. $animate.enter(options.backdrop, $document[0].body);
  511. }
  512. /**
  513. * Hide and destroys the backdrop created by showBackdrop()
  514. */
  515. return function hideBackdrop() {
  516. if (options.backdrop) options.backdrop.remove();
  517. if (options.disableParentScroll) options.restoreScroll();
  518. };
  519. }
  520. /**
  521. * Removing the menu element from the DOM and remove all associated event listeners
  522. * and backdrop
  523. */
  524. function onRemove(scope, element, opts) {
  525. opts.cleanupInteraction();
  526. opts.cleanupBackdrop();
  527. opts.cleanupResizing();
  528. opts.hideBackdrop();
  529. // Before the menu is closing remove the clickable class.
  530. element.removeClass('md-clickable');
  531. // For navigation $destroy events, do a quick, non-animated removal,
  532. // but for normal closes (from clicks, etc) animate the removal
  533. return (opts.$destroy === true) ? detachAndClean() : animateRemoval().then( detachAndClean );
  534. /**
  535. * For normal closes, animate the removal.
  536. * For forced closes (like $destroy events), skip the animations
  537. */
  538. function animateRemoval() {
  539. return $animateCss(element, {addClass: 'md-leave'}).start();
  540. }
  541. /**
  542. * Detach the element
  543. */
  544. function detachAndClean() {
  545. element.removeClass('md-active');
  546. detachElement(element, opts);
  547. opts.alreadyOpen = false;
  548. }
  549. }
  550. /**
  551. * Inserts and configures the staged Menu element into the DOM, positioning it,
  552. * and wiring up various interaction events
  553. */
  554. function onShow(scope, element, opts) {
  555. sanitizeAndConfigure(opts);
  556. if (opts.menuContentEl[0]) {
  557. // Inherit the theme from the target element.
  558. $mdTheming.inherit(opts.menuContentEl, opts.target);
  559. } else {
  560. $log.warn(
  561. '$mdMenu: Menu elements should always contain a `md-menu-content` element,' +
  562. 'otherwise interactivity features will not work properly.',
  563. element
  564. );
  565. }
  566. // Register various listeners to move menu on resize/orientation change
  567. opts.cleanupResizing = startRepositioningOnResize();
  568. opts.hideBackdrop = showBackdrop(scope, element, opts);
  569. // Return the promise for when our menu is done animating in
  570. return showMenu()
  571. .then(function(response) {
  572. opts.alreadyOpen = true;
  573. opts.cleanupInteraction = activateInteraction();
  574. opts.cleanupBackdrop = setupBackdrop();
  575. // Since the menu finished its animation, mark the menu as clickable.
  576. element.addClass('md-clickable');
  577. return response;
  578. });
  579. /**
  580. * Place the menu into the DOM and call positioning related functions
  581. */
  582. function showMenu() {
  583. opts.parent.append(element);
  584. element[0].style.display = '';
  585. return $q(function(resolve) {
  586. var position = calculateMenuPosition(element, opts);
  587. element.removeClass('md-leave');
  588. // Animate the menu scaling, and opacity [from its position origin (default == top-left)]
  589. // to normal scale.
  590. $animateCss(element, {
  591. addClass: 'md-active',
  592. from: animator.toCss(position),
  593. to: animator.toCss({transform: ''})
  594. })
  595. .start()
  596. .then(resolve);
  597. });
  598. }
  599. /**
  600. * Check for valid opts and set some sane defaults
  601. */
  602. function sanitizeAndConfigure() {
  603. if (!opts.target) {
  604. throw Error(
  605. '$mdMenu.show() expected a target to animate from in options.target'
  606. );
  607. }
  608. angular.extend(opts, {
  609. alreadyOpen: false,
  610. isRemoved: false,
  611. target: angular.element(opts.target), //make sure it's not a naked dom node
  612. parent: angular.element(opts.parent),
  613. menuContentEl: angular.element(element[0].querySelector('md-menu-content'))
  614. });
  615. }
  616. /**
  617. * Configure various resize listeners for screen changes
  618. */
  619. function startRepositioningOnResize() {
  620. var repositionMenu = (function(target, options) {
  621. return $$rAF.throttle(function() {
  622. if (opts.isRemoved) return;
  623. var position = calculateMenuPosition(target, options);
  624. target.css(animator.toCss(position));
  625. });
  626. })(element, opts);
  627. $window.addEventListener('resize', repositionMenu);
  628. $window.addEventListener('orientationchange', repositionMenu);
  629. return function stopRepositioningOnResize() {
  630. // Disable resizing handlers
  631. $window.removeEventListener('resize', repositionMenu);
  632. $window.removeEventListener('orientationchange', repositionMenu);
  633. };
  634. }
  635. /**
  636. * Sets up the backdrop and listens for click elements.
  637. * Once the backdrop will be clicked, the menu will automatically close.
  638. * @returns {!Function} Function to remove the backdrop.
  639. */
  640. function setupBackdrop() {
  641. if (!opts.backdrop) return angular.noop;
  642. opts.backdrop.on('click', onBackdropClick);
  643. return function() {
  644. opts.backdrop.off('click', onBackdropClick);
  645. }
  646. }
  647. /**
  648. * Function to be called whenever the backdrop is clicked.
  649. * @param {!MouseEvent} event
  650. */
  651. function onBackdropClick(event) {
  652. event.preventDefault();
  653. event.stopPropagation();
  654. scope.$apply(function() {
  655. opts.mdMenuCtrl.close(true, { closeAll: true });
  656. });
  657. }
  658. /**
  659. * Activate interaction on the menu. Resolves the focus target and closes the menu on
  660. * escape or option click.
  661. * @returns {!Function} Function to deactivate the interaction listeners.
  662. */
  663. function activateInteraction() {
  664. if (!opts.menuContentEl[0]) return angular.noop;
  665. // Wire up keyboard listeners.
  666. // - Close on escape,
  667. // - focus next item on down arrow,
  668. // - focus prev item on up
  669. opts.menuContentEl.on('keydown', onMenuKeyDown);
  670. opts.menuContentEl[0].addEventListener('click', captureClickListener, true);
  671. // kick off initial focus in the menu on the first enabled element
  672. var focusTarget = opts.menuContentEl[0]
  673. .querySelector(prefixer.buildSelector(['md-menu-focus-target', 'md-autofocus']));
  674. if ( !focusTarget ) {
  675. var childrenLen = opts.menuContentEl[0].children.length;
  676. for(var childIndex = 0; childIndex < childrenLen; childIndex++) {
  677. var child = opts.menuContentEl[0].children[childIndex];
  678. focusTarget = child.querySelector('.md-button:not([disabled])');
  679. if (focusTarget) {
  680. break;
  681. }
  682. if (child.firstElementChild && !child.firstElementChild.disabled) {
  683. focusTarget = child.firstElementChild;
  684. break;
  685. }
  686. }
  687. }
  688. focusTarget && focusTarget.focus();
  689. return function cleanupInteraction() {
  690. opts.menuContentEl.off('keydown', onMenuKeyDown);
  691. opts.menuContentEl[0].removeEventListener('click', captureClickListener, true);
  692. };
  693. // ************************************
  694. // internal functions
  695. // ************************************
  696. function onMenuKeyDown(ev) {
  697. var handled;
  698. switch (ev.keyCode) {
  699. case $mdConstant.KEY_CODE.ESCAPE:
  700. opts.mdMenuCtrl.close(false, { closeAll: true });
  701. handled = true;
  702. break;
  703. case $mdConstant.KEY_CODE.UP_ARROW:
  704. if (!focusMenuItem(ev, opts.menuContentEl, opts, -1) && !opts.nestLevel) {
  705. opts.mdMenuCtrl.triggerContainerProxy(ev);
  706. }
  707. handled = true;
  708. break;
  709. case $mdConstant.KEY_CODE.DOWN_ARROW:
  710. if (!focusMenuItem(ev, opts.menuContentEl, opts, 1) && !opts.nestLevel) {
  711. opts.mdMenuCtrl.triggerContainerProxy(ev);
  712. }
  713. handled = true;
  714. break;
  715. case $mdConstant.KEY_CODE.LEFT_ARROW:
  716. if (opts.nestLevel) {
  717. opts.mdMenuCtrl.close();
  718. } else {
  719. opts.mdMenuCtrl.triggerContainerProxy(ev);
  720. }
  721. handled = true;
  722. break;
  723. case $mdConstant.KEY_CODE.RIGHT_ARROW:
  724. var parentMenu = $mdUtil.getClosest(ev.target, 'MD-MENU');
  725. if (parentMenu && parentMenu != opts.parent[0]) {
  726. ev.target.click();
  727. } else {
  728. opts.mdMenuCtrl.triggerContainerProxy(ev);
  729. }
  730. handled = true;
  731. break;
  732. }
  733. if (handled) {
  734. ev.preventDefault();
  735. ev.stopImmediatePropagation();
  736. }
  737. }
  738. function onBackdropClick(e) {
  739. e.preventDefault();
  740. e.stopPropagation();
  741. scope.$apply(function() {
  742. opts.mdMenuCtrl.close(true, { closeAll: true });
  743. });
  744. }
  745. // Close menu on menu item click, if said menu-item is not disabled
  746. function captureClickListener(e) {
  747. var target = e.target;
  748. // Traverse up the event until we get to the menuContentEl to see if
  749. // there is an ng-click and that the ng-click is not disabled
  750. do {
  751. if (target == opts.menuContentEl[0]) return;
  752. if ((hasAnyAttribute(target, ['ng-click', 'ng-href', 'ui-sref']) ||
  753. target.nodeName == 'BUTTON' || target.nodeName == 'MD-BUTTON') && !hasAnyAttribute(target, ['md-prevent-menu-close'])) {
  754. var closestMenu = $mdUtil.getClosest(target, 'MD-MENU');
  755. if (!target.hasAttribute('disabled') && (!closestMenu || closestMenu == opts.parent[0])) {
  756. close();
  757. }
  758. break;
  759. }
  760. } while (target = target.parentNode);
  761. function close() {
  762. scope.$apply(function() {
  763. opts.mdMenuCtrl.close(true, { closeAll: true });
  764. });
  765. }
  766. function hasAnyAttribute(target, attrs) {
  767. if (!target) return false;
  768. for (var i = 0, attr; attr = attrs[i]; ++i) {
  769. if (prefixer.hasAttribute(target, attr)) {
  770. return true;
  771. }
  772. }
  773. return false;
  774. }
  775. }
  776. }
  777. }
  778. /**
  779. * Takes a keypress event and focuses the next/previous menu
  780. * item from the emitting element
  781. * @param {event} e - The origin keypress event
  782. * @param {angular.element} menuEl - The menu element
  783. * @param {object} opts - The interim element options for the mdMenu
  784. * @param {number} direction - The direction to move in (+1 = next, -1 = prev)
  785. */
  786. function focusMenuItem(e, menuEl, opts, direction) {
  787. var currentItem = $mdUtil.getClosest(e.target, 'MD-MENU-ITEM');
  788. var items = $mdUtil.nodesToArray(menuEl[0].children);
  789. var currentIndex = items.indexOf(currentItem);
  790. // Traverse through our elements in the specified direction (+/-1) and try to
  791. // focus them until we find one that accepts focus
  792. var didFocus;
  793. for (var i = currentIndex + direction; i >= 0 && i < items.length; i = i + direction) {
  794. var focusTarget = items[i].querySelector('.md-button');
  795. didFocus = attemptFocus(focusTarget);
  796. if (didFocus) {
  797. break;
  798. }
  799. }
  800. return didFocus;
  801. }
  802. /**
  803. * Attempts to focus an element. Checks whether that element is the currently
  804. * focused element after attempting.
  805. * @param {HTMLElement} el - the element to attempt focus on
  806. * @returns {bool} - whether the element was successfully focused
  807. */
  808. function attemptFocus(el) {
  809. if (el && el.getAttribute('tabindex') != -1) {
  810. el.focus();
  811. return ($document[0].activeElement == el);
  812. }
  813. }
  814. /**
  815. * Use browser to remove this element without triggering a $destroy event
  816. */
  817. function detachElement(element, opts) {
  818. if (!opts.preserveElement) {
  819. if (toNode(element).parentNode === toNode(opts.parent)) {
  820. toNode(opts.parent).removeChild(toNode(element));
  821. }
  822. } else {
  823. toNode(element).style.display = 'none';
  824. }
  825. }
  826. /**
  827. * Computes menu position and sets the style on the menu container
  828. * @param {HTMLElement} el - the menu container element
  829. * @param {object} opts - the interim element options object
  830. */
  831. function calculateMenuPosition(el, opts) {
  832. var containerNode = el[0],
  833. openMenuNode = el[0].firstElementChild,
  834. openMenuNodeRect = openMenuNode.getBoundingClientRect(),
  835. boundryNode = $document[0].body,
  836. boundryNodeRect = boundryNode.getBoundingClientRect();
  837. var menuStyle = $window.getComputedStyle(openMenuNode);
  838. var originNode = opts.target[0].querySelector(prefixer.buildSelector('md-menu-origin')) || opts.target[0],
  839. originNodeRect = originNode.getBoundingClientRect();
  840. var bounds = {
  841. left: boundryNodeRect.left + MENU_EDGE_MARGIN,
  842. top: Math.max(boundryNodeRect.top, 0) + MENU_EDGE_MARGIN,
  843. bottom: Math.max(boundryNodeRect.bottom, Math.max(boundryNodeRect.top, 0) + boundryNodeRect.height) - MENU_EDGE_MARGIN,
  844. right: boundryNodeRect.right - MENU_EDGE_MARGIN
  845. };
  846. var alignTarget, alignTargetRect = { top:0, left : 0, right:0, bottom:0 }, existingOffsets = { top:0, left : 0, right:0, bottom:0 };
  847. var positionMode = opts.mdMenuCtrl.positionMode();
  848. if (positionMode.top == 'target' || positionMode.left == 'target' || positionMode.left == 'target-right') {
  849. alignTarget = firstVisibleChild();
  850. if ( alignTarget ) {
  851. // TODO: Allow centering on an arbitrary node, for now center on first menu-item's child
  852. alignTarget = alignTarget.firstElementChild || alignTarget;
  853. alignTarget = alignTarget.querySelector(prefixer.buildSelector('md-menu-align-target')) || alignTarget;
  854. alignTargetRect = alignTarget.getBoundingClientRect();
  855. existingOffsets = {
  856. top: parseFloat(containerNode.style.top || 0),
  857. left: parseFloat(containerNode.style.left || 0)
  858. };
  859. }
  860. }
  861. var position = {};
  862. var transformOrigin = 'top ';
  863. switch (positionMode.top) {
  864. case 'target':
  865. position.top = existingOffsets.top + originNodeRect.top - alignTargetRect.top;
  866. break;
  867. case 'cascade':
  868. position.top = originNodeRect.top - parseFloat(menuStyle.paddingTop) - originNode.style.top;
  869. break;
  870. case 'bottom':
  871. position.top = originNodeRect.top + originNodeRect.height;
  872. break;
  873. default:
  874. throw new Error('Invalid target mode "' + positionMode.top + '" specified for md-menu on Y axis.');
  875. }
  876. var rtl = ($mdUtil.bidi() == 'rtl');
  877. switch (positionMode.left) {
  878. case 'target':
  879. position.left = existingOffsets.left + originNodeRect.left - alignTargetRect.left;
  880. transformOrigin += rtl ? 'right' : 'left';
  881. break;
  882. case 'target-left':
  883. position.left = originNodeRect.left;
  884. transformOrigin += 'left';
  885. break;
  886. case 'target-right':
  887. position.left = originNodeRect.right - openMenuNodeRect.width + (openMenuNodeRect.right - alignTargetRect.right);
  888. transformOrigin += 'right';
  889. break;
  890. case 'cascade':
  891. var willFitRight = rtl ? (originNodeRect.left - openMenuNodeRect.width) < bounds.left : (originNodeRect.right + openMenuNodeRect.width) < bounds.right;
  892. position.left = willFitRight ? originNodeRect.right - originNode.style.left : originNodeRect.left - originNode.style.left - openMenuNodeRect.width;
  893. transformOrigin += willFitRight ? 'left' : 'right';
  894. break;
  895. case 'right':
  896. if (rtl) {
  897. position.left = originNodeRect.right - originNodeRect.width;
  898. transformOrigin += 'left';
  899. } else {
  900. position.left = originNodeRect.right - openMenuNodeRect.width;
  901. transformOrigin += 'right';
  902. }
  903. break;
  904. case 'left':
  905. if (rtl) {
  906. position.left = originNodeRect.right - openMenuNodeRect.width;
  907. transformOrigin += 'right';
  908. } else {
  909. position.left = originNodeRect.left;
  910. transformOrigin += 'left';
  911. }
  912. break;
  913. default:
  914. throw new Error('Invalid target mode "' + positionMode.left + '" specified for md-menu on X axis.');
  915. }
  916. var offsets = opts.mdMenuCtrl.offsets();
  917. position.top += offsets.top;
  918. position.left += offsets.left;
  919. clamp(position);
  920. var scaleX = Math.round(100 * Math.min(originNodeRect.width / containerNode.offsetWidth, 1.0)) / 100;
  921. var scaleY = Math.round(100 * Math.min(originNodeRect.height / containerNode.offsetHeight, 1.0)) / 100;
  922. return {
  923. top: Math.round(position.top),
  924. left: Math.round(position.left),
  925. // Animate a scale out if we aren't just repositioning
  926. transform: !opts.alreadyOpen ? $mdUtil.supplant('scale({0},{1})', [scaleX, scaleY]) : undefined,
  927. transformOrigin: transformOrigin
  928. };
  929. /**
  930. * Clamps the repositioning of the menu within the confines of
  931. * bounding element (often the screen/body)
  932. */
  933. function clamp(pos) {
  934. pos.top = Math.max(Math.min(pos.top, bounds.bottom - containerNode.offsetHeight), bounds.top);
  935. pos.left = Math.max(Math.min(pos.left, bounds.right - containerNode.offsetWidth), bounds.left);
  936. }
  937. /**
  938. * Gets the first visible child in the openMenuNode
  939. * Necessary incase menu nodes are being dynamically hidden
  940. */
  941. function firstVisibleChild() {
  942. for (var i = 0; i < openMenuNode.children.length; ++i) {
  943. if ($window.getComputedStyle(openMenuNode.children[i]).display != 'none') {
  944. return openMenuNode.children[i];
  945. }
  946. }
  947. }
  948. }
  949. }
  950. function toNode(el) {
  951. if (el instanceof angular.element) {
  952. el = el[0];
  953. }
  954. return el;
  955. }
  956. }
  957. ngmaterial.components.menu = angular.module("material.components.menu");