menu.js 38 KB

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