wowchemy.js 23 KB

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