foundation.drilldown.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642
  1. 'use strict';
  2. import $ from 'jquery';
  3. import { Keyboard } from './foundation.util.keyboard';
  4. import { Nest } from './foundation.util.nest';
  5. import { GetYoDigits, transitionend } from './foundation.core.utils';
  6. import { Box } from './foundation.util.box';
  7. import { Plugin } from './foundation.core.plugin';
  8. /**
  9. * Drilldown module.
  10. * @module foundation.drilldown
  11. * @requires foundation.util.keyboard
  12. * @requires foundation.util.nest
  13. * @requires foundation.util.box
  14. */
  15. class Drilldown extends Plugin {
  16. /**
  17. * Creates a new instance of a drilldown menu.
  18. * @class
  19. * @name Drilldown
  20. * @param {jQuery} element - jQuery object to make into an accordion menu.
  21. * @param {Object} options - Overrides to the default plugin settings.
  22. */
  23. _setup(element, options) {
  24. this.$element = element;
  25. this.options = $.extend({}, Drilldown.defaults, this.$element.data(), options);
  26. this.className = 'Drilldown'; // ie9 back compat
  27. this._init();
  28. Keyboard.register('Drilldown', {
  29. 'ENTER': 'open',
  30. 'SPACE': 'open',
  31. 'ARROW_RIGHT': 'next',
  32. 'ARROW_UP': 'up',
  33. 'ARROW_DOWN': 'down',
  34. 'ARROW_LEFT': 'previous',
  35. 'ESCAPE': 'close',
  36. 'TAB': 'down',
  37. 'SHIFT_TAB': 'up'
  38. });
  39. }
  40. /**
  41. * Initializes the drilldown by creating jQuery collections of elements
  42. * @private
  43. */
  44. _init() {
  45. Nest.Feather(this.$element, 'drilldown');
  46. if(this.options.autoApplyClass) {
  47. this.$element.addClass('drilldown');
  48. }
  49. this.$element.attr({
  50. 'role': 'tree',
  51. 'aria-multiselectable': false
  52. });
  53. this.$submenuAnchors = this.$element.find('li.is-drilldown-submenu-parent').children('a');
  54. this.$submenus = this.$submenuAnchors.parent('li').children('[data-submenu]').attr('role', 'group');
  55. this.$menuItems = this.$element.find('li').not('.js-drilldown-back').attr('role', 'treeitem').find('a');
  56. // Set the main menu as current by default (unless a submenu is selected)
  57. // Used to set the wrapper height when the drilldown is closed/reopened from any (sub)menu
  58. this.$currentMenu = this.$element;
  59. this.$element.attr('data-mutate', (this.$element.attr('data-drilldown') || GetYoDigits(6, 'drilldown')));
  60. this._prepareMenu();
  61. this._registerEvents();
  62. this._keyboardEvents();
  63. }
  64. /**
  65. * prepares drilldown menu by setting attributes to links and elements
  66. * sets a min height to prevent content jumping
  67. * wraps the element if not already wrapped
  68. * @private
  69. * @function
  70. */
  71. _prepareMenu() {
  72. var _this = this;
  73. // if(!this.options.holdOpen){
  74. // this._menuLinkEvents();
  75. // }
  76. this.$submenuAnchors.each(function(){
  77. var $link = $(this);
  78. var $sub = $link.parent();
  79. if(_this.options.parentLink){
  80. $link.clone().prependTo($sub.children('[data-submenu]')).wrap('<li data-is-parent-link class="is-submenu-parent-item is-submenu-item is-drilldown-submenu-item" role="menuitem"></li>');
  81. }
  82. $link.data('savedHref', $link.attr('href')).removeAttr('href').attr('tabindex', 0);
  83. $link.children('[data-submenu]')
  84. .attr({
  85. 'aria-hidden': true,
  86. 'tabindex': 0,
  87. 'role': 'group'
  88. });
  89. _this._events($link);
  90. });
  91. this.$submenus.each(function(){
  92. var $menu = $(this),
  93. $back = $menu.find('.js-drilldown-back');
  94. if(!$back.length){
  95. switch (_this.options.backButtonPosition) {
  96. case "bottom":
  97. $menu.append(_this.options.backButton);
  98. break;
  99. case "top":
  100. $menu.prepend(_this.options.backButton);
  101. break;
  102. default:
  103. console.error("Unsupported backButtonPosition value '" + _this.options.backButtonPosition + "'");
  104. }
  105. }
  106. _this._back($menu);
  107. });
  108. this.$submenus.addClass('invisible');
  109. if(!this.options.autoHeight) {
  110. this.$submenus.addClass('drilldown-submenu-cover-previous');
  111. }
  112. // create a wrapper on element if it doesn't exist.
  113. if(!this.$element.parent().hasClass('is-drilldown')){
  114. this.$wrapper = $(this.options.wrapper).addClass('is-drilldown');
  115. if(this.options.animateHeight) this.$wrapper.addClass('animate-height');
  116. this.$element.wrap(this.$wrapper);
  117. }
  118. // set wrapper
  119. this.$wrapper = this.$element.parent();
  120. this.$wrapper.css(this._getMaxDims());
  121. }
  122. _resize() {
  123. this.$wrapper.css({'max-width': 'none', 'min-height': 'none'});
  124. // _getMaxDims has side effects (boo) but calling it should update all other necessary heights & widths
  125. this.$wrapper.css(this._getMaxDims());
  126. }
  127. /**
  128. * Adds event handlers to elements in the menu.
  129. * @function
  130. * @private
  131. * @param {jQuery} $elem - the current menu item to add handlers to.
  132. */
  133. _events($elem) {
  134. var _this = this;
  135. $elem.off('click.zf.drilldown')
  136. .on('click.zf.drilldown', function(e){
  137. if($(e.target).parentsUntil('ul', 'li').hasClass('is-drilldown-submenu-parent')){
  138. e.stopImmediatePropagation();
  139. e.preventDefault();
  140. }
  141. // if(e.target !== e.currentTarget.firstElementChild){
  142. // return false;
  143. // }
  144. _this._show($elem.parent('li'));
  145. if(_this.options.closeOnClick){
  146. var $body = $('body');
  147. $body.off('.zf.drilldown').on('click.zf.drilldown', function(e){
  148. if (e.target === _this.$element[0] || $.contains(_this.$element[0], e.target)) { return; }
  149. e.preventDefault();
  150. _this._hideAll();
  151. $body.off('.zf.drilldown');
  152. });
  153. }
  154. });
  155. }
  156. /**
  157. * Adds event handlers to the menu element.
  158. * @function
  159. * @private
  160. */
  161. _registerEvents() {
  162. if(this.options.scrollTop){
  163. this._bindHandler = this._scrollTop.bind(this);
  164. this.$element.on('open.zf.drilldown hide.zf.drilldown closed.zf.drilldown',this._bindHandler);
  165. }
  166. this.$element.on('mutateme.zf.trigger', this._resize.bind(this));
  167. }
  168. /**
  169. * Scroll to Top of Element or data-scroll-top-element
  170. * @function
  171. * @fires Drilldown#scrollme
  172. */
  173. _scrollTop() {
  174. var _this = this;
  175. var $scrollTopElement = _this.options.scrollTopElement!=''?$(_this.options.scrollTopElement):_this.$element,
  176. scrollPos = parseInt($scrollTopElement.offset().top+_this.options.scrollTopOffset, 10);
  177. $('html, body').stop(true).animate({ scrollTop: scrollPos }, _this.options.animationDuration, _this.options.animationEasing,function(){
  178. /**
  179. * Fires after the menu has scrolled
  180. * @event Drilldown#scrollme
  181. */
  182. if(this===$('html')[0])_this.$element.trigger('scrollme.zf.drilldown');
  183. });
  184. }
  185. /**
  186. * Adds keydown event listener to `li`'s in the menu.
  187. * @private
  188. */
  189. _keyboardEvents() {
  190. var _this = this;
  191. this.$menuItems.add(this.$element.find('.js-drilldown-back > a, .is-submenu-parent-item > a')).on('keydown.zf.drilldown', function(e){
  192. var $element = $(this),
  193. $elements = $element.parent('li').parent('ul').children('li').children('a'),
  194. $prevElement,
  195. $nextElement;
  196. $elements.each(function(i) {
  197. if ($(this).is($element)) {
  198. $prevElement = $elements.eq(Math.max(0, i-1));
  199. $nextElement = $elements.eq(Math.min(i+1, $elements.length-1));
  200. return;
  201. }
  202. });
  203. Keyboard.handleKey(e, 'Drilldown', {
  204. next: function() {
  205. if ($element.is(_this.$submenuAnchors)) {
  206. _this._show($element.parent('li'));
  207. $element.parent('li').one(transitionend($element), function(){
  208. $element.parent('li').find('ul li a').not('.js-drilldown-back a').first().focus();
  209. });
  210. return true;
  211. }
  212. },
  213. previous: function() {
  214. _this._hide($element.parent('li').parent('ul'));
  215. $element.parent('li').parent('ul').one(transitionend($element), function(){
  216. setTimeout(function() {
  217. $element.parent('li').parent('ul').parent('li').children('a').first().focus();
  218. }, 1);
  219. });
  220. return true;
  221. },
  222. up: function() {
  223. $prevElement.focus();
  224. // Don't tap focus on first element in root ul
  225. return !$element.is(_this.$element.find('> li:first-child > a'));
  226. },
  227. down: function() {
  228. $nextElement.focus();
  229. // Don't tap focus on last element in root ul
  230. return !$element.is(_this.$element.find('> li:last-child > a'));
  231. },
  232. close: function() {
  233. // Don't close on element in root ul
  234. if (!$element.is(_this.$element.find('> li > a'))) {
  235. _this._hide($element.parent().parent());
  236. $element.parent().parent().siblings('a').focus();
  237. }
  238. },
  239. open: function() {
  240. if (_this.options.parentLink && $element.attr('href')) { // Link with href
  241. return false;
  242. } else if (!$element.is(_this.$menuItems)) { // not menu item means back button
  243. _this._hide($element.parent('li').parent('ul'));
  244. $element.parent('li').parent('ul').one(transitionend($element), function(){
  245. setTimeout(function() {
  246. $element.parent('li').parent('ul').parent('li').children('a').first().focus();
  247. }, 1);
  248. });
  249. return true;
  250. } else if ($element.is(_this.$submenuAnchors)) { // Sub menu item
  251. _this._show($element.parent('li'));
  252. $element.parent('li').one(transitionend($element), function(){
  253. $element.parent('li').find('ul li a').not('.js-drilldown-back a').first().focus();
  254. });
  255. return true;
  256. }
  257. },
  258. handled: function(preventDefault) {
  259. if (preventDefault) {
  260. e.preventDefault();
  261. }
  262. e.stopImmediatePropagation();
  263. }
  264. });
  265. }); // end keyboardAccess
  266. }
  267. /**
  268. * Closes all open elements, and returns to root menu.
  269. * @function
  270. * @fires Drilldown#closed
  271. */
  272. _hideAll() {
  273. var $elem = this.$element.find('.is-drilldown-submenu.is-active').addClass('is-closing');
  274. if(this.options.autoHeight) this.$wrapper.css({height:$elem.parent().closest('ul').data('calcHeight')});
  275. $elem.one(transitionend($elem), function(e){
  276. $elem.removeClass('is-active is-closing');
  277. });
  278. /**
  279. * Fires when the menu is fully closed.
  280. * @event Drilldown#closed
  281. */
  282. this.$element.trigger('closed.zf.drilldown');
  283. }
  284. /**
  285. * Adds event listener for each `back` button, and closes open menus.
  286. * @function
  287. * @fires Drilldown#back
  288. * @param {jQuery} $elem - the current sub-menu to add `back` event.
  289. */
  290. _back($elem) {
  291. var _this = this;
  292. $elem.off('click.zf.drilldown');
  293. $elem.children('.js-drilldown-back')
  294. .on('click.zf.drilldown', function(e){
  295. e.stopImmediatePropagation();
  296. // console.log('mouseup on back');
  297. _this._hide($elem);
  298. // If there is a parent submenu, call show
  299. let parentSubMenu = $elem.parent('li').parent('ul').parent('li');
  300. if (parentSubMenu.length) {
  301. _this._show(parentSubMenu);
  302. }
  303. });
  304. }
  305. /**
  306. * Adds event listener to menu items w/o submenus to close open menus on click.
  307. * @function
  308. * @private
  309. */
  310. _menuLinkEvents() {
  311. var _this = this;
  312. this.$menuItems.not('.is-drilldown-submenu-parent')
  313. .off('click.zf.drilldown')
  314. .on('click.zf.drilldown', function(e){
  315. // e.stopImmediatePropagation();
  316. setTimeout(function(){
  317. _this._hideAll();
  318. }, 0);
  319. });
  320. }
  321. /**
  322. * Sets the CSS classes for submenu to show it.
  323. * @function
  324. * @private
  325. * @param {jQuery} $elem - the target submenu (`ul` tag)
  326. * @param {boolean} trigger - trigger drilldown event
  327. */
  328. _setShowSubMenuClasses($elem, trigger) {
  329. $elem.addClass('is-active').removeClass('invisible').attr('aria-hidden', false);
  330. $elem.parent('li').attr('aria-expanded', true);
  331. if (trigger === true) {
  332. this.$element.trigger('open.zf.drilldown', [$elem]);
  333. }
  334. }
  335. /**
  336. * Sets the CSS classes for submenu to hide it.
  337. * @function
  338. * @private
  339. * @param {jQuery} $elem - the target submenu (`ul` tag)
  340. * @param {boolean} trigger - trigger drilldown event
  341. */
  342. _setHideSubMenuClasses($elem, trigger) {
  343. $elem.removeClass('is-active').addClass('invisible').attr('aria-hidden', true);
  344. $elem.parent('li').attr('aria-expanded', false);
  345. if (trigger === true) {
  346. $elem.trigger('hide.zf.drilldown', [$elem]);
  347. }
  348. }
  349. /**
  350. * Opens a specific drilldown (sub)menu no matter which (sub)menu in it is currently visible.
  351. * Compared to _show() this lets you jump into any submenu without clicking through every submenu on the way to it.
  352. * @function
  353. * @fires Drilldown#open
  354. * @param {jQuery} $elem - the target (sub)menu (`ul` tag)
  355. * @param {boolean} autoFocus - if true the first link in the target (sub)menu gets auto focused
  356. */
  357. _showMenu($elem, autoFocus) {
  358. var _this = this;
  359. // Reset drilldown
  360. var $expandedSubmenus = this.$element.find('li[aria-expanded="true"] > ul[data-submenu]');
  361. $expandedSubmenus.each(function(index) {
  362. _this._setHideSubMenuClasses($(this));
  363. });
  364. // Save the menu as the currently displayed one.
  365. this.$currentMenu = $elem;
  366. // If target menu is root, focus first link & exit
  367. if ($elem.is('[data-drilldown]')) {
  368. if (autoFocus === true) $elem.find('li[role="treeitem"] > a').first().focus();
  369. if (this.options.autoHeight) this.$wrapper.css('height', $elem.data('calcHeight'));
  370. return;
  371. }
  372. // Find all submenus on way to root incl. the element itself
  373. var $submenus = $elem.children().first().parentsUntil('[data-drilldown]', '[data-submenu]');
  374. // Open target menu and all submenus on its way to root
  375. $submenus.each(function(index) {
  376. // Update height of first child (target menu) if autoHeight option true
  377. if (index === 0 && _this.options.autoHeight) {
  378. _this.$wrapper.css('height', $(this).data('calcHeight'));
  379. }
  380. var isLastChild = index == $submenus.length - 1;
  381. // Add transitionsend listener to last child (root due to reverse order) to open target menu's first link
  382. // Last child makes sure the event gets always triggered even if going through several menus
  383. if (isLastChild === true) {
  384. $(this).one(transitionend($(this)), () => {
  385. if (autoFocus === true) {
  386. $elem.find('li[role="treeitem"] > a').first().focus();
  387. }
  388. });
  389. }
  390. _this._setShowSubMenuClasses($(this), isLastChild);
  391. });
  392. }
  393. /**
  394. * Opens a submenu.
  395. * @function
  396. * @fires Drilldown#open
  397. * @param {jQuery} $elem - the current element with a submenu to open, i.e. the `li` tag.
  398. */
  399. _show($elem) {
  400. const $submenu = $elem.children('[data-submenu]');
  401. $elem.attr('aria-expanded', true);
  402. this.$currentMenu = $submenu;
  403. $submenu.addClass('is-active').removeClass('invisible').attr('aria-hidden', false);
  404. if (this.options.autoHeight) {
  405. this.$wrapper.css({ height: $submenu.data('calcHeight') });
  406. }
  407. /**
  408. * Fires when the submenu has opened.
  409. * @event Drilldown#open
  410. */
  411. this.$element.trigger('open.zf.drilldown', [$elem]);
  412. }
  413. /**
  414. * Hides a submenu
  415. * @function
  416. * @fires Drilldown#hide
  417. * @param {jQuery} $elem - the current sub-menu to hide, i.e. the `ul` tag.
  418. */
  419. _hide($elem) {
  420. if(this.options.autoHeight) this.$wrapper.css({height:$elem.parent().closest('ul').data('calcHeight')});
  421. var _this = this;
  422. $elem.parent('li').attr('aria-expanded', false);
  423. $elem.attr('aria-hidden', true);
  424. $elem.addClass('is-closing')
  425. .one(transitionend($elem), function(){
  426. $elem.removeClass('is-active is-closing');
  427. $elem.blur().addClass('invisible');
  428. });
  429. /**
  430. * Fires when the submenu has closed.
  431. * @event Drilldown#hide
  432. */
  433. $elem.trigger('hide.zf.drilldown', [$elem]);
  434. }
  435. /**
  436. * Iterates through the nested menus to calculate the min-height, and max-width for the menu.
  437. * Prevents content jumping.
  438. * @function
  439. * @private
  440. */
  441. _getMaxDims() {
  442. var maxHeight = 0, result = {}, _this = this;
  443. // Recalculate menu heights and total max height
  444. this.$submenus.add(this.$element).each(function(){
  445. var numOfElems = $(this).children('li').length;
  446. var height = Box.GetDimensions(this).height;
  447. maxHeight = height > maxHeight ? height : maxHeight;
  448. if(_this.options.autoHeight) {
  449. $(this).data('calcHeight',height);
  450. }
  451. });
  452. if (this.options.autoHeight)
  453. result['height'] = this.$currentMenu.data('calcHeight');
  454. else
  455. result['min-height'] = `${maxHeight}px`;
  456. result['max-width'] = `${this.$element[0].getBoundingClientRect().width}px`;
  457. return result;
  458. }
  459. /**
  460. * Destroys the Drilldown Menu
  461. * @function
  462. */
  463. _destroy() {
  464. if(this.options.scrollTop) this.$element.off('.zf.drilldown',this._bindHandler);
  465. this._hideAll();
  466. this.$element.off('mutateme.zf.trigger');
  467. Nest.Burn(this.$element, 'drilldown');
  468. this.$element.unwrap()
  469. .find('.js-drilldown-back, .is-submenu-parent-item').remove()
  470. .end().find('.is-active, .is-closing, .is-drilldown-submenu').removeClass('is-active is-closing is-drilldown-submenu')
  471. .end().find('[data-submenu]').removeAttr('aria-hidden tabindex role');
  472. this.$submenuAnchors.each(function() {
  473. $(this).off('.zf.drilldown');
  474. });
  475. this.$element.find('[data-is-parent-link]').detach();
  476. this.$submenus.removeClass('drilldown-submenu-cover-previous invisible');
  477. this.$element.find('a').each(function(){
  478. var $link = $(this);
  479. $link.removeAttr('tabindex');
  480. if($link.data('savedHref')){
  481. $link.attr('href', $link.data('savedHref')).removeData('savedHref');
  482. }else{ return; }
  483. });
  484. };
  485. }
  486. Drilldown.defaults = {
  487. /**
  488. * Drilldowns depend on styles in order to function properly; in the default build of Foundation these are
  489. * on the `drilldown` class. This option auto-applies this class to the drilldown upon initialization.
  490. * @option
  491. * @type {boolian}
  492. * @default true
  493. */
  494. autoApplyClass: true,
  495. /**
  496. * Markup used for JS generated back button. Prepended or appended (see backButtonPosition) to submenu lists and deleted on `destroy` method, 'js-drilldown-back' class required. Remove the backslash (`\`) if copy and pasting.
  497. * @option
  498. * @type {string}
  499. * @default '<li class="js-drilldown-back"><a tabindex="0">Back</a></li>'
  500. */
  501. backButton: '<li class="js-drilldown-back"><a tabindex="0">Back</a></li>',
  502. /**
  503. * Position the back button either at the top or bottom of drilldown submenus. Can be `'left'` or `'bottom'`.
  504. * @option
  505. * @type {string}
  506. * @default top
  507. */
  508. backButtonPosition: 'top',
  509. /**
  510. * Markup used to wrap drilldown menu. Use a class name for independent styling; the JS applied class: `is-drilldown` is required. Remove the backslash (`\`) if copy and pasting.
  511. * @option
  512. * @type {string}
  513. * @default '<div></div>'
  514. */
  515. wrapper: '<div></div>',
  516. /**
  517. * Adds the parent link to the submenu.
  518. * @option
  519. * @type {boolean}
  520. * @default false
  521. */
  522. parentLink: false,
  523. /**
  524. * Allow the menu to return to root list on body click.
  525. * @option
  526. * @type {boolean}
  527. * @default false
  528. */
  529. closeOnClick: false,
  530. /**
  531. * Allow the menu to auto adjust height.
  532. * @option
  533. * @type {boolean}
  534. * @default false
  535. */
  536. autoHeight: false,
  537. /**
  538. * Animate the auto adjust height.
  539. * @option
  540. * @type {boolean}
  541. * @default false
  542. */
  543. animateHeight: false,
  544. /**
  545. * Scroll to the top of the menu after opening a submenu or navigating back using the menu back button
  546. * @option
  547. * @type {boolean}
  548. * @default false
  549. */
  550. scrollTop: false,
  551. /**
  552. * String jquery selector (for example 'body') of element to take offset().top from, if empty string the drilldown menu offset().top is taken
  553. * @option
  554. * @type {string}
  555. * @default ''
  556. */
  557. scrollTopElement: '',
  558. /**
  559. * ScrollTop offset
  560. * @option
  561. * @type {number}
  562. * @default 0
  563. */
  564. scrollTopOffset: 0,
  565. /**
  566. * Scroll animation duration
  567. * @option
  568. * @type {number}
  569. * @default 500
  570. */
  571. animationDuration: 500,
  572. /**
  573. * Scroll animation easing. Can be `'swing'` or `'linear'`.
  574. * @option
  575. * @type {string}
  576. * @see {@link https://api.jquery.com/animate|JQuery animate}
  577. * @default 'swing'
  578. */
  579. animationEasing: 'swing'
  580. // holdOpen: false
  581. };
  582. export {Drilldown};