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.

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