hugo-academic.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. /*************************************************
  2. * Academic: the personal website framework for Hugo.
  3. * https://github.com/gcushen/hugo-academic
  4. **************************************************/
  5. (function($){
  6. /* ---------------------------------------------------------------------------
  7. * Responsive scrolling for URL hashes.
  8. * --------------------------------------------------------------------------- */
  9. // Dynamically get responsive navigation bar offset.
  10. let $navbar = $('.navbar');
  11. let navbar_offset = $navbar.innerHeight();
  12. /**
  13. * Responsive hash scrolling.
  14. * Check for a URL hash as an anchor.
  15. * If it exists on current page, scroll to it responsively.
  16. * If `target` argument omitted (e.g. after event), assume it's the window's hash.
  17. */
  18. function scrollToAnchor(target) {
  19. // If `target` is undefined or HashChangeEvent object, set it to window's hash.
  20. target = (typeof target === 'undefined' || typeof target === 'object') ? window.location.hash : target;
  21. // Escape colons from IDs, such as those found in Markdown footnote links.
  22. target = target.replace(/:/g, '\\:');
  23. // If target element exists, scroll to it taking into account fixed navigation bar offset.
  24. if($(target).length) {
  25. $('body').addClass('scrolling');
  26. $('html, body').animate({
  27. scrollTop: $(target).offset().top - navbar_offset
  28. }, 600, function () {
  29. $('body').removeClass('scrolling');
  30. });
  31. }
  32. }
  33. // Make Scrollspy responsive.
  34. function fixScrollspy() {
  35. let $body = $('body');
  36. let data = $body.data('bs.scrollspy');
  37. if (data) {
  38. data._config.offset = navbar_offset;
  39. $body.data('bs.scrollspy', data);
  40. $body.scrollspy('refresh');
  41. }
  42. }
  43. // Check for hash change event and fix responsive offset for hash links (e.g. Markdown footnotes).
  44. window.addEventListener("hashchange", scrollToAnchor);
  45. /* ---------------------------------------------------------------------------
  46. * Add smooth scrolling to all links inside the main navbar.
  47. * --------------------------------------------------------------------------- */
  48. $('#navbar-main li.nav-item a.nav-link').on('click', function(event) {
  49. // Store requested URL hash.
  50. let hash = this.hash;
  51. // If we are on the homepage and the navigation bar link is to a homepage section.
  52. if ( hash && $(hash).length && ($("#homepage").length > 0)) {
  53. // Prevent default click behavior.
  54. event.preventDefault();
  55. // Use jQuery's animate() method for smooth page scrolling.
  56. // The numerical parameter specifies the time (ms) taken to scroll to the specified hash.
  57. $('html, body').animate({
  58. scrollTop: $(hash).offset().top - navbar_offset
  59. }, 800);
  60. }
  61. });
  62. /* ---------------------------------------------------------------------------
  63. * Smooth scrolling for Back To Top link.
  64. * --------------------------------------------------------------------------- */
  65. $('#back_to_top').on('click', function(event) {
  66. event.preventDefault();
  67. $('html, body').animate({
  68. 'scrollTop': 0
  69. }, 800, function() {
  70. window.location.hash = "";
  71. });
  72. });
  73. /* ---------------------------------------------------------------------------
  74. * Hide mobile collapsable menu on clicking a link.
  75. * --------------------------------------------------------------------------- */
  76. $(document).on('click', '.navbar-collapse.show', function(e) {
  77. //get the <a> element that was clicked, even if the <span> element that is inside the <a> element is e.target
  78. let targetElement = $(e.target).is('a') ? $(e.target) : $(e.target).parent();
  79. if (targetElement.is('a') && targetElement.attr('class') != 'dropdown-toggle') {
  80. $(this).collapse('hide');
  81. }
  82. });
  83. /* ---------------------------------------------------------------------------
  84. * Filter publications.
  85. * --------------------------------------------------------------------------- */
  86. let $grid_pubs = $('#container-publications');
  87. $grid_pubs.isotope({
  88. itemSelector: '.isotope-item',
  89. percentPosition: true,
  90. masonry: {
  91. // Use Bootstrap compatible grid layout.
  92. columnWidth: '.grid-sizer'
  93. }
  94. });
  95. // Active publication filters.
  96. let pubFilters = {};
  97. // Flatten object by concatenating values.
  98. function concatValues( obj ) {
  99. let value = '';
  100. for ( let prop in obj ) {
  101. value += obj[ prop ];
  102. }
  103. return value;
  104. }
  105. $('.pub-filters').on( 'change', function() {
  106. let $this = $(this);
  107. // Get group key.
  108. let filterGroup = $this[0].getAttribute('data-filter-group');
  109. // Set filter for group.
  110. pubFilters[ filterGroup ] = this.value;
  111. // Combine filters.
  112. let filterValues = concatValues( pubFilters );
  113. // Activate filters.
  114. $grid_pubs.isotope({ filter: filterValues });
  115. // If filtering by publication type, update the URL hash to enable direct linking to results.
  116. if (filterGroup == "pubtype") {
  117. // Set hash URL to current filter.
  118. let url = $(this).val();
  119. if (url.substr(0, 9) == '.pubtype-') {
  120. window.location.hash = url.substr(9);
  121. } else {
  122. window.location.hash = '';
  123. }
  124. }
  125. });
  126. // Filter publications according to hash in URL.
  127. function filter_publications() {
  128. let urlHash = window.location.hash.replace('#','');
  129. let filterValue = '*';
  130. // Check if hash is numeric.
  131. if (urlHash != '' && !isNaN(urlHash)) {
  132. filterValue = '.pubtype-' + urlHash;
  133. }
  134. // Set filter.
  135. let filterGroup = 'pubtype';
  136. pubFilters[ filterGroup ] = filterValue;
  137. let filterValues = concatValues( pubFilters );
  138. // Activate filters.
  139. $grid_pubs.isotope({ filter: filterValues });
  140. // Set selected option.
  141. $('.pubtype-select').val(filterValue);
  142. }
  143. /* ---------------------------------------------------------------------------
  144. * Google Maps or OpenStreetMap via Leaflet.
  145. * --------------------------------------------------------------------------- */
  146. function initMap () {
  147. if ($('#map').length) {
  148. let map_provider = $('#map-provider').val();
  149. let lat = $('#map-lat').val();
  150. let lng = $('#map-lng').val();
  151. let zoom = parseInt($('#map-zoom').val());
  152. let address = $('#map-dir').val();
  153. let api_key = $('#map-api-key').val();
  154. if ( map_provider == 1 ) {
  155. let map = new GMaps({
  156. div: '#map',
  157. lat: lat,
  158. lng: lng,
  159. zoom: zoom,
  160. zoomControl: true,
  161. zoomControlOpt: {
  162. style: 'SMALL',
  163. position: 'TOP_LEFT'
  164. },
  165. panControl: false,
  166. streetViewControl: false,
  167. mapTypeControl: false,
  168. overviewMapControl: false,
  169. scrollwheel: true,
  170. draggable: true
  171. });
  172. map.addMarker({
  173. lat: lat,
  174. lng: lng,
  175. click: function (e) {
  176. let url = 'https://www.google.com/maps/place/' + encodeURIComponent(address) + '/@' + lat + ',' + lng +'/';
  177. window.open(url, '_blank')
  178. },
  179. title: address
  180. })
  181. } else {
  182. let map = new L.map('map').setView([lat, lng], zoom);
  183. if ( map_provider == 3 && api_key.length ) {
  184. L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}', {
  185. 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>',
  186. maxZoom: 18,
  187. id: 'mapbox.streets',
  188. accessToken: api_key
  189. }).addTo(map);
  190. } else {
  191. L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
  192. maxZoom: 19,
  193. attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
  194. }).addTo(map);
  195. }
  196. let marker = L.marker([lat, lng]).addTo(map);
  197. let url = lat + ',' + lng +'#map='+ zoom +'/'+ lat +'/'+ lng +'&layers=N';
  198. marker.bindPopup(address + '<p><a href="https://www.openstreetmap.org/directions?engine=osrm_car&route='+ url +'">Routing via OpenStreetMap</a></p>');
  199. }
  200. }
  201. }
  202. /* ---------------------------------------------------------------------------
  203. * GitHub API.
  204. * --------------------------------------------------------------------------- */
  205. function printLatestRelease(selector, repo) {
  206. $.getJSON('https://api.github.com/repos/' + repo + '/tags').done(function (json) {
  207. let release = json[0];
  208. $(selector).append(release.name);
  209. }).fail(function( jqxhr, textStatus, error ) {
  210. let err = textStatus + ", " + error;
  211. console.log( "Request Failed: " + err );
  212. });
  213. }
  214. /* ---------------------------------------------------------------------------
  215. * On window load.
  216. * --------------------------------------------------------------------------- */
  217. $(window).on('load', function() {
  218. if (window.location.hash) {
  219. // When accessing homepage from another page and `#top` hash is set, show top of page (no hash).
  220. if (window.location.hash == "#top") {
  221. window.location.hash = ""
  222. } else if (!$('.projects-container').length) {
  223. // If URL contains a hash and there are no dynamically loaded images on the page,
  224. // immediately scroll to target ID taking into account responsive offset.
  225. // Otherwise, wait for `imagesLoaded()` to complete before scrolling to hash to prevent scrolling to wrong
  226. // location.
  227. scrollToAnchor();
  228. }
  229. }
  230. // Initialize Scrollspy.
  231. let $body = $('body');
  232. $body.scrollspy({offset: navbar_offset });
  233. // Call `fixScrollspy` when window is resized.
  234. let resizeTimer;
  235. $(window).resize(function() {
  236. clearTimeout(resizeTimer);
  237. resizeTimer = setTimeout(fixScrollspy, 200);
  238. });
  239. // Filter projects.
  240. $('.projects-container').each(function(index, container) {
  241. let $container = $(container);
  242. let $section = $container.closest('section');
  243. let layout = 'masonry';
  244. if ($section.find('.isotope').hasClass('js-layout-row')) {
  245. layout = 'fitRows';
  246. }
  247. $container.imagesLoaded(function() {
  248. // Initialize Isotope after all images have loaded.
  249. $container.isotope({
  250. itemSelector: '.isotope-item',
  251. layoutMode: layout,
  252. filter: $section.find('.default-project-filter').text()
  253. });
  254. // Filter items when filter link is clicked.
  255. $section.find('.project-filters a').click(function() {
  256. let selector = $(this).attr('data-filter');
  257. $container.isotope({filter: selector});
  258. $(this).removeClass('active').addClass('active').siblings().removeClass('active all');
  259. return false;
  260. });
  261. // If window hash is set, scroll to hash.
  262. // Placing this within `imagesLoaded` prevents scrolling to the wrong location due to dynamic image loading
  263. // affecting page layout and position of the target anchor ID.
  264. // Note: If there are multiple project widgets on a page, ideally only perform this once after images
  265. // from *all* project widgets have finished loading.
  266. if (window.location.hash) {
  267. scrollToAnchor();
  268. }
  269. });
  270. });
  271. // Enable publication filter for publication index page.
  272. if ($('.pub-filters-select')) {
  273. filter_publications();
  274. // Useful for changing hash manually (e.g. in development):
  275. // window.addEventListener('hashchange', filter_publications, false);
  276. }
  277. // Load citation modal on 'Cite' click.
  278. $('.js-cite-modal').click(function(e) {
  279. e.preventDefault();
  280. let filename = $(this).attr('data-filename');
  281. let modal = $('#modal');
  282. modal.find('.modal-body code').load( filename , function( response, status, xhr ) {
  283. if ( status == 'error' ) {
  284. let msg = "Error: ";
  285. $('#modal-error').html( msg + xhr.status + " " + xhr.statusText );
  286. } else {
  287. $('.js-download-cite').attr('href', filename);
  288. }
  289. });
  290. modal.modal('show');
  291. });
  292. // Copy citation text on 'Copy' click.
  293. $('.js-copy-cite').click(function(e) {
  294. e.preventDefault();
  295. // Get selection.
  296. let range = document.createRange();
  297. let code_node = document.querySelector('#modal .modal-body');
  298. range.selectNode(code_node);
  299. window.getSelection().addRange(range);
  300. try {
  301. // Execute the copy command.
  302. document.execCommand('copy');
  303. } catch(e) {
  304. console.log('Error: citation copy failed.');
  305. }
  306. // Remove selection.
  307. window.getSelection().removeRange(range);
  308. });
  309. // Initialise Google Maps if necessary.
  310. initMap();
  311. // Fix Hugo's inbuilt Table of Contents.
  312. $('#TableOfContents > ul > li > ul').unwrap().unwrap();
  313. // Print latest Academic version if necessary.
  314. if ($('#academic-release').length > 0)
  315. printLatestRelease('#academic-release', $('#academic-release').data('repo'));
  316. });
  317. })(jQuery);