academic.js 22 KB

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