academic.js 20 KB

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