wowchemy.js 20 KB

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