academic.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  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. let $grid_pubs = $('#container-publications');
  89. $grid_pubs.isotope({
  90. itemSelector: '.isotope-item',
  91. percentPosition: true,
  92. masonry: {
  93. // Use Bootstrap compatible grid layout.
  94. columnWidth: '.grid-sizer'
  95. }
  96. });
  97. // Active publication filters.
  98. let pubFilters = {};
  99. // Flatten object by concatenating values.
  100. function concatValues( obj ) {
  101. let value = '';
  102. for ( let prop in obj ) {
  103. value += obj[ prop ];
  104. }
  105. return value;
  106. }
  107. $('.pub-filters').on( 'change', function() {
  108. let $this = $(this);
  109. // Get group key.
  110. let filterGroup = $this[0].getAttribute('data-filter-group');
  111. // Set filter for group.
  112. pubFilters[ filterGroup ] = this.value;
  113. // Combine filters.
  114. let filterValues = concatValues( pubFilters );
  115. // Activate filters.
  116. $grid_pubs.isotope({ filter: filterValues });
  117. // If filtering by publication type, update the URL hash to enable direct linking to results.
  118. if (filterGroup == "pubtype") {
  119. // Set hash URL to current filter.
  120. let url = $(this).val();
  121. if (url.substr(0, 9) == '.pubtype-') {
  122. window.location.hash = url.substr(9);
  123. } else {
  124. window.location.hash = '';
  125. }
  126. }
  127. });
  128. // Filter publications according to hash in URL.
  129. function filter_publications() {
  130. let urlHash = window.location.hash.replace('#','');
  131. let filterValue = '*';
  132. // Check if hash is numeric.
  133. if (urlHash != '' && !isNaN(urlHash)) {
  134. filterValue = '.pubtype-' + urlHash;
  135. }
  136. // Set filter.
  137. let filterGroup = 'pubtype';
  138. pubFilters[ filterGroup ] = filterValue;
  139. let filterValues = concatValues( pubFilters );
  140. // Activate filters.
  141. $grid_pubs.isotope({ filter: filterValues });
  142. // Set selected option.
  143. $('.pubtype-select').val(filterValue);
  144. }
  145. /* ---------------------------------------------------------------------------
  146. * Google Maps or OpenStreetMap via Leaflet.
  147. * --------------------------------------------------------------------------- */
  148. function initMap () {
  149. if ($('#map').length) {
  150. let map_provider = $('#map-provider').val();
  151. let lat = $('#map-lat').val();
  152. let lng = $('#map-lng').val();
  153. let zoom = parseInt($('#map-zoom').val());
  154. let address = $('#map-dir').val();
  155. let api_key = $('#map-api-key').val();
  156. if ( map_provider == 1 ) {
  157. let map = new GMaps({
  158. div: '#map',
  159. lat: lat,
  160. lng: lng,
  161. zoom: zoom,
  162. zoomControl: true,
  163. zoomControlOpt: {
  164. style: 'SMALL',
  165. position: 'TOP_LEFT'
  166. },
  167. panControl: false,
  168. streetViewControl: false,
  169. mapTypeControl: false,
  170. overviewMapControl: false,
  171. scrollwheel: true,
  172. draggable: true
  173. });
  174. map.addMarker({
  175. lat: lat,
  176. lng: lng,
  177. click: function (e) {
  178. let url = 'https://www.google.com/maps/place/' + encodeURIComponent(address) + '/@' + lat + ',' + lng +'/';
  179. window.open(url, '_blank')
  180. },
  181. title: address
  182. })
  183. } else {
  184. let map = new L.map('map').setView([lat, lng], zoom);
  185. if ( map_provider == 3 && api_key.length ) {
  186. L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}', {
  187. 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>',
  188. maxZoom: 18,
  189. id: 'mapbox.streets',
  190. accessToken: api_key
  191. }).addTo(map);
  192. } else {
  193. L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
  194. maxZoom: 19,
  195. attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
  196. }).addTo(map);
  197. }
  198. let marker = L.marker([lat, lng]).addTo(map);
  199. let url = lat + ',' + lng +'#map='+ zoom +'/'+ lat +'/'+ lng +'&layers=N';
  200. marker.bindPopup(address + '<p><a href="https://www.openstreetmap.org/directions?engine=osrm_car&route='+ url +'">Routing via OpenStreetMap</a></p>');
  201. }
  202. }
  203. }
  204. /* ---------------------------------------------------------------------------
  205. * GitHub API.
  206. * --------------------------------------------------------------------------- */
  207. function printLatestRelease(selector, repo) {
  208. $.getJSON('https://api.github.com/repos/' + repo + '/tags').done(function (json) {
  209. let release = json[0];
  210. $(selector).append(release.name);
  211. }).fail(function( jqxhr, textStatus, error ) {
  212. let err = textStatus + ", " + error;
  213. console.log( "Request Failed: " + err );
  214. });
  215. }
  216. /* ---------------------------------------------------------------------------
  217. * On window load.
  218. * --------------------------------------------------------------------------- */
  219. $(window).on('load', function() {
  220. if (window.location.hash) {
  221. // When accessing homepage from another page and `#top` hash is set, show top of page (no hash).
  222. if (window.location.hash == "#top") {
  223. window.location.hash = ""
  224. } else if (!$('.projects-container').length) {
  225. // If URL contains a hash and there are no dynamically loaded images on the page,
  226. // immediately scroll to target ID taking into account responsive offset.
  227. // Otherwise, wait for `imagesLoaded()` to complete before scrolling to hash to prevent scrolling to wrong
  228. // location.
  229. scrollToAnchor();
  230. }
  231. }
  232. // Initialize Scrollspy.
  233. let $body = $('body');
  234. $body.scrollspy({offset: navbar_offset });
  235. // Call `fixScrollspy` when window is resized.
  236. let resizeTimer;
  237. $(window).resize(function() {
  238. clearTimeout(resizeTimer);
  239. resizeTimer = setTimeout(fixScrollspy, 200);
  240. });
  241. // Filter projects.
  242. $('.projects-container').each(function(index, container) {
  243. let $container = $(container);
  244. let $section = $container.closest('section');
  245. let layout = 'masonry';
  246. if ($section.find('.isotope').hasClass('js-layout-row')) {
  247. layout = 'fitRows';
  248. }
  249. $container.imagesLoaded(function() {
  250. // Initialize Isotope after all images have loaded.
  251. $container.isotope({
  252. itemSelector: '.isotope-item',
  253. layoutMode: layout,
  254. filter: $section.find('.default-project-filter').text()
  255. });
  256. // Filter items when filter link is clicked.
  257. $section.find('.project-filters a').click(function() {
  258. let selector = $(this).attr('data-filter');
  259. $container.isotope({filter: selector});
  260. $(this).removeClass('active').addClass('active').siblings().removeClass('active all');
  261. return false;
  262. });
  263. // If window hash is set, scroll to hash.
  264. // Placing this within `imagesLoaded` prevents scrolling to the wrong location due to dynamic image loading
  265. // affecting page layout and position of the target anchor ID.
  266. // Note: If there are multiple project widgets on a page, ideally only perform this once after images
  267. // from *all* project widgets have finished loading.
  268. if (window.location.hash) {
  269. scrollToAnchor();
  270. }
  271. });
  272. });
  273. // Enable publication filter for publication index page.
  274. if ($('.pub-filters-select')) {
  275. filter_publications();
  276. // Useful for changing hash manually (e.g. in development):
  277. // window.addEventListener('hashchange', filter_publications, false);
  278. }
  279. // Load citation modal on 'Cite' click.
  280. $('.js-cite-modal').click(function(e) {
  281. e.preventDefault();
  282. let filename = $(this).attr('data-filename');
  283. let modal = $('#modal');
  284. modal.find('.modal-body code').load( filename , function( response, status, xhr ) {
  285. if ( status == 'error' ) {
  286. let msg = "Error: ";
  287. $('#modal-error').html( msg + xhr.status + " " + xhr.statusText );
  288. } else {
  289. $('.js-download-cite').attr('href', filename);
  290. }
  291. });
  292. modal.modal('show');
  293. });
  294. // Copy citation text on 'Copy' click.
  295. $('.js-copy-cite').click(function(e) {
  296. e.preventDefault();
  297. // Get selection.
  298. let range = document.createRange();
  299. let code_node = document.querySelector('#modal .modal-body');
  300. range.selectNode(code_node);
  301. window.getSelection().addRange(range);
  302. try {
  303. // Execute the copy command.
  304. document.execCommand('copy');
  305. } catch(e) {
  306. console.log('Error: citation copy failed.');
  307. }
  308. // Remove selection.
  309. window.getSelection().removeRange(range);
  310. });
  311. // Initialise Google Maps if necessary.
  312. initMap();
  313. // Fix Hugo's inbuilt Table of Contents.
  314. $('#TableOfContents > ul > li > ul').unwrap().unwrap();
  315. // Print latest Academic version if necessary.
  316. if ($('#academic-release').length > 0)
  317. printLatestRelease('#academic-release', $('#academic-release').data('repo'));
  318. // On search icon click toggle search dialog.
  319. $('.js-search').click(function(e) {
  320. e.preventDefault();
  321. if ($('body').hasClass('searching')) {
  322. $('body').removeClass('searching');
  323. } else {
  324. $('body').addClass('searching');
  325. $('.search-results').css({opacity: 0, visibility: 'visible'}).animate({opacity: 1}, 200);
  326. $('#search-query').focus();
  327. }
  328. });
  329. });
  330. })(jQuery);