wowchemy.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691
  1. /*************************************************
  2. * Wowchemy
  3. * https://github.com/wowchemy/wowchemy-hugo-modules
  4. *
  5. * Core JS functions and initialization.
  6. **************************************************/
  7. import {hugoEnvironment, codeHighlighting, searchEnabled} from '@params';
  8. import {fixMermaid, scrollParentToChild} from './wowchemy-utils';
  9. import {
  10. changeThemeModeClick,
  11. initThemeVariation,
  12. renderThemeVariation,
  13. onMediaQueryListEvent,
  14. } from './wowchemy-theming';
  15. console.debug(`Environment: ${hugoEnvironment}`);
  16. /* ---------------------------------------------------------------------------
  17. * Responsive scrolling for URL hashes.
  18. * --------------------------------------------------------------------------- */
  19. // Dynamically get responsive navigation bar height for offsetting Scrollspy.
  20. function getNavBarHeight() {
  21. let $navbar = $('#navbar-main');
  22. let navbar_offset = $navbar.outerHeight();
  23. console.debug('Navbar height: ' + navbar_offset);
  24. return navbar_offset;
  25. }
  26. /**
  27. * Responsive hash scrolling.
  28. * Check for a URL hash as an anchor.
  29. * If page anchor matches hash, scroll to it responsively considering dynamic height elements.
  30. * If `target` argument omitted (e.g. after event), assume it's the window's hash.
  31. * Default to 0ms animation duration as don't want animation for fixing scrollspy Book page ToC highlighting.
  32. */
  33. function scrollToAnchor(target, duration = 0) {
  34. // If `target` is undefined or HashChangeEvent object, set it to window's hash.
  35. // Decode the hash as browsers can encode non-ASCII characters (e.g. Chinese symbols).
  36. target =
  37. typeof target === 'undefined' || typeof target === 'object' ? decodeURIComponent(window.location.hash) : target;
  38. // If target element exists, scroll to it taking into account fixed navigation bar offset.
  39. if ($(target).length) {
  40. // Escape special chars from IDs, such as colons found in Markdown footnote links.
  41. target = '#' + $.escapeSelector(target.substring(1)); // Previously, `target = target.replace(/:/g, '\\:');`
  42. let elementOffset = Math.ceil($(target).offset().top - getNavBarHeight()); // Round up to highlight right ID!
  43. $('body').addClass('scrolling');
  44. $('html, body').animate(
  45. {
  46. scrollTop: elementOffset,
  47. },
  48. duration,
  49. function () {
  50. $('body').removeClass('scrolling');
  51. },
  52. );
  53. } else {
  54. console.debug('Cannot scroll to target `#' + target + '`. ID not found!');
  55. }
  56. }
  57. // Make Scrollspy responsive.
  58. function fixScrollspy() {
  59. let $body = $('body');
  60. let data = $body.data('bs.scrollspy');
  61. if (data) {
  62. data._config.offset = getNavBarHeight();
  63. $body.data('bs.scrollspy', data);
  64. $body.scrollspy('refresh');
  65. }
  66. }
  67. function removeQueryParamsFromUrl() {
  68. if (window.history.replaceState) {
  69. let urlWithoutSearchParams =
  70. window.location.protocol + '//' + window.location.host + window.location.pathname + window.location.hash;
  71. window.history.replaceState({path: urlWithoutSearchParams}, '', urlWithoutSearchParams);
  72. }
  73. }
  74. // Check for hash change event and fix responsive offset for hash links (e.g. Markdown footnotes).
  75. window.addEventListener('hashchange', scrollToAnchor);
  76. /* ---------------------------------------------------------------------------
  77. * Add smooth scrolling to all links inside the main navbar.
  78. * --------------------------------------------------------------------------- */
  79. $('#navbar-main li.nav-item a.nav-link, .js-scroll').on('click', function (event) {
  80. // Store requested URL hash.
  81. let hash = this.hash;
  82. // If we are on a widget page and the navbar link is to a section on the same page.
  83. if (this.pathname === window.location.pathname && hash && $(hash).length && $('.js-widget-page').length > 0) {
  84. // Prevent default click behavior.
  85. event.preventDefault();
  86. // Use jQuery's animate() method for smooth page scrolling.
  87. // The numerical parameter specifies the time (ms) taken to scroll to the specified hash.
  88. let elementOffset = Math.ceil($(hash).offset().top - getNavBarHeight()); // Round up to highlight right ID!
  89. // Uncomment to debug.
  90. // let scrollTop = $(window).scrollTop();
  91. // let scrollDelta = (elementOffset - scrollTop);
  92. // console.debug('Scroll Delta: ' + scrollDelta);
  93. $('html, body').animate(
  94. {
  95. scrollTop: elementOffset,
  96. },
  97. 800,
  98. );
  99. }
  100. });
  101. /* ---------------------------------------------------------------------------
  102. * Hide mobile collapsable menu on clicking a link.
  103. * --------------------------------------------------------------------------- */
  104. $(document).on('click', '.navbar-collapse.show', function (e) {
  105. //get the <a> element that was clicked, even if the <span> element that is inside the <a> element is e.target
  106. let targetElement = $(e.target).is('a') ? $(e.target) : $(e.target).parent();
  107. if (targetElement.is('a') && targetElement.attr('class') != 'dropdown-toggle') {
  108. $(this).collapse('hide');
  109. }
  110. });
  111. /* ---------------------------------------------------------------------------
  112. * Filter publications.
  113. * --------------------------------------------------------------------------- */
  114. // Active publication filters.
  115. let pubFilters = {};
  116. // Search term.
  117. let searchRegex;
  118. // Filter values (concatenated).
  119. let filterValues;
  120. // Publication container.
  121. let $grid_pubs = $('#container-publications');
  122. // Initialise Isotope publication layout if required.
  123. if ($grid_pubs.length) {
  124. $grid_pubs.isotope({
  125. itemSelector: '.isotope-item',
  126. percentPosition: true,
  127. masonry: {
  128. // Use Bootstrap compatible grid layout.
  129. columnWidth: '.grid-sizer',
  130. },
  131. filter: function () {
  132. let $this = $(this);
  133. let searchResults = searchRegex ? $this.text().match(searchRegex) : true;
  134. let filterResults = filterValues ? $this.is(filterValues) : true;
  135. return searchResults && filterResults;
  136. },
  137. });
  138. // Filter by search term.
  139. let $quickSearch = $('.filter-search').keyup(
  140. debounce(function () {
  141. searchRegex = new RegExp($quickSearch.val(), 'gi');
  142. $grid_pubs.isotope();
  143. }),
  144. );
  145. $('.pub-filters').on('change', function () {
  146. let $this = $(this);
  147. // Get group key.
  148. let filterGroup = $this[0].getAttribute('data-filter-group');
  149. // Set filter for group.
  150. pubFilters[filterGroup] = this.value;
  151. // Combine filters.
  152. filterValues = concatValues(pubFilters);
  153. // Activate filters.
  154. $grid_pubs.isotope();
  155. // If filtering by publication type, update the URL hash to enable direct linking to results.
  156. if (filterGroup === 'pubtype') {
  157. // Set hash URL to current filter.
  158. let url = $(this).val();
  159. if (url.substr(0, 9) === '.pubtype-') {
  160. window.location.hash = url.substr(9);
  161. } else {
  162. window.location.hash = '';
  163. }
  164. }
  165. });
  166. }
  167. // Debounce input to prevent spamming filter requests.
  168. function debounce(fn, threshold) {
  169. let timeout;
  170. threshold = threshold || 100;
  171. return function debounced() {
  172. clearTimeout(timeout);
  173. let args = arguments;
  174. let _this = this;
  175. function delayed() {
  176. fn.apply(_this, args);
  177. }
  178. timeout = setTimeout(delayed, threshold);
  179. };
  180. }
  181. // Flatten object by concatenating values.
  182. function concatValues(obj) {
  183. let value = '';
  184. for (let prop in obj) {
  185. value += obj[prop];
  186. }
  187. return value;
  188. }
  189. // Filter publications according to hash in URL.
  190. function filter_publications() {
  191. // Check for Isotope publication layout.
  192. if (!$grid_pubs.length) return;
  193. let urlHash = window.location.hash.replace('#', '');
  194. let filterValue = '*';
  195. // Check if hash is numeric.
  196. if (urlHash != '' && !isNaN(urlHash)) {
  197. filterValue = '.pubtype-' + urlHash;
  198. }
  199. // Set filter.
  200. let filterGroup = 'pubtype';
  201. pubFilters[filterGroup] = filterValue;
  202. filterValues = concatValues(pubFilters);
  203. // Activate filters.
  204. $grid_pubs.isotope();
  205. // Set selected option.
  206. $('.pubtype-select').val(filterValue);
  207. }
  208. /* ---------------------------------------------------------------------------
  209. * Google Maps or OpenStreetMap via Leaflet.
  210. * --------------------------------------------------------------------------- */
  211. function initMap() {
  212. if ($('#map').length) {
  213. let map_provider = $('#map-provider').val();
  214. let lat = $('#map-lat').val();
  215. let lng = $('#map-lng').val();
  216. let zoom = parseInt($('#map-zoom').val());
  217. let address = $('#map-dir').val();
  218. let api_key = $('#map-api-key').val();
  219. if (map_provider === 'google') {
  220. let map = new GMaps({
  221. div: '#map',
  222. lat: lat,
  223. lng: lng,
  224. zoom: zoom,
  225. zoomControl: true,
  226. zoomControlOpt: {
  227. style: 'SMALL',
  228. position: 'TOP_LEFT',
  229. },
  230. streetViewControl: false,
  231. mapTypeControl: false,
  232. gestureHandling: 'cooperative',
  233. });
  234. map.addMarker({
  235. lat: lat,
  236. lng: lng,
  237. click: function () {
  238. let url = 'https://www.google.com/maps/place/' + encodeURIComponent(address) + '/@' + lat + ',' + lng + '/';
  239. window.open(url, '_blank');
  240. },
  241. title: address,
  242. });
  243. } else {
  244. let map = new L.map('map').setView([lat, lng], zoom);
  245. if (map_provider === 'mapbox' && api_key.length) {
  246. L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}', {
  247. attribution:
  248. 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://mapbox.com">Mapbox</a>',
  249. tileSize: 512,
  250. maxZoom: 18,
  251. zoomOffset: -1,
  252. id: 'mapbox/streets-v11',
  253. accessToken: api_key,
  254. }).addTo(map);
  255. } else {
  256. L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
  257. maxZoom: 19,
  258. attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>',
  259. }).addTo(map);
  260. }
  261. let marker = L.marker([lat, lng]).addTo(map);
  262. let url = lat + ',' + lng + '#map=' + zoom + '/' + lat + '/' + lng + '&layers=N';
  263. marker.bindPopup(
  264. address +
  265. '<p><a href="https://www.openstreetmap.org/directions?engine=osrm_car&route=' +
  266. url +
  267. '">Routing via OpenStreetMap</a></p>',
  268. );
  269. }
  270. }
  271. }
  272. /* ---------------------------------------------------------------------------
  273. * GitHub API.
  274. * --------------------------------------------------------------------------- */
  275. function printLatestRelease(selector, repo) {
  276. if (hugoEnvironment === 'production') {
  277. $.getJSON('https://api.github.com/repos/' + repo + '/tags')
  278. .done(function (json) {
  279. let release = json[0];
  280. $(selector).append(' ' + release.name);
  281. })
  282. .fail(function (jqxhr, textStatus, error) {
  283. let err = textStatus + ', ' + error;
  284. console.log('Request Failed: ' + err);
  285. });
  286. }
  287. }
  288. /* ---------------------------------------------------------------------------
  289. * Toggle search dialog.
  290. * --------------------------------------------------------------------------- */
  291. function toggleSearchDialog() {
  292. if ($('body').hasClass('searching')) {
  293. // Clear search query and hide search modal.
  294. $('[id=search-query]').blur();
  295. $('body').removeClass('searching compensate-for-scrollbar');
  296. // Remove search query params from URL as user has finished searching.
  297. removeQueryParamsFromUrl();
  298. // Prevent fixed positioned elements (e.g. navbar) moving due to scrollbars.
  299. $('#fancybox-style-noscroll').remove();
  300. } else {
  301. // Prevent fixed positioned elements (e.g. navbar) moving due to scrollbars.
  302. if (!$('#fancybox-style-noscroll').length && document.body.scrollHeight > window.innerHeight) {
  303. $('head').append(
  304. '<style id="fancybox-style-noscroll">.compensate-for-scrollbar{margin-right:' +
  305. (window.innerWidth - document.documentElement.clientWidth) +
  306. 'px;}</style>',
  307. );
  308. $('body').addClass('compensate-for-scrollbar');
  309. }
  310. // Show search modal.
  311. $('body').addClass('searching');
  312. $('.search-results').css({opacity: 0, visibility: 'visible'}).animate({opacity: 1}, 200);
  313. $('#search-query').focus();
  314. }
  315. }
  316. /* ---------------------------------------------------------------------------
  317. * Normalize Bootstrap Carousel Slide Heights.
  318. * --------------------------------------------------------------------------- */
  319. function normalizeCarouselSlideHeights() {
  320. $('.carousel').each(function () {
  321. // Get carousel slides.
  322. let items = $('.carousel-item', this);
  323. // Reset all slide heights.
  324. items.css('min-height', 0);
  325. // Normalize all slide heights.
  326. let maxHeight = Math.max.apply(
  327. null,
  328. items
  329. .map(function () {
  330. return $(this).outerHeight();
  331. })
  332. .get(),
  333. );
  334. items.css('min-height', maxHeight + 'px');
  335. });
  336. }
  337. /* ---------------------------------------------------------------------------
  338. * Fix Hugo's Goldmark output and Mermaid code blocks.
  339. * --------------------------------------------------------------------------- */
  340. /**
  341. * Fix Hugo's Goldmark output.
  342. */
  343. function fixHugoOutput() {
  344. // Fix Goldmark table of contents.
  345. // - Must be performed prior to initializing ScrollSpy.
  346. $('#TableOfContents').addClass('nav flex-column');
  347. $('#TableOfContents li').addClass('nav-item');
  348. $('#TableOfContents li a').addClass('nav-link');
  349. // Fix Goldmark task lists (remove bullet points).
  350. $("input[type='checkbox'][disabled]").parents('ul').addClass('task-list');
  351. }
  352. // Get an element's siblings.
  353. function getSiblings(elem) {
  354. // Filter out itself.
  355. return Array.prototype.filter.call(elem.parentNode.children, function (sibling) {
  356. return sibling !== elem;
  357. });
  358. }
  359. /* ---------------------------------------------------------------------------
  360. * On document ready.
  361. * --------------------------------------------------------------------------- */
  362. $(document).ready(function () {
  363. fixHugoOutput();
  364. fixMermaid();
  365. // Initialise code highlighting if enabled for this page.
  366. // Note: this block should be processed after the Mermaid code-->div conversion.
  367. if (codeHighlighting) {
  368. hljs.initHighlighting();
  369. }
  370. // Render theme variation, including any HLJS and Mermaid themes.
  371. let {isDarkTheme, themeMode} = initThemeVariation();
  372. renderThemeVariation(isDarkTheme, themeMode, true);
  373. // Scroll Book page's active menu sidebar link into view.
  374. let child = document.querySelector('.docs-links .active');
  375. let parent = document.querySelector('.docs-links');
  376. if (child && parent) {
  377. scrollParentToChild(parent, child);
  378. }
  379. });
  380. /* ---------------------------------------------------------------------------
  381. * On window loaded.
  382. * --------------------------------------------------------------------------- */
  383. $(window).on('load', function () {
  384. // Re-initialize Scrollspy with dynamic navbar height offset.
  385. fixScrollspy();
  386. // Detect instances of the Portfolio widget.
  387. let isotopeInstances = document.querySelectorAll('.projects-container');
  388. let isotopeInstancesCount = isotopeInstances.length;
  389. // Fix ScrollSpy highlighting previous Book page ToC link for some anchors.
  390. // Check if isotopeInstancesCount>0 as that case performs its own scrollToAnchor.
  391. if (window.location.hash && isotopeInstancesCount === 0) {
  392. scrollToAnchor(decodeURIComponent(window.location.hash), 0);
  393. }
  394. // Scroll Book page's active ToC sidebar link into view.
  395. // Action after calling scrollToAnchor to fix Scrollspy highlighting otherwise wrong link may have active class.
  396. let child = document.querySelector('.docs-toc .nav-link.active');
  397. let parent = document.querySelector('.docs-toc');
  398. if (child && parent) {
  399. scrollParentToChild(parent, child);
  400. }
  401. // Init Isotope Layout Engine for instances of the Portfolio widget.
  402. let isotopeCounter = 0;
  403. isotopeInstances.forEach(function (isotopeInstance, index) {
  404. console.debug(`Loading Isotope instance ${index}`);
  405. // Isotope instance
  406. let iso;
  407. // Get the layout for this Isotope instance
  408. let isoSection = isotopeInstance.closest('section');
  409. let layout = '';
  410. if (isoSection.querySelector('.isotope').classList.contains('js-layout-row')) {
  411. layout = 'fitRows';
  412. } else {
  413. layout = 'masonry';
  414. }
  415. // Get default filter (if any) for this instance
  416. let defaultFilter = isoSection.querySelector('.default-project-filter');
  417. let filterText = '*';
  418. if (defaultFilter !== null) {
  419. filterText = defaultFilter.textContent;
  420. }
  421. console.debug(`Default Isotope filter: ${filterText}`);
  422. // Init Isotope instance once its images have loaded.
  423. imagesLoaded(isotopeInstance, function () {
  424. iso = new Isotope(isotopeInstance, {
  425. itemSelector: '.isotope-item',
  426. layoutMode: layout,
  427. masonry: {
  428. gutter: 20,
  429. },
  430. filter: filterText,
  431. });
  432. // Filter Isotope items when a toolbar filter button is clicked.
  433. let isoFilterButtons = isoSection.querySelectorAll('.project-filters a');
  434. isoFilterButtons.forEach((button) =>
  435. button.addEventListener('click', (e) => {
  436. e.preventDefault();
  437. let selector = button.getAttribute('data-filter');
  438. // Apply filter
  439. console.debug(`Updating Isotope filter to ${selector}`);
  440. iso.arrange({filter: selector});
  441. // Update active toolbar filter button
  442. button.classList.remove('active');
  443. button.classList.add('active');
  444. let buttonSiblings = getSiblings(button);
  445. buttonSiblings.forEach((buttonSibling) => {
  446. buttonSibling.classList.remove('active');
  447. buttonSibling.classList.remove('all');
  448. });
  449. }),
  450. );
  451. // Check if all Isotope instances have loaded.
  452. incrementIsotopeCounter();
  453. });
  454. });
  455. // Hook to perform actions once all Isotope instances have loaded.
  456. function incrementIsotopeCounter() {
  457. isotopeCounter++;
  458. if (isotopeCounter === isotopeInstancesCount) {
  459. console.debug(`All Portfolio Isotope instances loaded.`);
  460. // Once all Isotope instances and their images have loaded, scroll to hash (if set).
  461. // Prevents scrolling to the wrong location due to the dynamic height of Isotope instances.
  462. // Each Isotope instance height is affected by applying filters and loading images.
  463. // Without this logic, the scroll location can appear correct, but actually a few pixels out and hence Scrollspy
  464. // can highlight the wrong nav link.
  465. if (window.location.hash) {
  466. scrollToAnchor(decodeURIComponent(window.location.hash), 0);
  467. }
  468. }
  469. }
  470. // Enable publication filter for publication index page.
  471. if ($('.pub-filters-select')) {
  472. filter_publications();
  473. // Useful for changing hash manually (e.g. in development):
  474. // window.addEventListener('hashchange', filter_publications, false);
  475. }
  476. // Load citation modal on 'Cite' click.
  477. $('.js-cite-modal').click(function (e) {
  478. e.preventDefault();
  479. let filename = $(this).attr('data-filename');
  480. let modal = $('#modal');
  481. modal.find('.modal-body code').load(filename, function (response, status, xhr) {
  482. if (status == 'error') {
  483. let msg = 'Error: ';
  484. $('#modal-error').html(msg + xhr.status + ' ' + xhr.statusText);
  485. } else {
  486. $('.js-download-cite').attr('href', filename);
  487. }
  488. });
  489. modal.modal('show');
  490. });
  491. // Copy citation text on 'Copy' click.
  492. $('.js-copy-cite').click(function (e) {
  493. e.preventDefault();
  494. // Get selection.
  495. let range = document.createRange();
  496. let code_node = document.querySelector('#modal .modal-body');
  497. range.selectNode(code_node);
  498. window.getSelection().addRange(range);
  499. try {
  500. // Execute the copy command.
  501. document.execCommand('copy');
  502. } catch (e) {
  503. console.log('Error: citation copy failed.');
  504. }
  505. // Remove selection.
  506. window.getSelection().removeRange(range);
  507. });
  508. // Initialise Google Maps if necessary.
  509. initMap();
  510. // Print latest version of GitHub projects.
  511. let githubReleaseSelector = '.js-github-release';
  512. if ($(githubReleaseSelector).length > 0) {
  513. printLatestRelease(githubReleaseSelector, $(githubReleaseSelector).data('repo'));
  514. }
  515. // Parse Wowchemy keyboard shortcuts.
  516. document.addEventListener('keyup', (event) => {
  517. if (event.code === 'Escape') {
  518. const body = document.body;
  519. if (body.classList.contains('searching')) {
  520. // Close search dialog.
  521. toggleSearchDialog();
  522. }
  523. }
  524. // Use `key` to check for slash. Otherwise, with `code` we need to check for modifiers.
  525. if (event.key === '/') {
  526. let focusedElement =
  527. (document.hasFocus() &&
  528. document.activeElement !== document.body &&
  529. document.activeElement !== document.documentElement &&
  530. document.activeElement) ||
  531. null;
  532. let isInputFocused = focusedElement instanceof HTMLInputElement || focusedElement instanceof HTMLTextAreaElement;
  533. if (searchEnabled && !isInputFocused) {
  534. // Open search dialog.
  535. event.preventDefault();
  536. toggleSearchDialog();
  537. }
  538. }
  539. });
  540. // Search event handler
  541. // Check that built-in search or Algolia enabled.
  542. if (searchEnabled) {
  543. // On search icon click toggle search dialog.
  544. $('.js-search').click(function (e) {
  545. e.preventDefault();
  546. toggleSearchDialog();
  547. });
  548. }
  549. // Init. author notes (tooltips).
  550. $('[data-toggle="tooltip"]').tooltip();
  551. });
  552. // Theme chooser events.
  553. let linkLight = document.querySelector('.js-set-theme-light');
  554. let linkDark = document.querySelector('.js-set-theme-dark');
  555. let linkAuto = document.querySelector('.js-set-theme-auto');
  556. if (linkLight && linkDark && linkAuto) {
  557. linkLight.addEventListener('click', (event) => {
  558. event.preventDefault();
  559. changeThemeModeClick(0);
  560. });
  561. linkDark.addEventListener('click', (event) => {
  562. event.preventDefault();
  563. changeThemeModeClick(1);
  564. });
  565. linkAuto.addEventListener('click', (event) => {
  566. event.preventDefault();
  567. changeThemeModeClick(2);
  568. });
  569. }
  570. // Media Query events.
  571. // Live update of day/night mode on system preferences update (no refresh required).
  572. // Note: since we listen only for *dark* events, we won't detect other scheme changes such as light to no-preference.
  573. const darkModeMediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
  574. darkModeMediaQuery.addEventListener('change', (event) => {
  575. onMediaQueryListEvent(event);
  576. });
  577. // Normalize Bootstrap carousel slide heights for Slider widget instances.
  578. window.addEventListener('load', normalizeCarouselSlideHeights);
  579. window.addEventListener('resize', normalizeCarouselSlideHeights);
  580. window.addEventListener('orientationchange', normalizeCarouselSlideHeights);
  581. // Automatic main menu dropdowns on mouse over.
  582. $('body').on('mouseenter mouseleave', '.dropdown', function (e) {
  583. var dropdown = $(e.target).closest('.dropdown');
  584. var menu = $('.dropdown-menu', dropdown);
  585. dropdown.addClass('show');
  586. menu.addClass('show');
  587. setTimeout(function () {
  588. dropdown[dropdown.is(':hover') ? 'addClass' : 'removeClass']('show');
  589. menu[dropdown.is(':hover') ? 'addClass' : 'removeClass']('show');
  590. }, 300);
  591. });
  592. // Call `fixScrollspy` when window is resized.
  593. let resizeTimer;
  594. $(window).resize(function () {
  595. clearTimeout(resizeTimer);
  596. resizeTimer = setTimeout(fixScrollspy, 200);
  597. });