index.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806
  1. /* -----------------------------------------------------------------------------------------------
  2. Namespace
  3. --------------------------------------------------------------------------------------------------- */
  4. var twentytwenty = twentytwenty || {};
  5. // Set a default value for scrolled.
  6. twentytwenty.scrolled = 0;
  7. // polyfill closest
  8. // https://developer.mozilla.org/en-US/docs/Web/API/Element/closest#Polyfill
  9. if ( ! Element.prototype.closest ) {
  10. Element.prototype.closest = function( s ) {
  11. var el = this;
  12. do {
  13. if ( el.matches( s ) ) {
  14. return el;
  15. }
  16. el = el.parentElement || el.parentNode;
  17. } while ( el !== null && el.nodeType === 1 );
  18. return null;
  19. };
  20. }
  21. // polyfill forEach
  22. // https://developer.mozilla.org/en-US/docs/Web/API/NodeList/forEach#Polyfill
  23. if ( window.NodeList && ! NodeList.prototype.forEach ) {
  24. NodeList.prototype.forEach = function( callback, thisArg ) {
  25. var i;
  26. var len = this.length;
  27. thisArg = thisArg || window;
  28. for ( i = 0; i < len; i++ ) {
  29. callback.call( thisArg, this[ i ], i, this );
  30. }
  31. };
  32. }
  33. // event "polyfill"
  34. twentytwenty.createEvent = function( eventName ) {
  35. var event;
  36. if ( typeof window.Event === 'function' ) {
  37. event = new Event( eventName );
  38. } else {
  39. event = document.createEvent( 'Event' );
  40. event.initEvent( eventName, true, false );
  41. }
  42. return event;
  43. };
  44. // matches "polyfill"
  45. // https://developer.mozilla.org/es/docs/Web/API/Element/matches
  46. if ( ! Element.prototype.matches ) {
  47. Element.prototype.matches =
  48. Element.prototype.matchesSelector ||
  49. Element.prototype.mozMatchesSelector ||
  50. Element.prototype.msMatchesSelector ||
  51. Element.prototype.oMatchesSelector ||
  52. Element.prototype.webkitMatchesSelector ||
  53. function( s ) {
  54. var matches = ( this.document || this.ownerDocument ).querySelectorAll( s ),
  55. i = matches.length;
  56. while ( --i >= 0 && matches.item( i ) !== this ) {}
  57. return i > -1;
  58. };
  59. }
  60. // Add a class to the body for when touch is enabled for browsers that don't support media queries
  61. // for interaction media features. Adapted from <https://codepen.io/Ferie/pen/vQOMmO>.
  62. twentytwenty.touchEnabled = {
  63. init: function() {
  64. var matchMedia = function() {
  65. // Include the 'heartz' as a way to have a non matching MQ to help terminate the join. See <https://git.io/vznFH>.
  66. var prefixes = [ '-webkit-', '-moz-', '-o-', '-ms-' ];
  67. var query = [ '(', prefixes.join( 'touch-enabled),(' ), 'heartz', ')' ].join( '' );
  68. return window.matchMedia && window.matchMedia( query ).matches;
  69. };
  70. if ( ( 'ontouchstart' in window ) || ( window.DocumentTouch && document instanceof window.DocumentTouch ) || matchMedia() ) {
  71. document.body.classList.add( 'touch-enabled' );
  72. }
  73. }
  74. }; // twentytwenty.touchEnabled
  75. /* -----------------------------------------------------------------------------------------------
  76. Cover Modals
  77. --------------------------------------------------------------------------------------------------- */
  78. twentytwenty.coverModals = {
  79. init: function() {
  80. if ( document.querySelector( '.cover-modal' ) ) {
  81. // Handle cover modals when they're toggled.
  82. this.onToggle();
  83. // When toggled, untoggle if visitor clicks on the wrapping element of the modal.
  84. this.outsideUntoggle();
  85. // Close on escape key press.
  86. this.closeOnEscape();
  87. // Hide and show modals before and after their animations have played out.
  88. this.hideAndShowModals();
  89. }
  90. },
  91. // Handle cover modals when they're toggled.
  92. onToggle: function() {
  93. document.querySelectorAll( '.cover-modal' ).forEach( function( element ) {
  94. element.addEventListener( 'toggled', function( event ) {
  95. var modal = event.target,
  96. body = document.body;
  97. if ( modal.classList.contains( 'active' ) ) {
  98. body.classList.add( 'showing-modal' );
  99. } else {
  100. body.classList.remove( 'showing-modal' );
  101. body.classList.add( 'hiding-modal' );
  102. // Remove the hiding class after a delay, when animations have been run.
  103. setTimeout( function() {
  104. body.classList.remove( 'hiding-modal' );
  105. }, 500 );
  106. }
  107. } );
  108. } );
  109. },
  110. // Close modal on outside click.
  111. outsideUntoggle: function() {
  112. document.addEventListener( 'click', function( event ) {
  113. var target = event.target;
  114. var modal = document.querySelector( '.cover-modal.active' );
  115. if ( target === modal ) {
  116. this.untoggleModal( target );
  117. }
  118. }.bind( this ) );
  119. },
  120. // Close modal on escape key press.
  121. closeOnEscape: function() {
  122. document.addEventListener( 'keydown', function( event ) {
  123. if ( event.keyCode === 27 ) {
  124. event.preventDefault();
  125. document.querySelectorAll( '.cover-modal.active' ).forEach( function( element ) {
  126. this.untoggleModal( element );
  127. }.bind( this ) );
  128. }
  129. }.bind( this ) );
  130. },
  131. // Hide and show modals before and after their animations have played out.
  132. hideAndShowModals: function() {
  133. var _doc = document,
  134. _win = window,
  135. modals = _doc.querySelectorAll( '.cover-modal' ),
  136. htmlStyle = _doc.documentElement.style,
  137. adminBar = _doc.querySelector( '#wpadminbar' );
  138. function getAdminBarHeight( negativeValue ) {
  139. var height,
  140. currentScroll = _win.pageYOffset;
  141. if ( adminBar ) {
  142. height = currentScroll + adminBar.getBoundingClientRect().height;
  143. return negativeValue ? -height : height;
  144. }
  145. return currentScroll === 0 ? 0 : -currentScroll;
  146. }
  147. function htmlStyles() {
  148. var overflow = _win.innerHeight > _doc.documentElement.getBoundingClientRect().height;
  149. return {
  150. 'overflow-y': overflow ? 'hidden' : 'scroll',
  151. position: 'fixed',
  152. width: '100%',
  153. top: getAdminBarHeight( true ) + 'px',
  154. left: 0
  155. };
  156. }
  157. // Show the modal.
  158. modals.forEach( function( modal ) {
  159. modal.addEventListener( 'toggle-target-before-inactive', function( event ) {
  160. var styles = htmlStyles(),
  161. offsetY = _win.pageYOffset,
  162. paddingTop = ( Math.abs( getAdminBarHeight() ) - offsetY ) + 'px',
  163. mQuery = _win.matchMedia( '(max-width: 600px)' );
  164. if ( event.target !== modal ) {
  165. return;
  166. }
  167. Object.keys( styles ).forEach( function( styleKey ) {
  168. htmlStyle.setProperty( styleKey, styles[ styleKey ] );
  169. } );
  170. _win.twentytwenty.scrolled = parseInt( styles.top, 10 );
  171. if ( adminBar ) {
  172. _doc.body.style.setProperty( 'padding-top', paddingTop );
  173. if ( mQuery.matches ) {
  174. if ( offsetY >= getAdminBarHeight() ) {
  175. modal.style.setProperty( 'top', 0 );
  176. } else {
  177. modal.style.setProperty( 'top', ( getAdminBarHeight() - offsetY ) + 'px' );
  178. }
  179. }
  180. }
  181. modal.classList.add( 'show-modal' );
  182. } );
  183. // Hide the modal after a delay, so animations have time to play out.
  184. modal.addEventListener( 'toggle-target-after-inactive', function( event ) {
  185. if ( event.target !== modal ) {
  186. return;
  187. }
  188. setTimeout( function() {
  189. var clickedEl = twentytwenty.toggles.clickedEl;
  190. modal.classList.remove( 'show-modal' );
  191. Object.keys( htmlStyles() ).forEach( function( styleKey ) {
  192. htmlStyle.removeProperty( styleKey );
  193. } );
  194. if ( adminBar ) {
  195. _doc.body.style.removeProperty( 'padding-top' );
  196. modal.style.removeProperty( 'top' );
  197. }
  198. if ( clickedEl !== false ) {
  199. clickedEl.focus();
  200. clickedEl = false;
  201. }
  202. _win.scrollTo( 0, Math.abs( _win.twentytwenty.scrolled + getAdminBarHeight() ) );
  203. _win.twentytwenty.scrolled = 0;
  204. }, 500 );
  205. } );
  206. } );
  207. },
  208. // Untoggle a modal.
  209. untoggleModal: function( modal ) {
  210. var modalTargetClass,
  211. modalToggle = false;
  212. // If the modal has specified the string (ID or class) used by toggles to target it, untoggle the toggles with that target string.
  213. // The modal-target-string must match the string toggles use to target the modal.
  214. if ( modal.dataset.modalTargetString ) {
  215. modalTargetClass = modal.dataset.modalTargetString;
  216. modalToggle = document.querySelector( '*[data-toggle-target="' + modalTargetClass + '"]' );
  217. }
  218. // If a modal toggle exists, trigger it so all of the toggle options are included.
  219. if ( modalToggle ) {
  220. modalToggle.click();
  221. // If one doesn't exist, just hide the modal.
  222. } else {
  223. modal.classList.remove( 'active' );
  224. }
  225. }
  226. }; // twentytwenty.coverModals
  227. /* -----------------------------------------------------------------------------------------------
  228. Intrinsic Ratio Embeds
  229. --------------------------------------------------------------------------------------------------- */
  230. twentytwenty.intrinsicRatioVideos = {
  231. init: function() {
  232. this.makeFit();
  233. window.addEventListener( 'resize', function() {
  234. this.makeFit();
  235. }.bind( this ) );
  236. },
  237. makeFit: function() {
  238. document.querySelectorAll( 'iframe, object, video' ).forEach( function( video ) {
  239. var ratio, iTargetWidth,
  240. container = video.parentNode;
  241. // Skip videos we want to ignore.
  242. if ( video.classList.contains( 'intrinsic-ignore' ) || video.parentNode.classList.contains( 'intrinsic-ignore' ) ) {
  243. return true;
  244. }
  245. if ( ! video.dataset.origwidth ) {
  246. // Get the video element proportions.
  247. video.setAttribute( 'data-origwidth', video.width );
  248. video.setAttribute( 'data-origheight', video.height );
  249. }
  250. iTargetWidth = container.offsetWidth;
  251. // Get ratio from proportions.
  252. ratio = iTargetWidth / video.dataset.origwidth;
  253. // Scale based on ratio, thus retaining proportions.
  254. video.style.width = iTargetWidth + 'px';
  255. video.style.height = ( video.dataset.origheight * ratio ) + 'px';
  256. } );
  257. }
  258. }; // twentytwenty.instrinsicRatioVideos
  259. /* -----------------------------------------------------------------------------------------------
  260. Modal Menu
  261. --------------------------------------------------------------------------------------------------- */
  262. twentytwenty.modalMenu = {
  263. init: function() {
  264. // If the current menu item is in a sub level, expand all the levels higher up on load.
  265. this.expandLevel();
  266. this.keepFocusInModal();
  267. },
  268. expandLevel: function() {
  269. var modalMenus = document.querySelectorAll( '.modal-menu' );
  270. modalMenus.forEach( function( modalMenu ) {
  271. var activeMenuItem = modalMenu.querySelector( '.current-menu-item' );
  272. if ( activeMenuItem ) {
  273. twentytwentyFindParents( activeMenuItem, 'li' ).forEach( function( element ) {
  274. var subMenuToggle = element.querySelector( '.sub-menu-toggle' );
  275. if ( subMenuToggle ) {
  276. twentytwenty.toggles.performToggle( subMenuToggle, true );
  277. }
  278. } );
  279. }
  280. } );
  281. },
  282. keepFocusInModal: function() {
  283. var _doc = document;
  284. _doc.addEventListener( 'keydown', function( event ) {
  285. var toggleTarget, modal, selectors, elements, menuType, bottomMenu, activeEl, lastEl, firstEl, tabKey, shiftKey,
  286. clickedEl = twentytwenty.toggles.clickedEl;
  287. if ( clickedEl && _doc.body.classList.contains( 'showing-modal' ) ) {
  288. toggleTarget = clickedEl.dataset.toggleTarget;
  289. selectors = 'input, a, button';
  290. modal = _doc.querySelector( toggleTarget );
  291. elements = modal.querySelectorAll( selectors );
  292. elements = Array.prototype.slice.call( elements );
  293. if ( '.menu-modal' === toggleTarget ) {
  294. menuType = window.matchMedia( '(min-width: 1000px)' ).matches;
  295. menuType = menuType ? '.expanded-menu' : '.mobile-menu';
  296. elements = elements.filter( function( element ) {
  297. return null !== element.closest( menuType ) && null !== element.offsetParent;
  298. } );
  299. elements.unshift( _doc.querySelector( '.close-nav-toggle' ) );
  300. bottomMenu = _doc.querySelector( '.menu-bottom > nav' );
  301. if ( bottomMenu ) {
  302. bottomMenu.querySelectorAll( selectors ).forEach( function( element ) {
  303. elements.push( element );
  304. } );
  305. }
  306. }
  307. lastEl = elements[ elements.length - 1 ];
  308. firstEl = elements[0];
  309. activeEl = _doc.activeElement;
  310. tabKey = event.keyCode === 9;
  311. shiftKey = event.shiftKey;
  312. if ( ! shiftKey && tabKey && lastEl === activeEl ) {
  313. event.preventDefault();
  314. firstEl.focus();
  315. }
  316. if ( shiftKey && tabKey && firstEl === activeEl ) {
  317. event.preventDefault();
  318. lastEl.focus();
  319. }
  320. }
  321. } );
  322. }
  323. }; // twentytwenty.modalMenu
  324. /* -----------------------------------------------------------------------------------------------
  325. Primary Menu
  326. --------------------------------------------------------------------------------------------------- */
  327. twentytwenty.primaryMenu = {
  328. init: function() {
  329. this.focusMenuWithChildren();
  330. },
  331. // The focusMenuWithChildren() function implements Keyboard Navigation in the Primary Menu
  332. // by adding the '.focus' class to all 'li.menu-item-has-children' when the focus is on the 'a' element.
  333. focusMenuWithChildren: function() {
  334. // Get all the link elements within the primary menu.
  335. var links, i, len,
  336. menu = document.querySelector( '.primary-menu-wrapper' );
  337. if ( ! menu ) {
  338. return false;
  339. }
  340. links = menu.getElementsByTagName( 'a' );
  341. // Each time a menu link is focused or blurred, toggle focus.
  342. for ( i = 0, len = links.length; i < len; i++ ) {
  343. links[i].addEventListener( 'focus', toggleFocus, true );
  344. links[i].addEventListener( 'blur', toggleFocus, true );
  345. }
  346. //Sets or removes the .focus class on an element.
  347. function toggleFocus() {
  348. var self = this;
  349. // Move up through the ancestors of the current link until we hit .primary-menu.
  350. while ( -1 === self.className.indexOf( 'primary-menu' ) ) {
  351. // On li elements toggle the class .focus.
  352. if ( 'li' === self.tagName.toLowerCase() ) {
  353. if ( -1 !== self.className.indexOf( 'focus' ) ) {
  354. self.className = self.className.replace( ' focus', '' );
  355. } else {
  356. self.className += ' focus';
  357. }
  358. }
  359. self = self.parentElement;
  360. }
  361. }
  362. }
  363. }; // twentytwenty.primaryMenu
  364. /* -----------------------------------------------------------------------------------------------
  365. Toggles
  366. --------------------------------------------------------------------------------------------------- */
  367. twentytwenty.toggles = {
  368. clickedEl: false,
  369. init: function() {
  370. // Do the toggle.
  371. this.toggle();
  372. // Check for toggle/untoggle on resize.
  373. this.resizeCheck();
  374. // Check for untoggle on escape key press.
  375. this.untoggleOnEscapeKeyPress();
  376. },
  377. performToggle: function( element, instantly ) {
  378. var target, timeOutTime, classToToggle,
  379. self = this,
  380. _doc = document,
  381. // Get our targets.
  382. toggle = element,
  383. targetString = toggle.dataset.toggleTarget,
  384. activeClass = 'active';
  385. // Elements to focus after modals are closed.
  386. if ( ! _doc.querySelectorAll( '.show-modal' ).length ) {
  387. self.clickedEl = _doc.activeElement;
  388. }
  389. if ( targetString === 'next' ) {
  390. target = toggle.nextSibling;
  391. } else {
  392. target = _doc.querySelector( targetString );
  393. }
  394. // Trigger events on the toggle targets before they are toggled.
  395. if ( target.classList.contains( activeClass ) ) {
  396. target.dispatchEvent( twentytwenty.createEvent( 'toggle-target-before-active' ) );
  397. } else {
  398. target.dispatchEvent( twentytwenty.createEvent( 'toggle-target-before-inactive' ) );
  399. }
  400. // Get the class to toggle, if specified.
  401. classToToggle = toggle.dataset.classToToggle ? toggle.dataset.classToToggle : activeClass;
  402. // For cover modals, set a short timeout duration so the class animations have time to play out.
  403. timeOutTime = 0;
  404. if ( target.classList.contains( 'cover-modal' ) ) {
  405. timeOutTime = 10;
  406. }
  407. setTimeout( function() {
  408. var focusElement,
  409. subMenued = target.classList.contains( 'sub-menu' ),
  410. newTarget = subMenued ? toggle.closest( '.menu-item' ).querySelector( '.sub-menu' ) : target,
  411. duration = toggle.dataset.toggleDuration;
  412. // Toggle the target of the clicked toggle.
  413. if ( toggle.dataset.toggleType === 'slidetoggle' && ! instantly && duration !== '0' ) {
  414. twentytwentyMenuToggle( newTarget, duration );
  415. } else {
  416. newTarget.classList.toggle( classToToggle );
  417. }
  418. // If the toggle target is 'next', only give the clicked toggle the active class.
  419. if ( targetString === 'next' ) {
  420. toggle.classList.toggle( activeClass );
  421. } else if ( target.classList.contains( 'sub-menu' ) ) {
  422. toggle.classList.toggle( activeClass );
  423. } else {
  424. // If not, toggle all toggles with this toggle target.
  425. _doc.querySelector( '*[data-toggle-target="' + targetString + '"]' ).classList.toggle( activeClass );
  426. }
  427. // Toggle aria-expanded on the toggle.
  428. twentytwentyToggleAttribute( toggle, 'aria-expanded', 'true', 'false' );
  429. if ( self.clickedEl && -1 !== toggle.getAttribute( 'class' ).indexOf( 'close-' ) ) {
  430. twentytwentyToggleAttribute( self.clickedEl, 'aria-expanded', 'true', 'false' );
  431. }
  432. // Toggle body class.
  433. if ( toggle.dataset.toggleBodyClass ) {
  434. _doc.body.classList.toggle( toggle.dataset.toggleBodyClass );
  435. }
  436. // Check whether to set focus.
  437. if ( toggle.dataset.setFocus ) {
  438. focusElement = _doc.querySelector( toggle.dataset.setFocus );
  439. if ( focusElement ) {
  440. if ( target.classList.contains( activeClass ) ) {
  441. focusElement.focus();
  442. } else {
  443. focusElement.blur();
  444. }
  445. }
  446. }
  447. // Trigger the toggled event on the toggle target.
  448. target.dispatchEvent( twentytwenty.createEvent( 'toggled' ) );
  449. // Trigger events on the toggle targets after they are toggled.
  450. if ( target.classList.contains( activeClass ) ) {
  451. target.dispatchEvent( twentytwenty.createEvent( 'toggle-target-after-active' ) );
  452. } else {
  453. target.dispatchEvent( twentytwenty.createEvent( 'toggle-target-after-inactive' ) );
  454. }
  455. }, timeOutTime );
  456. },
  457. // Do the toggle.
  458. toggle: function() {
  459. var self = this;
  460. document.querySelectorAll( '*[data-toggle-target]' ).forEach( function( element ) {
  461. element.addEventListener( 'click', function( event ) {
  462. event.preventDefault();
  463. self.performToggle( element );
  464. } );
  465. } );
  466. },
  467. // Check for toggle/untoggle on screen resize.
  468. resizeCheck: function() {
  469. if ( document.querySelectorAll( '*[data-untoggle-above], *[data-untoggle-below], *[data-toggle-above], *[data-toggle-below]' ).length ) {
  470. window.addEventListener( 'resize', function() {
  471. var winWidth = window.innerWidth,
  472. toggles = document.querySelectorAll( '.toggle' );
  473. toggles.forEach( function( toggle ) {
  474. var unToggleAbove = toggle.dataset.untoggleAbove,
  475. unToggleBelow = toggle.dataset.untoggleBelow,
  476. toggleAbove = toggle.dataset.toggleAbove,
  477. toggleBelow = toggle.dataset.toggleBelow;
  478. // If no width comparison is set, continue.
  479. if ( ! unToggleAbove && ! unToggleBelow && ! toggleAbove && ! toggleBelow ) {
  480. return;
  481. }
  482. // If the toggle width comparison is true, toggle the toggle.
  483. if (
  484. ( ( ( unToggleAbove && winWidth > unToggleAbove ) ||
  485. ( unToggleBelow && winWidth < unToggleBelow ) ) &&
  486. toggle.classList.contains( 'active' ) ) ||
  487. ( ( ( toggleAbove && winWidth > toggleAbove ) ||
  488. ( toggleBelow && winWidth < toggleBelow ) ) &&
  489. ! toggle.classList.contains( 'active' ) )
  490. ) {
  491. toggle.click();
  492. }
  493. } );
  494. } );
  495. }
  496. },
  497. // Close toggle on escape key press.
  498. untoggleOnEscapeKeyPress: function() {
  499. document.addEventListener( 'keyup', function( event ) {
  500. if ( event.key === 'Escape' ) {
  501. document.querySelectorAll( '*[data-untoggle-on-escape].active' ).forEach( function( element ) {
  502. if ( element.classList.contains( 'active' ) ) {
  503. element.click();
  504. }
  505. } );
  506. }
  507. } );
  508. }
  509. }; // twentytwenty.toggles
  510. /**
  511. * Is the DOM ready?
  512. *
  513. * This implementation is coming from https://gomakethings.com/a-native-javascript-equivalent-of-jquerys-ready-method/
  514. *
  515. * @param {Function} fn Callback function to run.
  516. */
  517. function twentytwentyDomReady( fn ) {
  518. if ( typeof fn !== 'function' ) {
  519. return;
  520. }
  521. if ( document.readyState === 'interactive' || document.readyState === 'complete' ) {
  522. return fn();
  523. }
  524. document.addEventListener( 'DOMContentLoaded', fn, false );
  525. }
  526. twentytwentyDomReady( function() {
  527. twentytwenty.toggles.init(); // Handle toggles.
  528. twentytwenty.coverModals.init(); // Handle cover modals.
  529. twentytwenty.intrinsicRatioVideos.init(); // Retain aspect ratio of videos on window resize.
  530. twentytwenty.modalMenu.init(); // Modal Menu.
  531. twentytwenty.primaryMenu.init(); // Primary Menu.
  532. twentytwenty.touchEnabled.init(); // Add class to body if device is touch-enabled.
  533. } );
  534. /* -----------------------------------------------------------------------------------------------
  535. Helper functions
  536. --------------------------------------------------------------------------------------------------- */
  537. /* Toggle an attribute ----------------------- */
  538. function twentytwentyToggleAttribute( element, attribute, trueVal, falseVal ) {
  539. if ( trueVal === undefined ) {
  540. trueVal = true;
  541. }
  542. if ( falseVal === undefined ) {
  543. falseVal = false;
  544. }
  545. if ( element.getAttribute( attribute ) !== trueVal ) {
  546. element.setAttribute( attribute, trueVal );
  547. } else {
  548. element.setAttribute( attribute, falseVal );
  549. }
  550. }
  551. /**
  552. * Toggle a menu item on or off.
  553. *
  554. * @param {HTMLElement} target
  555. * @param {number} duration
  556. */
  557. function twentytwentyMenuToggle( target, duration ) {
  558. var initialParentHeight, finalParentHeight, menu, menuItems, transitionListener,
  559. initialPositions = [],
  560. finalPositions = [];
  561. if ( ! target ) {
  562. return;
  563. }
  564. menu = target.closest( '.menu-wrapper' );
  565. // Step 1: look at the initial positions of every menu item.
  566. menuItems = menu.querySelectorAll( '.menu-item' );
  567. menuItems.forEach( function( menuItem, index ) {
  568. initialPositions[ index ] = { x: menuItem.offsetLeft, y: menuItem.offsetTop };
  569. } );
  570. initialParentHeight = target.parentElement.offsetHeight;
  571. target.classList.add( 'toggling-target' );
  572. // Step 2: toggle target menu item and look at the final positions of every menu item.
  573. target.classList.toggle( 'active' );
  574. menuItems.forEach( function( menuItem, index ) {
  575. finalPositions[ index ] = { x: menuItem.offsetLeft, y: menuItem.offsetTop };
  576. } );
  577. finalParentHeight = target.parentElement.offsetHeight;
  578. // Step 3: close target menu item again.
  579. // The whole process happens without giving the browser a chance to render, so it's invisible.
  580. target.classList.toggle( 'active' );
  581. /*
  582. * Step 4: prepare animation.
  583. * Position all the items with absolute offsets, at the same starting position.
  584. * Shouldn't result in any visual changes if done right.
  585. */
  586. menu.classList.add( 'is-toggling' );
  587. target.classList.toggle( 'active' );
  588. menuItems.forEach( function( menuItem, index ) {
  589. var initialPosition = initialPositions[ index ];
  590. if ( initialPosition.y === 0 && menuItem.parentElement === target ) {
  591. initialPosition.y = initialParentHeight;
  592. }
  593. menuItem.style.transform = 'translate(' + initialPosition.x + 'px, ' + initialPosition.y + 'px)';
  594. } );
  595. /*
  596. * The double rAF is unfortunately needed, since we're toggling CSS classes, and
  597. * the only way to ensure layout completion here across browsers is to wait twice.
  598. * This just delays the start of the animation by 2 frames and is thus not an issue.
  599. */
  600. requestAnimationFrame( function() {
  601. requestAnimationFrame( function() {
  602. /*
  603. * Step 5: start animation by moving everything to final position.
  604. * All the layout work has already happened, while we were preparing for the animation.
  605. * The animation now runs entirely in CSS, using cheap CSS properties (opacity and transform)
  606. * that don't trigger the layout or paint stages.
  607. */
  608. menu.classList.add( 'is-animating' );
  609. menuItems.forEach( function( menuItem, index ) {
  610. var finalPosition = finalPositions[ index ];
  611. if ( finalPosition.y === 0 && menuItem.parentElement === target ) {
  612. finalPosition.y = finalParentHeight;
  613. }
  614. if ( duration !== undefined ) {
  615. menuItem.style.transitionDuration = duration + 'ms';
  616. }
  617. menuItem.style.transform = 'translate(' + finalPosition.x + 'px, ' + finalPosition.y + 'px)';
  618. } );
  619. if ( duration !== undefined ) {
  620. target.style.transitionDuration = duration + 'ms';
  621. }
  622. } );
  623. // Step 6: finish toggling.
  624. // Remove all transient classes when the animation ends.
  625. transitionListener = function() {
  626. menu.classList.remove( 'is-animating' );
  627. menu.classList.remove( 'is-toggling' );
  628. target.classList.remove( 'toggling-target' );
  629. menuItems.forEach( function( menuItem ) {
  630. menuItem.style.transform = '';
  631. menuItem.style.transitionDuration = '';
  632. } );
  633. target.style.transitionDuration = '';
  634. target.removeEventListener( 'transitionend', transitionListener );
  635. };
  636. target.addEventListener( 'transitionend', transitionListener );
  637. } );
  638. }
  639. /**
  640. * Traverses the DOM up to find elements matching the query.
  641. *
  642. * @param {HTMLElement} target
  643. * @param {string} query
  644. * @return {NodeList} parents matching query
  645. */
  646. function twentytwentyFindParents( target, query ) {
  647. var parents = [];
  648. // Recursively go up the DOM adding matches to the parents array.
  649. function traverse( item ) {
  650. var parent = item.parentNode;
  651. if ( parent instanceof HTMLElement ) {
  652. if ( parent.matches( query ) ) {
  653. parents.push( parent );
  654. }
  655. traverse( parent );
  656. }
  657. }
  658. traverse( target );
  659. return parents;
  660. }