menu.js 32 KB

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