academic.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562
  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. $('[id=search-query]').blur();
  262. $('body').removeClass('searching');
  263. removeQueryParamsFromUrl();
  264. } else {
  265. $('body').addClass('searching');
  266. $('.search-results').css({opacity: 0, visibility: 'visible'}).animate({opacity: 1}, 200);
  267. $('#search-query').focus();
  268. }
  269. }
  270. /* ---------------------------------------------------------------------------
  271. * Toggle day/night mode.
  272. * --------------------------------------------------------------------------- */
  273. function toggleDarkMode(codeHlEnabled, codeHlLight, codeHlDark, diagramEnabled) {
  274. if ($('body').hasClass('dark')) {
  275. $('body').css({opacity: 0, visibility: 'visible'}).animate({opacity: 1}, 500);
  276. $('body').removeClass('dark');
  277. if (codeHlEnabled) {
  278. codeHlLight.disabled = false;
  279. codeHlDark.disabled = true;
  280. }
  281. $('.js-dark-toggle i').removeClass('fa-sun').addClass('fa-moon');
  282. localStorage.setItem('dark_mode', '0');
  283. if (diagramEnabled) {
  284. // TODO: Investigate Mermaid.js approach to re-render diagrams with new theme without reloading.
  285. location.reload();
  286. }
  287. } else {
  288. $('body').css({opacity: 0, visibility: 'visible'}).animate({opacity: 1}, 500);
  289. $('body').addClass('dark');
  290. if (codeHlEnabled) {
  291. codeHlLight.disabled = true;
  292. codeHlDark.disabled = false;
  293. }
  294. $('.js-dark-toggle i').removeClass('fa-moon').addClass('fa-sun');
  295. localStorage.setItem('dark_mode', '1');
  296. if (diagramEnabled) {
  297. // TODO: Investigate Mermaid.js approach to re-render diagrams with new theme without reloading.
  298. location.reload();
  299. }
  300. }
  301. }
  302. /* ---------------------------------------------------------------------------
  303. * Normalize Bootstrap Carousel Slide Heights.
  304. * --------------------------------------------------------------------------- */
  305. function normalizeCarouselSlideHeights() {
  306. $('.carousel').each(function(){
  307. // Get carousel slides.
  308. let items = $('.carousel-item', this);
  309. // Reset all slide heights.
  310. items.css('min-height', 0);
  311. // Normalize all slide heights.
  312. let maxHeight = Math.max.apply(null, items.map(function(){return $(this).outerHeight()}).get());
  313. items.css('min-height', maxHeight + 'px');
  314. })
  315. }
  316. /* ---------------------------------------------------------------------------
  317. * On document ready.
  318. * --------------------------------------------------------------------------- */
  319. $(document).ready(function() {
  320. // Fix Hugo's auto-generated Table of Contents.
  321. // Must be performed prior to initializing ScrollSpy.
  322. $('#TableOfContents > ul > li > ul').unwrap().unwrap();
  323. $('#TableOfContents').addClass('nav flex-column');
  324. $('#TableOfContents li').addClass('nav-item');
  325. $('#TableOfContents li a').addClass('nav-link');
  326. // Set dark mode if user chose it.
  327. let default_mode = 0;
  328. if ($('body').hasClass('dark')) {
  329. default_mode = 1;
  330. }
  331. let dark_mode = parseInt(localStorage.getItem('dark_mode') || default_mode);
  332. // Is code highlighting enabled in site config?
  333. const codeHlEnabled = $('link[title=hl-light]').length > 0;
  334. const codeHlLight = $('link[title=hl-light]')[0];
  335. const codeHlDark = $('link[title=hl-dark]')[0];
  336. const diagramEnabled = $('script[title=mermaid]').length > 0;
  337. if (dark_mode) {
  338. $('body').addClass('dark');
  339. if (codeHlEnabled) {
  340. codeHlLight.disabled = true;
  341. codeHlDark.disabled = false;
  342. }
  343. if (diagramEnabled) {
  344. mermaid.initialize({ theme: 'dark' });
  345. }
  346. $('.js-dark-toggle i').removeClass('fa-moon').addClass('fa-sun');
  347. } else {
  348. $('body').removeClass('dark');
  349. if (codeHlEnabled) {
  350. codeHlLight.disabled = false;
  351. codeHlDark.disabled = true;
  352. }
  353. if (diagramEnabled) {
  354. mermaid.initialize({ theme: 'default' });
  355. }
  356. $('.js-dark-toggle i').removeClass('fa-sun').addClass('fa-moon');
  357. }
  358. // Toggle day/night mode.
  359. $('.js-dark-toggle').click(function(e) {
  360. e.preventDefault();
  361. toggleDarkMode(codeHlEnabled, codeHlLight, codeHlDark, diagramEnabled);
  362. });
  363. });
  364. /* ---------------------------------------------------------------------------
  365. * On window loaded.
  366. * --------------------------------------------------------------------------- */
  367. $(window).on('load', function() {
  368. if (window.location.hash) {
  369. // When accessing homepage from another page and `#top` hash is set, show top of page (no hash).
  370. if (window.location.hash == "#top") {
  371. window.location.hash = ""
  372. } else if (!$('.projects-container').length) {
  373. // If URL contains a hash and there are no dynamically loaded images on the page,
  374. // immediately scroll to target ID taking into account responsive offset.
  375. // Otherwise, wait for `imagesLoaded()` to complete before scrolling to hash to prevent scrolling to wrong
  376. // location.
  377. scrollToAnchor();
  378. }
  379. }
  380. // Initialize Scrollspy.
  381. let $body = $('body');
  382. $body.scrollspy({offset: navbar_offset });
  383. // Call `fixScrollspy` when window is resized.
  384. let resizeTimer;
  385. $(window).resize(function() {
  386. clearTimeout(resizeTimer);
  387. resizeTimer = setTimeout(fixScrollspy, 200);
  388. });
  389. // Filter projects.
  390. $('.projects-container').each(function(index, container) {
  391. let $container = $(container);
  392. let $section = $container.closest('section');
  393. let layout;
  394. if ($section.find('.isotope').hasClass('js-layout-row')) {
  395. layout = 'fitRows';
  396. } else {
  397. layout = 'masonry';
  398. }
  399. $container.imagesLoaded(function() {
  400. // Initialize Isotope after all images have loaded.
  401. $container.isotope({
  402. itemSelector: '.isotope-item',
  403. layoutMode: layout,
  404. masonry: {
  405. gutter: 20
  406. },
  407. filter: $section.find('.default-project-filter').text()
  408. });
  409. // Filter items when filter link is clicked.
  410. $section.find('.project-filters a').click(function() {
  411. let selector = $(this).attr('data-filter');
  412. $container.isotope({filter: selector});
  413. $(this).removeClass('active').addClass('active').siblings().removeClass('active all');
  414. return false;
  415. });
  416. // If window hash is set, scroll to hash.
  417. // Placing this within `imagesLoaded` prevents scrolling to the wrong location due to dynamic image loading
  418. // affecting page layout and position of the target anchor ID.
  419. // Note: If there are multiple project widgets on a page, ideally only perform this once after images
  420. // from *all* project widgets have finished loading.
  421. if (window.location.hash) {
  422. scrollToAnchor();
  423. }
  424. });
  425. });
  426. // Enable publication filter for publication index page.
  427. if ($('.pub-filters-select')) {
  428. filter_publications();
  429. // Useful for changing hash manually (e.g. in development):
  430. // window.addEventListener('hashchange', filter_publications, false);
  431. }
  432. // Load citation modal on 'Cite' click.
  433. $('.js-cite-modal').click(function(e) {
  434. e.preventDefault();
  435. let filename = $(this).attr('data-filename');
  436. let modal = $('#modal');
  437. modal.find('.modal-body code').load( filename , function( response, status, xhr ) {
  438. if ( status == 'error' ) {
  439. let msg = "Error: ";
  440. $('#modal-error').html( msg + xhr.status + " " + xhr.statusText );
  441. } else {
  442. $('.js-download-cite').attr('href', filename);
  443. }
  444. });
  445. modal.modal('show');
  446. });
  447. // Copy citation text on 'Copy' click.
  448. $('.js-copy-cite').click(function(e) {
  449. e.preventDefault();
  450. // Get selection.
  451. let range = document.createRange();
  452. let code_node = document.querySelector('#modal .modal-body');
  453. range.selectNode(code_node);
  454. window.getSelection().addRange(range);
  455. try {
  456. // Execute the copy command.
  457. document.execCommand('copy');
  458. } catch(e) {
  459. console.log('Error: citation copy failed.');
  460. }
  461. // Remove selection.
  462. window.getSelection().removeRange(range);
  463. });
  464. // Initialise Google Maps if necessary.
  465. initMap();
  466. // Print latest version of GitHub projects.
  467. let githubReleaseSelector = '.js-github-release';
  468. if ($(githubReleaseSelector).length > 0)
  469. printLatestRelease(githubReleaseSelector, $(githubReleaseSelector).data('repo'));
  470. // On search icon click toggle search dialog.
  471. $('.js-search').click(function(e) {
  472. e.preventDefault();
  473. toggleSearchDialog();
  474. });
  475. $(document).on('keydown', function(e){
  476. if (e.which == 27) {
  477. // `Esc` key pressed.
  478. if ($('body').hasClass('searching')) {
  479. toggleSearchDialog();
  480. }
  481. } else if (e.which == 191 && e.shiftKey == false && !$('input,textarea').is(':focus')) {
  482. // `/` key pressed outside of text input.
  483. e.preventDefault();
  484. toggleSearchDialog();
  485. }
  486. });
  487. });
  488. // Normalize Bootstrap carousel slide heights.
  489. $(window).on('load resize orientationchange', normalizeCarouselSlideHeights);
  490. })(jQuery);