academic.js 19 KB

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