fabSpeedDial.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  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. (function() {
  10. 'use strict';
  11. angular.module('material.components.fabShared', ['material.core'])
  12. .controller('FabController', FabController);
  13. function FabController($scope, $element, $animate, $mdUtil, $mdConstant) {
  14. var vm = this;
  15. // NOTE: We use async evals below to avoid conflicts with any existing digest loops
  16. vm.open = function() {
  17. $scope.$evalAsync("vm.isOpen = true");
  18. };
  19. vm.close = function() {
  20. // Async eval to avoid conflicts with existing digest loops
  21. $scope.$evalAsync("vm.isOpen = false");
  22. // Focus the trigger when the element closes so users can still tab to the next item
  23. $element.find('md-fab-trigger')[0].focus();
  24. };
  25. // Toggle the open/close state when the trigger is clicked
  26. vm.toggle = function() {
  27. $scope.$evalAsync("vm.isOpen = !vm.isOpen");
  28. };
  29. setupDefaults();
  30. setupListeners();
  31. setupWatchers();
  32. fireInitialAnimations();
  33. function setupDefaults() {
  34. // Set the default direction to 'down' if none is specified
  35. vm.direction = vm.direction || 'down';
  36. // Set the default to be closed
  37. vm.isOpen = vm.isOpen || false;
  38. // Start the keyboard interaction at the first action
  39. resetActionIndex();
  40. }
  41. var events = [];
  42. function setupListeners() {
  43. var eventTypes = [
  44. 'mousedown', 'mouseup', 'click', 'touchstart', 'touchend', 'focusin', 'focusout'
  45. ];
  46. // Add our listeners
  47. angular.forEach(eventTypes, function(eventType) {
  48. $element.on(eventType, parseEvents);
  49. });
  50. // Remove our listeners when destroyed
  51. $scope.$on('$destroy', function() {
  52. angular.forEach(eventTypes, function(eventType) {
  53. $element.off(eventType, parseEvents);
  54. });
  55. // remove any attached keyboard handlers in case element is removed while
  56. // speed dial is open
  57. disableKeyboard();
  58. });
  59. }
  60. function resetEvents() {
  61. events = [];
  62. }
  63. function equalsEvents(toCheck) {
  64. var isEqual, strippedCheck, moreToCheck;
  65. // Quick check to make sure we don't get stuck in an infinite loop
  66. var numTests = 0;
  67. do {
  68. // Strip out the question mark
  69. strippedCheck = toCheck.map(function(event) {
  70. return event.replace('?', '')
  71. });
  72. // Check if they are equal
  73. isEqual = angular.equals(events, strippedCheck);
  74. // If not, check to see if removing an optional event makes them equal
  75. if (!isEqual) {
  76. toCheck = removeOptionalEvent(toCheck);
  77. moreToCheck = (toCheck.length >= events.length && toCheck.length !== strippedCheck.length);
  78. }
  79. }
  80. while (numTests < 10 && !isEqual && moreToCheck);
  81. return isEqual;
  82. }
  83. function removeOptionalEvent(events) {
  84. var foundOptional = false;
  85. return events.filter(function(event) {
  86. // If we have not found an optional one, keep searching
  87. if (!foundOptional && event.indexOf('?') !== -1) {
  88. foundOptional = true;
  89. // If we find an optional one, remove only that one and keep going
  90. return false;
  91. }
  92. return true;
  93. });
  94. }
  95. function parseEvents(latestEvent) {
  96. events.push(latestEvent.type);
  97. // Handle desktop click
  98. if (equalsEvents(['mousedown', 'focusout?', 'focusin?', 'mouseup', 'click'])) {
  99. handleItemClick(latestEvent);
  100. resetEvents();
  101. return;
  102. }
  103. // Handle mobile click/tap (and keyboard enter)
  104. if (equalsEvents(['touchstart?', 'touchend?', 'click'])) {
  105. handleItemClick(latestEvent);
  106. resetEvents();
  107. return;
  108. }
  109. // Handle tab keys (focusin)
  110. if (equalsEvents(['focusin'])) {
  111. vm.open();
  112. resetEvents();
  113. return;
  114. }
  115. // Handle tab keys (focusout)
  116. if (equalsEvents(['focusout'])) {
  117. vm.close();
  118. resetEvents();
  119. return;
  120. }
  121. eventUnhandled();
  122. }
  123. /*
  124. * No event was handled, so setup a timeout to clear the events
  125. *
  126. * TODO: Use $mdUtil.debounce()?
  127. */
  128. var resetEventsTimeout;
  129. function eventUnhandled() {
  130. if (resetEventsTimeout) {
  131. window.clearTimeout(resetEventsTimeout);
  132. }
  133. resetEventsTimeout = window.setTimeout(function() {
  134. resetEvents();
  135. }, 250);
  136. }
  137. function resetActionIndex() {
  138. vm.currentActionIndex = -1;
  139. }
  140. function setupWatchers() {
  141. // Watch for changes to the direction and update classes/attributes
  142. $scope.$watch('vm.direction', function(newDir, oldDir) {
  143. // Add the appropriate classes so we can target the direction in the CSS
  144. $animate.removeClass($element, 'md-' + oldDir);
  145. $animate.addClass($element, 'md-' + newDir);
  146. // Reset the action index since it may have changed
  147. resetActionIndex();
  148. });
  149. var trigger, actions;
  150. // Watch for changes to md-open
  151. $scope.$watch('vm.isOpen', function(isOpen) {
  152. // Reset the action index since it may have changed
  153. resetActionIndex();
  154. // We can't get the trigger/actions outside of the watch because the component hasn't been
  155. // linked yet, so we wait until the first watch fires to cache them.
  156. if (!trigger || !actions) {
  157. trigger = getTriggerElement();
  158. actions = getActionsElement();
  159. }
  160. if (isOpen) {
  161. enableKeyboard();
  162. } else {
  163. disableKeyboard();
  164. }
  165. var toAdd = isOpen ? 'md-is-open' : '';
  166. var toRemove = isOpen ? '' : 'md-is-open';
  167. // Set the proper ARIA attributes
  168. trigger.attr('aria-haspopup', true);
  169. trigger.attr('aria-expanded', isOpen);
  170. actions.attr('aria-hidden', !isOpen);
  171. // Animate the CSS classes
  172. $animate.setClass($element, toAdd, toRemove);
  173. });
  174. }
  175. // Fire the animations once in a separate digest loop to initialize them
  176. function fireInitialAnimations() {
  177. $mdUtil.nextTick(function() {
  178. $animate.addClass($element, 'md-noop');
  179. });
  180. }
  181. function enableKeyboard() {
  182. angular.element(document).on('keydown', keyPressed);
  183. }
  184. function disableKeyboard() {
  185. angular.element(document).off('keydown', keyPressed);
  186. }
  187. function keyPressed(event) {
  188. switch (event.which) {
  189. case $mdConstant.KEY_CODE.SPACE: event.preventDefault(); return false;
  190. case $mdConstant.KEY_CODE.ESCAPE: vm.close(); event.preventDefault(); return false;
  191. case $mdConstant.KEY_CODE.LEFT_ARROW: doKeyLeft(event); return false;
  192. case $mdConstant.KEY_CODE.UP_ARROW: doKeyUp(event); return false;
  193. case $mdConstant.KEY_CODE.RIGHT_ARROW: doKeyRight(event); return false;
  194. case $mdConstant.KEY_CODE.DOWN_ARROW: doKeyDown(event); return false;
  195. }
  196. }
  197. function doActionPrev(event) {
  198. focusAction(event, -1);
  199. }
  200. function doActionNext(event) {
  201. focusAction(event, 1);
  202. }
  203. function focusAction(event, direction) {
  204. // Grab all of the actions
  205. var actions = getActionsElement()[0].querySelectorAll('.md-fab-action-item');
  206. // Disable all other actions for tabbing
  207. angular.forEach(actions, function(action) {
  208. angular.element(angular.element(action).children()[0]).attr('tabindex', -1);
  209. });
  210. // Increment/decrement the counter with restrictions
  211. vm.currentActionIndex = vm.currentActionIndex + direction;
  212. vm.currentActionIndex = Math.min(actions.length - 1, vm.currentActionIndex);
  213. vm.currentActionIndex = Math.max(0, vm.currentActionIndex);
  214. // Focus the element
  215. var focusElement = angular.element(actions[vm.currentActionIndex]).children()[0];
  216. angular.element(focusElement).attr('tabindex', 0);
  217. focusElement.focus();
  218. // Make sure the event doesn't bubble and cause something else
  219. event.preventDefault();
  220. event.stopImmediatePropagation();
  221. }
  222. function doKeyLeft(event) {
  223. if (vm.direction === 'left') {
  224. doActionNext(event);
  225. } else {
  226. doActionPrev(event);
  227. }
  228. }
  229. function doKeyUp(event) {
  230. if (vm.direction === 'down') {
  231. doActionPrev(event);
  232. } else {
  233. doActionNext(event);
  234. }
  235. }
  236. function doKeyRight(event) {
  237. if (vm.direction === 'left') {
  238. doActionPrev(event);
  239. } else {
  240. doActionNext(event);
  241. }
  242. }
  243. function doKeyDown(event) {
  244. if (vm.direction === 'up') {
  245. doActionPrev(event);
  246. } else {
  247. doActionNext(event);
  248. }
  249. }
  250. function isTrigger(element) {
  251. return $mdUtil.getClosest(element, 'md-fab-trigger');
  252. }
  253. function isAction(element) {
  254. return $mdUtil.getClosest(element, 'md-fab-actions');
  255. }
  256. function handleItemClick(event) {
  257. if (isTrigger(event.target)) {
  258. vm.toggle();
  259. }
  260. if (isAction(event.target)) {
  261. vm.close();
  262. }
  263. }
  264. function getTriggerElement() {
  265. return $element.find('md-fab-trigger');
  266. }
  267. function getActionsElement() {
  268. return $element.find('md-fab-actions');
  269. }
  270. }
  271. FabController.$inject = ["$scope", "$element", "$animate", "$mdUtil", "$mdConstant"];
  272. })();
  273. (function() {
  274. 'use strict';
  275. /**
  276. * @ngdoc module
  277. * @name material.components.fabSpeedDial
  278. */
  279. angular
  280. // Declare our module
  281. .module('material.components.fabSpeedDial', [
  282. 'material.core',
  283. 'material.components.fabShared',
  284. 'material.components.fabTrigger',
  285. 'material.components.fabActions'
  286. ])
  287. // Register our directive
  288. .directive('mdFabSpeedDial', MdFabSpeedDialDirective)
  289. // Register our custom animations
  290. .animation('.md-fling', MdFabSpeedDialFlingAnimation)
  291. .animation('.md-scale', MdFabSpeedDialScaleAnimation)
  292. // Register a service for each animation so that we can easily inject them into unit tests
  293. .service('mdFabSpeedDialFlingAnimation', MdFabSpeedDialFlingAnimation)
  294. .service('mdFabSpeedDialScaleAnimation', MdFabSpeedDialScaleAnimation);
  295. /**
  296. * @ngdoc directive
  297. * @name mdFabSpeedDial
  298. * @module material.components.fabSpeedDial
  299. *
  300. * @restrict E
  301. *
  302. * @description
  303. * The `<md-fab-speed-dial>` directive is used to present a series of popup elements (usually
  304. * `<md-button>`s) for quick access to common actions.
  305. *
  306. * There are currently two animations available by applying one of the following classes to
  307. * the component:
  308. *
  309. * - `md-fling` - The speed dial items appear from underneath the trigger and move into their
  310. * appropriate positions.
  311. * - `md-scale` - The speed dial items appear in their proper places by scaling from 0% to 100%.
  312. *
  313. * You may also easily position the trigger by applying one one of the following classes to the
  314. * `<md-fab-speed-dial>` element:
  315. * - `md-fab-top-left`
  316. * - `md-fab-top-right`
  317. * - `md-fab-bottom-left`
  318. * - `md-fab-bottom-right`
  319. *
  320. * These CSS classes use `position: absolute`, so you need to ensure that the container element
  321. * also uses `position: absolute` or `position: relative` in order for them to work.
  322. *
  323. * Additionally, you may use the standard `ng-mouseenter` and `ng-mouseleave` directives to
  324. * open or close the speed dial. However, if you wish to allow users to hover over the empty
  325. * space where the actions will appear, you must also add the `md-hover-full` class to the speed
  326. * dial element. Without this, the hover effect will only occur on top of the trigger.
  327. *
  328. * @usage
  329. * <hljs lang="html">
  330. * <md-fab-speed-dial md-direction="up" class="md-fling">
  331. * <md-fab-trigger>
  332. * <md-button aria-label="Add..."><md-icon icon="/img/icons/plus.svg"></md-icon></md-button>
  333. * </md-fab-trigger>
  334. *
  335. * <md-fab-actions>
  336. * <md-button aria-label="Add User">
  337. * <md-icon icon="/img/icons/user.svg"></md-icon>
  338. * </md-button>
  339. *
  340. * <md-button aria-label="Add Group">
  341. * <md-icon icon="/img/icons/group.svg"></md-icon>
  342. * </md-button>
  343. * </md-fab-actions>
  344. * </md-fab-speed-dial>
  345. * </hljs>
  346. *
  347. * @param {string} md-direction From which direction you would like the speed dial to appear
  348. * relative to the trigger element.
  349. * @param {expression=} md-open Programmatically control whether or not the speed-dial is visible.
  350. */
  351. function MdFabSpeedDialDirective() {
  352. return {
  353. restrict: 'E',
  354. scope: {
  355. direction: '@?mdDirection',
  356. isOpen: '=?mdOpen'
  357. },
  358. bindToController: true,
  359. controller: 'FabController',
  360. controllerAs: 'vm',
  361. link: FabSpeedDialLink
  362. };
  363. function FabSpeedDialLink(scope, element) {
  364. // Prepend an element to hold our CSS variables so we can use them in the animations below
  365. element.prepend('<div class="md-css-variables"></div>');
  366. }
  367. }
  368. function MdFabSpeedDialFlingAnimation() {
  369. function runAnimation(element) {
  370. var el = element[0];
  371. var ctrl = element.controller('mdFabSpeedDial');
  372. var items = el.querySelectorAll('.md-fab-action-item');
  373. // Grab our trigger element
  374. var triggerElement = el.querySelector('md-fab-trigger');
  375. // Grab our element which stores CSS variables
  376. var variablesElement = el.querySelector('.md-css-variables');
  377. // Setup JS variables based on our CSS variables
  378. var startZIndex = parseInt(window.getComputedStyle(variablesElement).zIndex);
  379. // Always reset the items to their natural position/state
  380. angular.forEach(items, function(item, index) {
  381. var styles = item.style;
  382. styles.transform = styles.webkitTransform = '';
  383. styles.transitionDelay = '';
  384. styles.opacity = 1;
  385. // Make the items closest to the trigger have the highest z-index
  386. styles.zIndex = (items.length - index) + startZIndex;
  387. });
  388. // Set the trigger to be above all of the actions so they disappear behind it.
  389. triggerElement.style.zIndex = startZIndex + items.length + 1;
  390. // If the control is closed, hide the items behind the trigger
  391. if (!ctrl.isOpen) {
  392. angular.forEach(items, function(item, index) {
  393. var newPosition, axis;
  394. var styles = item.style;
  395. switch (ctrl.direction) {
  396. case 'up':
  397. newPosition = item.scrollHeight * (index + 1);
  398. axis = 'Y';
  399. break;
  400. case 'down':
  401. newPosition = -item.scrollHeight * (index + 1);
  402. axis = 'Y';
  403. break;
  404. case 'left':
  405. newPosition = item.scrollWidth * (index + 1);
  406. axis = 'X';
  407. break;
  408. case 'right':
  409. newPosition = -item.scrollWidth * (index + 1);
  410. axis = 'X';
  411. break;
  412. }
  413. var newTranslate = 'translate' + axis + '(' + newPosition + 'px)';
  414. styles.transform = styles.webkitTransform = newTranslate;
  415. });
  416. }
  417. }
  418. return {
  419. addClass: function(element, className, done) {
  420. if (element.hasClass('md-fling')) {
  421. runAnimation(element);
  422. done();
  423. }
  424. },
  425. removeClass: function(element, className, done) {
  426. runAnimation(element);
  427. done();
  428. }
  429. }
  430. }
  431. function MdFabSpeedDialScaleAnimation() {
  432. var delay = 65;
  433. function runAnimation(element) {
  434. var el = element[0];
  435. var ctrl = element.controller('mdFabSpeedDial');
  436. var items = el.querySelectorAll('.md-fab-action-item');
  437. // Grab our element which stores CSS variables
  438. var variablesElement = el.querySelector('.md-css-variables');
  439. // Setup JS variables based on our CSS variables
  440. var startZIndex = parseInt(window.getComputedStyle(variablesElement).zIndex);
  441. // Always reset the items to their natural position/state
  442. angular.forEach(items, function(item, index) {
  443. var styles = item.style,
  444. offsetDelay = index * delay;
  445. styles.opacity = ctrl.isOpen ? 1 : 0;
  446. styles.transform = styles.webkitTransform = ctrl.isOpen ? 'scale(1)' : 'scale(0)';
  447. styles.transitionDelay = (ctrl.isOpen ? offsetDelay : (items.length - offsetDelay)) + 'ms';
  448. // Make the items closest to the trigger have the highest z-index
  449. styles.zIndex = (items.length - index) + startZIndex;
  450. });
  451. }
  452. return {
  453. addClass: function(element, className, done) {
  454. runAnimation(element);
  455. done();
  456. },
  457. removeClass: function(element, className, done) {
  458. runAnimation(element);
  459. done();
  460. }
  461. }
  462. }
  463. })();
  464. })(window, window.angular);