wowchemy.js 21 KB

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