academic.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  1. /*************************************************
  2. * Academic
  3. * https://github.com/gcushen/hugo-academic
  4. *
  5. * Core JS functions and initialization.
  6. **************************************************/
  7. (function($){
  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');
  14. let navbar_offset = $navbar.innerHeight();
  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. // Escape special chars from IDs, such as colons found in Markdown footnote links.
  29. target = '#' + $.escapeSelector(target.substring(1)); // Previously, `target = target.replace(/:/g, '\\:');`
  30. // If target element exists, scroll to it taking into account fixed navigation bar offset.
  31. if($(target).length) {
  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.warn('Cannot scroll to '+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').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. * Smooth scrolling for Back To Top link.
  85. * --------------------------------------------------------------------------- */
  86. $('#back_to_top').on('click', function(event) {
  87. event.preventDefault();
  88. $('html, body').animate({
  89. 'scrollTop': 0
  90. }, 800, function() {
  91. window.location.hash = "";
  92. });
  93. });
  94. /* ---------------------------------------------------------------------------
  95. * Hide mobile collapsable menu on clicking a link.
  96. * --------------------------------------------------------------------------- */
  97. $(document).on('click', '.navbar-collapse.show', function(e) {
  98. //get the <a> element that was clicked, even if the <span> element that is inside the <a> element is e.target
  99. let targetElement = $(e.target).is('a') ? $(e.target) : $(e.target).parent();
  100. if (targetElement.is('a') && targetElement.attr('class') != 'dropdown-toggle') {
  101. $(this).collapse('hide');
  102. }
  103. });
  104. /* ---------------------------------------------------------------------------
  105. * Filter publications.
  106. * --------------------------------------------------------------------------- */
  107. // Active publication filters.
  108. let pubFilters = {};
  109. // Search term.
  110. let searchRegex;
  111. // Filter values (concatenated).
  112. let filterValues;
  113. // Publication container.
  114. let $grid_pubs = $('#container-publications');
  115. // Initialise Isotope.
  116. $grid_pubs.isotope({
  117. itemSelector: '.isotope-item',
  118. percentPosition: true,
  119. masonry: {
  120. // Use Bootstrap compatible grid layout.
  121. columnWidth: '.grid-sizer'
  122. },
  123. filter: function() {
  124. let $this = $(this);
  125. let searchResults = searchRegex ? $this.text().match( searchRegex ) : true;
  126. let filterResults = filterValues ? $this.is( filterValues ) : true;
  127. return searchResults && filterResults;
  128. }
  129. });
  130. // Filter by search term.
  131. let $quickSearch = $('.filter-search').keyup( debounce( function() {
  132. searchRegex = new RegExp( $quickSearch.val(), 'gi' );
  133. $grid_pubs.isotope();
  134. }) );
  135. // Debounce input to prevent spamming filter requests.
  136. function debounce( fn, threshold ) {
  137. let timeout;
  138. threshold = threshold || 100;
  139. return function debounced() {
  140. clearTimeout( timeout );
  141. let args = arguments;
  142. let _this = this;
  143. function delayed() {
  144. fn.apply( _this, args );
  145. }
  146. timeout = setTimeout( delayed, threshold );
  147. };
  148. }
  149. // Flatten object by concatenating values.
  150. function concatValues( obj ) {
  151. let value = '';
  152. for ( let prop in obj ) {
  153. value += obj[ prop ];
  154. }
  155. return value;
  156. }
  157. $('.pub-filters').on( 'change', function() {
  158. let $this = $(this);
  159. // Get group key.
  160. let filterGroup = $this[0].getAttribute('data-filter-group');
  161. // Set filter for group.
  162. pubFilters[ filterGroup ] = this.value;
  163. // Combine filters.
  164. filterValues = concatValues( pubFilters );
  165. // Activate filters.
  166. $grid_pubs.isotope();
  167. // If filtering by publication type, update the URL hash to enable direct linking to results.
  168. if (filterGroup == "pubtype") {
  169. // Set hash URL to current filter.
  170. let url = $(this).val();
  171. if (url.substr(0, 9) == '.pubtype-') {
  172. window.location.hash = url.substr(9);
  173. } else {
  174. window.location.hash = '';
  175. }
  176. }
  177. });
  178. // Filter publications according to hash in URL.
  179. function filter_publications() {
  180. let urlHash = window.location.hash.replace('#','');
  181. let filterValue = '*';
  182. // Check if hash is numeric.
  183. if (urlHash != '' && !isNaN(urlHash)) {
  184. filterValue = '.pubtype-' + urlHash;
  185. }
  186. // Set filter.
  187. let filterGroup = 'pubtype';
  188. pubFilters[ filterGroup ] = filterValue;
  189. filterValues = concatValues( pubFilters );
  190. // Activate filters.
  191. $grid_pubs.isotope();
  192. // Set selected option.
  193. $('.pubtype-select').val(filterValue);
  194. }
  195. /* ---------------------------------------------------------------------------
  196. * Google Maps or OpenStreetMap via Leaflet.
  197. * --------------------------------------------------------------------------- */
  198. function initMap () {
  199. if ($('#map').length) {
  200. let map_provider = $('#map-provider').val();
  201. let lat = $('#map-lat').val();
  202. let lng = $('#map-lng').val();
  203. let zoom = parseInt($('#map-zoom').val());
  204. let address = $('#map-dir').val();
  205. let api_key = $('#map-api-key').val();
  206. if ( map_provider == 1 ) {
  207. let map = new GMaps({
  208. div: '#map',
  209. lat: lat,
  210. lng: lng,
  211. zoom: zoom,
  212. zoomControl: true,
  213. zoomControlOpt: {
  214. style: 'SMALL',
  215. position: 'TOP_LEFT'
  216. },
  217. panControl: false,
  218. streetViewControl: false,
  219. mapTypeControl: false,
  220. overviewMapControl: false,
  221. scrollwheel: true,
  222. draggable: true
  223. });
  224. map.addMarker({
  225. lat: lat,
  226. lng: lng,
  227. click: function (e) {
  228. let url = 'https://www.google.com/maps/place/' + encodeURIComponent(address) + '/@' + lat + ',' + lng +'/';
  229. window.open(url, '_blank')
  230. },
  231. title: address
  232. })
  233. } else {
  234. let map = new L.map('map').setView([lat, lng], zoom);
  235. if ( map_provider == 3 && api_key.length ) {
  236. L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}', {
  237. 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>',
  238. maxZoom: 18,
  239. id: 'mapbox.streets',
  240. accessToken: api_key
  241. }).addTo(map);
  242. } else {
  243. L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
  244. maxZoom: 19,
  245. attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
  246. }).addTo(map);
  247. }
  248. let marker = L.marker([lat, lng]).addTo(map);
  249. let url = lat + ',' + lng +'#map='+ zoom +'/'+ lat +'/'+ lng +'&layers=N';
  250. marker.bindPopup(address + '<p><a href="https://www.openstreetmap.org/directions?engine=osrm_car&route='+ url +'">Routing via OpenStreetMap</a></p>');
  251. }
  252. }
  253. }
  254. /* ---------------------------------------------------------------------------
  255. * GitHub API.
  256. * --------------------------------------------------------------------------- */
  257. function printLatestRelease(selector, repo) {
  258. $.getJSON('https://api.github.com/repos/' + repo + '/tags').done(function (json) {
  259. let release = json[0];
  260. $(selector).append(' '+release.name);
  261. }).fail(function( jqxhr, textStatus, error ) {
  262. let err = textStatus + ", " + error;
  263. console.log( "Request Failed: " + err );
  264. });
  265. }
  266. /* ---------------------------------------------------------------------------
  267. * Toggle search dialog.
  268. * --------------------------------------------------------------------------- */
  269. function toggleSearchDialog() {
  270. if ($('body').hasClass('searching')) {
  271. // Clear search query and hide search modal.
  272. $('[id=search-query]').blur();
  273. $('body').removeClass('searching compensate-for-scrollbar');
  274. // Remove search query params from URL as user has finished searching.
  275. removeQueryParamsFromUrl();
  276. // Prevent fixed positioned elements (e.g. navbar) moving due to scrollbars.
  277. $('#fancybox-style-noscroll').remove();
  278. } else {
  279. // Prevent fixed positioned elements (e.g. navbar) moving due to scrollbars.
  280. if ( !$('#fancybox-style-noscroll').length && document.body.scrollHeight > window.innerHeight ) {
  281. $('head').append(
  282. '<style id="fancybox-style-noscroll">.compensate-for-scrollbar{margin-right:' +
  283. (window.innerWidth - document.documentElement.clientWidth) +
  284. 'px;}</style>'
  285. );
  286. $('body').addClass('compensate-for-scrollbar');
  287. }
  288. // Show search modal.
  289. $('body').addClass('searching');
  290. $('.search-results').css({opacity: 0, visibility: 'visible'}).animate({opacity: 1}, 200);
  291. $('#search-query').focus();
  292. }
  293. }
  294. /* ---------------------------------------------------------------------------
  295. * Toggle day/night mode.
  296. * --------------------------------------------------------------------------- */
  297. function toggleDarkMode(codeHlEnabled, codeHlLight, codeHlDark, diagramEnabled) {
  298. if ($('body').hasClass('dark')) {
  299. $('body').css({opacity: 0, visibility: 'visible'}).animate({opacity: 1}, 500);
  300. $('body').removeClass('dark');
  301. if (codeHlEnabled) {
  302. codeHlLight.disabled = false;
  303. codeHlDark.disabled = true;
  304. }
  305. $('.js-dark-toggle i').removeClass('fa-sun').addClass('fa-moon');
  306. localStorage.setItem('dark_mode', '0');
  307. if (diagramEnabled) {
  308. // TODO: Investigate Mermaid.js approach to re-render diagrams with new theme without reloading.
  309. location.reload();
  310. }
  311. } else {
  312. $('body').css({opacity: 0, visibility: 'visible'}).animate({opacity: 1}, 500);
  313. $('body').addClass('dark');
  314. if (codeHlEnabled) {
  315. codeHlLight.disabled = true;
  316. codeHlDark.disabled = false;
  317. }
  318. $('.js-dark-toggle i').removeClass('fa-moon').addClass('fa-sun');
  319. localStorage.setItem('dark_mode', '1');
  320. if (diagramEnabled) {
  321. // TODO: Investigate Mermaid.js approach to re-render diagrams with new theme without reloading.
  322. location.reload();
  323. }
  324. }
  325. }
  326. /* ---------------------------------------------------------------------------
  327. * Normalize Bootstrap Carousel Slide Heights.
  328. * --------------------------------------------------------------------------- */
  329. function normalizeCarouselSlideHeights() {
  330. $('.carousel').each(function(){
  331. // Get carousel slides.
  332. let items = $('.carousel-item', this);
  333. // Reset all slide heights.
  334. items.css('min-height', 0);
  335. // Normalize all slide heights.
  336. let maxHeight = Math.max.apply(null, items.map(function(){return $(this).outerHeight()}).get());
  337. items.css('min-height', maxHeight + 'px');
  338. })
  339. }
  340. /* ---------------------------------------------------------------------------
  341. * On document ready.
  342. * --------------------------------------------------------------------------- */
  343. $(document).ready(function() {
  344. // Fix Hugo's auto-generated Table of Contents.
  345. // Must be performed prior to initializing ScrollSpy.
  346. $('#TableOfContents > ul > li > ul').unwrap().unwrap();
  347. $('#TableOfContents').addClass('nav flex-column');
  348. $('#TableOfContents li').addClass('nav-item');
  349. $('#TableOfContents li a').addClass('nav-link');
  350. // Fix Mmark task lists (remove bullet points).
  351. $("input[type='checkbox'][disabled]").parents('ul').addClass('task-list');
  352. // Fix Mermaid.js clash with Highlight.js.
  353. let mermaids = [];
  354. [].push.apply(mermaids, document.getElementsByClassName('language-mermaid'));
  355. for (i = 0; i < mermaids.length; i++) {
  356. $(mermaids[i]).unwrap('pre'); // Remove <pre> wrapper.
  357. $(mermaids[i]).replaceWith(function(){
  358. // Convert <code> block to <div> and add `mermaid` class so that Mermaid will parse it.
  359. return $("<div />").append($(this).contents()).addClass('mermaid');
  360. });
  361. }
  362. // Get theme variation (day/night).
  363. let defaultThemeVariation;
  364. if ($('body').hasClass('dark')) {
  365. // The `color_theme` of the site is dark.
  366. defaultThemeVariation = 1;
  367. } else if ($('.js-dark-toggle').length && window.matchMedia('(prefers-color-scheme: dark)').matches) {
  368. // The visitor prefers dark themes and switching to the dark variation is allowed by admin.
  369. defaultThemeVariation = 1;
  370. } else {
  371. // Default to day (light) theme.
  372. defaultThemeVariation = 0;
  373. }
  374. let dark_mode = parseInt(localStorage.getItem('dark_mode') || defaultThemeVariation);
  375. // Is code highlighting enabled in site config?
  376. const codeHlEnabled = $('link[title=hl-light]').length > 0;
  377. const codeHlLight = $('link[title=hl-light]')[0];
  378. const codeHlDark = $('link[title=hl-dark]')[0];
  379. const diagramEnabled = $('script[title=mermaid]').length > 0;
  380. if (dark_mode) {
  381. $('body').addClass('dark');
  382. if (codeHlEnabled) {
  383. codeHlLight.disabled = true;
  384. codeHlDark.disabled = false;
  385. }
  386. if (diagramEnabled) {
  387. mermaid.initialize({ theme: 'dark' });
  388. }
  389. $('.js-dark-toggle i').removeClass('fa-moon').addClass('fa-sun');
  390. } else {
  391. $('body').removeClass('dark');
  392. if (codeHlEnabled) {
  393. codeHlLight.disabled = false;
  394. codeHlDark.disabled = true;
  395. }
  396. if (diagramEnabled) {
  397. mermaid.initialize({ theme: 'default' });
  398. }
  399. $('.js-dark-toggle i').removeClass('fa-sun').addClass('fa-moon');
  400. }
  401. // Toggle day/night mode.
  402. $('.js-dark-toggle').click(function(e) {
  403. e.preventDefault();
  404. toggleDarkMode(codeHlEnabled, codeHlLight, codeHlDark, diagramEnabled);
  405. });
  406. });
  407. /* ---------------------------------------------------------------------------
  408. * On window loaded.
  409. * --------------------------------------------------------------------------- */
  410. $(window).on('load', function() {
  411. // Re-initialize Scrollspy with dynamic navbar height offset.
  412. fixScrollspy();
  413. if (window.location.hash) {
  414. // When accessing homepage from another page and `#top` hash is set, show top of page (no hash).
  415. if (window.location.hash == "#top") {
  416. window.location.hash = ""
  417. } else if (!$('.projects-container').length) {
  418. // If URL contains a hash and there are no dynamically loaded images on the page,
  419. // immediately scroll to target ID taking into account responsive offset.
  420. // Otherwise, wait for `imagesLoaded()` to complete before scrolling to hash to prevent scrolling to wrong
  421. // location.
  422. scrollToAnchor();
  423. }
  424. }
  425. // Call `fixScrollspy` when window is resized.
  426. let resizeTimer;
  427. $(window).resize(function() {
  428. clearTimeout(resizeTimer);
  429. resizeTimer = setTimeout(fixScrollspy, 200);
  430. });
  431. // Filter projects.
  432. $('.projects-container').each(function(index, container) {
  433. let $container = $(container);
  434. let $section = $container.closest('section');
  435. let layout;
  436. if ($section.find('.isotope').hasClass('js-layout-row')) {
  437. layout = 'fitRows';
  438. } else {
  439. layout = 'masonry';
  440. }
  441. $container.imagesLoaded(function() {
  442. // Initialize Isotope after all images have loaded.
  443. $container.isotope({
  444. itemSelector: '.isotope-item',
  445. layoutMode: layout,
  446. masonry: {
  447. gutter: 20
  448. },
  449. filter: $section.find('.default-project-filter').text()
  450. });
  451. // Filter items when filter link is clicked.
  452. $section.find('.project-filters a').click(function() {
  453. let selector = $(this).attr('data-filter');
  454. $container.isotope({filter: selector});
  455. $(this).removeClass('active').addClass('active').siblings().removeClass('active all');
  456. return false;
  457. });
  458. // If window hash is set, scroll to hash.
  459. // Placing this within `imagesLoaded` prevents scrolling to the wrong location due to dynamic image loading
  460. // affecting page layout and position of the target anchor ID.
  461. // Note: If there are multiple project widgets on a page, ideally only perform this once after images
  462. // from *all* project widgets have finished loading.
  463. if (window.location.hash) {
  464. scrollToAnchor();
  465. }
  466. });
  467. });
  468. // Enable publication filter for publication index page.
  469. if ($('.pub-filters-select')) {
  470. filter_publications();
  471. // Useful for changing hash manually (e.g. in development):
  472. // window.addEventListener('hashchange', filter_publications, false);
  473. }
  474. // Load citation modal on 'Cite' click.
  475. $('.js-cite-modal').click(function(e) {
  476. e.preventDefault();
  477. let filename = $(this).attr('data-filename');
  478. let modal = $('#modal');
  479. modal.find('.modal-body code').load( filename , function( response, status, xhr ) {
  480. if ( status == 'error' ) {
  481. let msg = "Error: ";
  482. $('#modal-error').html( msg + xhr.status + " " + xhr.statusText );
  483. } else {
  484. $('.js-download-cite').attr('href', filename);
  485. }
  486. });
  487. modal.modal('show');
  488. });
  489. // Copy citation text on 'Copy' click.
  490. $('.js-copy-cite').click(function(e) {
  491. e.preventDefault();
  492. // Get selection.
  493. let range = document.createRange();
  494. let code_node = document.querySelector('#modal .modal-body');
  495. range.selectNode(code_node);
  496. window.getSelection().addRange(range);
  497. try {
  498. // Execute the copy command.
  499. document.execCommand('copy');
  500. } catch(e) {
  501. console.log('Error: citation copy failed.');
  502. }
  503. // Remove selection.
  504. window.getSelection().removeRange(range);
  505. });
  506. // Initialise Google Maps if necessary.
  507. initMap();
  508. // Print latest version of GitHub projects.
  509. let githubReleaseSelector = '.js-github-release';
  510. if ($(githubReleaseSelector).length > 0)
  511. printLatestRelease(githubReleaseSelector, $(githubReleaseSelector).data('repo'));
  512. // On search icon click toggle search dialog.
  513. $('.js-search').click(function(e) {
  514. e.preventDefault();
  515. toggleSearchDialog();
  516. });
  517. $(document).on('keydown', function(e){
  518. if (e.which == 27) {
  519. // `Esc` key pressed.
  520. if ($('body').hasClass('searching')) {
  521. toggleSearchDialog();
  522. }
  523. } else if (e.which == 191 && e.shiftKey == false && !$('input,textarea').is(':focus')) {
  524. // `/` key pressed outside of text input.
  525. e.preventDefault();
  526. toggleSearchDialog();
  527. }
  528. });
  529. });
  530. // Normalize Bootstrap carousel slide heights.
  531. $(window).on('load resize orientationchange', normalizeCarouselSlideHeights);
  532. })(jQuery);