academic.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  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. * Toggle search dialog.
  218. * --------------------------------------------------------------------------- */
  219. function toggleSearchDialog() {
  220. if ($('body').hasClass('searching')) {
  221. $('[id=search-query]').blur();
  222. $('body').removeClass('searching');
  223. } else {
  224. $('body').addClass('searching');
  225. $('.search-results').css({opacity: 0, visibility: 'visible'}).animate({opacity: 1}, 200);
  226. $('#search-query').focus();
  227. }
  228. }
  229. /* ---------------------------------------------------------------------------
  230. * Toggle day/night mode.
  231. * --------------------------------------------------------------------------- */
  232. function toggleDarkMode() {
  233. if ($('body').hasClass('dark')) {
  234. $('body').css({opacity: 0, visibility: 'visible'}).animate({opacity: 1}, 500);
  235. $('body').removeClass('dark');
  236. $('link[title=hl-light]')[0].disabled = false;
  237. $('link[title=hl-dark]')[0].disabled = true;
  238. $('.js-dark-toggle i').removeClass('fa-sun');
  239. $('.js-dark-toggle i').addClass('fa-moon');
  240. localStorage.setItem('dark_mode', '0');
  241. } else {
  242. $('body').css({opacity: 0, visibility: 'visible'}).animate({opacity: 1}, 500);
  243. $('body').addClass('dark');
  244. $('link[title=hl-light]')[0].disabled = true;
  245. $('link[title=hl-dark]')[0].disabled = false;
  246. $('.js-dark-toggle i').removeClass('fa-moon');
  247. $('.js-dark-toggle i').addClass('fa-sun');
  248. localStorage.setItem('dark_mode', '1');
  249. }
  250. }
  251. /* ---------------------------------------------------------------------------
  252. * On document ready.
  253. * --------------------------------------------------------------------------- */
  254. $(document).ready(function() {
  255. // Set dark mode if user chose it.
  256. let default_mode = 0;
  257. if ($('body').hasClass('dark')) {
  258. default_mode = 1;
  259. }
  260. let dark_mode = parseInt(localStorage.getItem('dark_mode') || default_mode);
  261. if (dark_mode) {
  262. $('body').addClass('dark');
  263. $('link[title=hl-light]')[0].disabled = true;
  264. $('link[title=hl-dark]')[0].disabled = false;
  265. $('.js-dark-toggle i').removeClass('fa-moon');
  266. $('.js-dark-toggle i').addClass('fa-sun');
  267. } else {
  268. $('body').removeClass('dark');
  269. $('link[title=hl-light]')[0].disabled = false;
  270. $('link[title=hl-dark]')[0].disabled = true;
  271. $('.js-dark-toggle i').removeClass('fa-sun');
  272. $('.js-dark-toggle i').addClass('fa-moon');
  273. }
  274. });
  275. /* ---------------------------------------------------------------------------
  276. * On window loaded.
  277. * --------------------------------------------------------------------------- */
  278. $(window).on('load', function() {
  279. if (window.location.hash) {
  280. // When accessing homepage from another page and `#top` hash is set, show top of page (no hash).
  281. if (window.location.hash == "#top") {
  282. window.location.hash = ""
  283. } else if (!$('.projects-container').length) {
  284. // If URL contains a hash and there are no dynamically loaded images on the page,
  285. // immediately scroll to target ID taking into account responsive offset.
  286. // Otherwise, wait for `imagesLoaded()` to complete before scrolling to hash to prevent scrolling to wrong
  287. // location.
  288. scrollToAnchor();
  289. }
  290. }
  291. // Initialize Scrollspy.
  292. let $body = $('body');
  293. $body.scrollspy({offset: navbar_offset });
  294. // Call `fixScrollspy` when window is resized.
  295. let resizeTimer;
  296. $(window).resize(function() {
  297. clearTimeout(resizeTimer);
  298. resizeTimer = setTimeout(fixScrollspy, 200);
  299. });
  300. // Filter projects.
  301. $('.projects-container').each(function(index, container) {
  302. let $container = $(container);
  303. let $section = $container.closest('section');
  304. let layout = 'masonry';
  305. if ($section.find('.isotope').hasClass('js-layout-row')) {
  306. layout = 'fitRows';
  307. }
  308. $container.imagesLoaded(function() {
  309. // Initialize Isotope after all images have loaded.
  310. $container.isotope({
  311. itemSelector: '.isotope-item',
  312. layoutMode: layout,
  313. filter: $section.find('.default-project-filter').text()
  314. });
  315. // Filter items when filter link is clicked.
  316. $section.find('.project-filters a').click(function() {
  317. let selector = $(this).attr('data-filter');
  318. $container.isotope({filter: selector});
  319. $(this).removeClass('active').addClass('active').siblings().removeClass('active all');
  320. return false;
  321. });
  322. // If window hash is set, scroll to hash.
  323. // Placing this within `imagesLoaded` prevents scrolling to the wrong location due to dynamic image loading
  324. // affecting page layout and position of the target anchor ID.
  325. // Note: If there are multiple project widgets on a page, ideally only perform this once after images
  326. // from *all* project widgets have finished loading.
  327. if (window.location.hash) {
  328. scrollToAnchor();
  329. }
  330. });
  331. });
  332. // Enable publication filter for publication index page.
  333. if ($('.pub-filters-select')) {
  334. filter_publications();
  335. // Useful for changing hash manually (e.g. in development):
  336. // window.addEventListener('hashchange', filter_publications, false);
  337. }
  338. // Load citation modal on 'Cite' click.
  339. $('.js-cite-modal').click(function(e) {
  340. e.preventDefault();
  341. let filename = $(this).attr('data-filename');
  342. let modal = $('#modal');
  343. modal.find('.modal-body code').load( filename , function( response, status, xhr ) {
  344. if ( status == 'error' ) {
  345. let msg = "Error: ";
  346. $('#modal-error').html( msg + xhr.status + " " + xhr.statusText );
  347. } else {
  348. $('.js-download-cite').attr('href', filename);
  349. }
  350. });
  351. modal.modal('show');
  352. });
  353. // Copy citation text on 'Copy' click.
  354. $('.js-copy-cite').click(function(e) {
  355. e.preventDefault();
  356. // Get selection.
  357. let range = document.createRange();
  358. let code_node = document.querySelector('#modal .modal-body');
  359. range.selectNode(code_node);
  360. window.getSelection().addRange(range);
  361. try {
  362. // Execute the copy command.
  363. document.execCommand('copy');
  364. } catch(e) {
  365. console.log('Error: citation copy failed.');
  366. }
  367. // Remove selection.
  368. window.getSelection().removeRange(range);
  369. });
  370. // Initialise Google Maps if necessary.
  371. initMap();
  372. // Fix Hugo's inbuilt Table of Contents.
  373. $('#TableOfContents > ul > li > ul').unwrap().unwrap();
  374. // Print latest Academic version if necessary.
  375. if ($('#academic-release').length > 0)
  376. printLatestRelease('#academic-release', $('#academic-release').data('repo'));
  377. // On search icon click toggle search dialog.
  378. $('.js-search').click(function(e) {
  379. e.preventDefault();
  380. toggleSearchDialog();
  381. });
  382. $(document).on('keydown', function(e){
  383. if (e.which == 27) {
  384. // `Esc` key pressed.
  385. if ($('body').hasClass('searching')) {
  386. toggleSearchDialog();
  387. }
  388. } else if (e.which == 191 && e.shiftKey == false && !$('input,textarea').is(':focus')) {
  389. // `/` key pressed outside of text input.
  390. e.preventDefault();
  391. toggleSearchDialog();
  392. }
  393. });
  394. // Toggle day/night mode.
  395. $('.js-dark-toggle').click(function(e) {
  396. e.preventDefault();
  397. toggleDarkMode();
  398. });
  399. });
  400. })(jQuery);