academic.js 18 KB

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