academic.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767
  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 height for offsetting Scrollspy.
  12. function getNavBarHeight() {
  13. let $navbar = $('#navbar-main');
  14. let navbar_offset = $navbar.outerHeight();
  15. console.debug('Navbar height: ' + navbar_offset);
  16. return navbar_offset;
  17. }
  18. /**
  19. * Responsive hash scrolling.
  20. * Check for a URL hash as an anchor.
  21. * If it exists on current page, scroll to it responsively.
  22. * If `target` argument omitted (e.g. after event), assume it's the window's hash.
  23. */
  24. function scrollToAnchor(target) {
  25. // If `target` is undefined or HashChangeEvent object, set it to window's hash.
  26. // Decode the hash as browsers can encode non-ASCII characters (e.g. Chinese symbols).
  27. target = (typeof target === 'undefined' || typeof target === 'object') ? decodeURIComponent(window.location.hash) : target;
  28. // If target element exists, scroll to it taking into account fixed navigation bar offset.
  29. if ($(target).length) {
  30. // Escape special chars from IDs, such as colons found in Markdown footnote links.
  31. target = '#' + $.escapeSelector(target.substring(1)); // Previously, `target = target.replace(/:/g, '\\:');`
  32. let elementOffset = Math.ceil($(target).offset().top - getNavBarHeight()); // Round up to highlight right ID!
  33. $('body').addClass('scrolling');
  34. $('html, body').animate({
  35. scrollTop: elementOffset
  36. }, 600, function () {
  37. $('body').removeClass('scrolling');
  38. });
  39. } else {
  40. console.debug('Cannot scroll to target `#' + target + '`. ID not found!');
  41. }
  42. }
  43. // Make Scrollspy responsive.
  44. function fixScrollspy() {
  45. let $body = $('body');
  46. let data = $body.data('bs.scrollspy');
  47. if (data) {
  48. data._config.offset = getNavBarHeight();
  49. $body.data('bs.scrollspy', data);
  50. $body.scrollspy('refresh');
  51. }
  52. }
  53. function removeQueryParamsFromUrl() {
  54. if (window.history.replaceState) {
  55. let urlWithoutSearchParams = window.location.protocol + "//" + window.location.host + window.location.pathname + window.location.hash;
  56. window.history.replaceState({path: urlWithoutSearchParams}, '', urlWithoutSearchParams);
  57. }
  58. }
  59. // Check for hash change event and fix responsive offset for hash links (e.g. Markdown footnotes).
  60. window.addEventListener("hashchange", scrollToAnchor);
  61. /* ---------------------------------------------------------------------------
  62. * Add smooth scrolling to all links inside the main navbar.
  63. * --------------------------------------------------------------------------- */
  64. $('#navbar-main li.nav-item a.nav-link').on('click', function (event) {
  65. // Store requested URL hash.
  66. let hash = this.hash;
  67. // If we are on a widget page and the navbar link is to a section on the same page.
  68. if (this.pathname === window.location.pathname && hash && $(hash).length && ($(".js-widget-page").length > 0)) {
  69. // Prevent default click behavior.
  70. event.preventDefault();
  71. // Use jQuery's animate() method for smooth page scrolling.
  72. // The numerical parameter specifies the time (ms) taken to scroll to the specified hash.
  73. let elementOffset = Math.ceil($(hash).offset().top - getNavBarHeight()); // Round up to highlight right ID!
  74. // Uncomment to debug.
  75. // let scrollTop = $(window).scrollTop();
  76. // let scrollDelta = (elementOffset - scrollTop);
  77. // console.debug('Scroll Delta: ' + scrollDelta);
  78. $('html, body').animate({
  79. scrollTop: elementOffset
  80. }, 800);
  81. }
  82. });
  83. /* ---------------------------------------------------------------------------
  84. * Hide mobile collapsable menu on clicking a link.
  85. * --------------------------------------------------------------------------- */
  86. $(document).on('click', '.navbar-collapse.show', function (e) {
  87. //get the <a> element that was clicked, even if the <span> element that is inside the <a> element is e.target
  88. let targetElement = $(e.target).is('a') ? $(e.target) : $(e.target).parent();
  89. if (targetElement.is('a') && targetElement.attr('class') != 'dropdown-toggle') {
  90. $(this).collapse('hide');
  91. }
  92. });
  93. /* ---------------------------------------------------------------------------
  94. * Filter publications.
  95. * --------------------------------------------------------------------------- */
  96. // Active publication filters.
  97. let pubFilters = {};
  98. // Search term.
  99. let searchRegex;
  100. // Filter values (concatenated).
  101. let filterValues;
  102. // Publication container.
  103. let $grid_pubs = $('#container-publications');
  104. // Initialise Isotope.
  105. $grid_pubs.isotope({
  106. itemSelector: '.isotope-item',
  107. percentPosition: true,
  108. masonry: {
  109. // Use Bootstrap compatible grid layout.
  110. columnWidth: '.grid-sizer'
  111. },
  112. filter: function () {
  113. let $this = $(this);
  114. let searchResults = searchRegex ? $this.text().match(searchRegex) : true;
  115. let filterResults = filterValues ? $this.is(filterValues) : true;
  116. return searchResults && filterResults;
  117. }
  118. });
  119. // Filter by search term.
  120. let $quickSearch = $('.filter-search').keyup(debounce(function () {
  121. searchRegex = new RegExp($quickSearch.val(), 'gi');
  122. $grid_pubs.isotope();
  123. }));
  124. // Debounce input to prevent spamming filter requests.
  125. function debounce(fn, threshold) {
  126. let timeout;
  127. threshold = threshold || 100;
  128. return function debounced() {
  129. clearTimeout(timeout);
  130. let args = arguments;
  131. let _this = this;
  132. function delayed() {
  133. fn.apply(_this, args);
  134. }
  135. timeout = setTimeout(delayed, threshold);
  136. };
  137. }
  138. // Flatten object by concatenating values.
  139. function concatValues(obj) {
  140. let value = '';
  141. for (let prop in obj) {
  142. value += obj[prop];
  143. }
  144. return value;
  145. }
  146. $('.pub-filters').on('change', function () {
  147. let $this = $(this);
  148. // Get group key.
  149. let filterGroup = $this[0].getAttribute('data-filter-group');
  150. // Set filter for group.
  151. pubFilters[filterGroup] = this.value;
  152. // Combine filters.
  153. filterValues = concatValues(pubFilters);
  154. // Activate filters.
  155. $grid_pubs.isotope();
  156. // If filtering by publication type, update the URL hash to enable direct linking to results.
  157. if (filterGroup == "pubtype") {
  158. // Set hash URL to current filter.
  159. let url = $(this).val();
  160. if (url.substr(0, 9) == '.pubtype-') {
  161. window.location.hash = url.substr(9);
  162. } else {
  163. window.location.hash = '';
  164. }
  165. }
  166. });
  167. // Filter publications according to hash in URL.
  168. function filter_publications() {
  169. let urlHash = window.location.hash.replace('#', '');
  170. let filterValue = '*';
  171. // Check if hash is numeric.
  172. if (urlHash != '' && !isNaN(urlHash)) {
  173. filterValue = '.pubtype-' + urlHash;
  174. }
  175. // Set filter.
  176. let filterGroup = 'pubtype';
  177. pubFilters[filterGroup] = filterValue;
  178. filterValues = concatValues(pubFilters);
  179. // Activate filters.
  180. $grid_pubs.isotope();
  181. // Set selected option.
  182. $('.pubtype-select').val(filterValue);
  183. }
  184. /* ---------------------------------------------------------------------------
  185. * Google Maps or OpenStreetMap via Leaflet.
  186. * --------------------------------------------------------------------------- */
  187. function initMap() {
  188. if ($('#map').length) {
  189. let map_provider = $('#map-provider').val();
  190. let lat = $('#map-lat').val();
  191. let lng = $('#map-lng').val();
  192. let zoom = parseInt($('#map-zoom').val());
  193. let address = $('#map-dir').val();
  194. let api_key = $('#map-api-key').val();
  195. if (map_provider == 1) {
  196. let map = new GMaps({
  197. div: '#map',
  198. lat: lat,
  199. lng: lng,
  200. zoom: zoom,
  201. zoomControl: true,
  202. zoomControlOpt: {
  203. style: 'SMALL',
  204. position: 'TOP_LEFT'
  205. },
  206. panControl: false,
  207. streetViewControl: false,
  208. mapTypeControl: false,
  209. overviewMapControl: false,
  210. scrollwheel: true,
  211. draggable: true
  212. });
  213. map.addMarker({
  214. lat: lat,
  215. lng: lng,
  216. click: function (e) {
  217. let url = 'https://www.google.com/maps/place/' + encodeURIComponent(address) + '/@' + lat + ',' + lng + '/';
  218. window.open(url, '_blank')
  219. },
  220. title: address
  221. })
  222. } else {
  223. let map = new L.map('map').setView([lat, lng], zoom);
  224. if (map_provider == 3 && api_key.length) {
  225. L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}', {
  226. 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>',
  227. maxZoom: 18,
  228. id: 'mapbox.streets',
  229. accessToken: api_key
  230. }).addTo(map);
  231. } else {
  232. L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
  233. maxZoom: 19,
  234. attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
  235. }).addTo(map);
  236. }
  237. let marker = L.marker([lat, lng]).addTo(map);
  238. let url = lat + ',' + lng + '#map=' + zoom + '/' + lat + '/' + lng + '&layers=N';
  239. marker.bindPopup(address + '<p><a href="https://www.openstreetmap.org/directions?engine=osrm_car&route=' + url + '">Routing via OpenStreetMap</a></p>');
  240. }
  241. }
  242. }
  243. /* ---------------------------------------------------------------------------
  244. * GitHub API.
  245. * --------------------------------------------------------------------------- */
  246. function printLatestRelease(selector, repo) {
  247. $.getJSON('https://api.github.com/repos/' + repo + '/tags').done(function (json) {
  248. let release = json[0];
  249. $(selector).append(' ' + release.name);
  250. }).fail(function (jqxhr, textStatus, error) {
  251. let err = textStatus + ", " + error;
  252. console.log("Request Failed: " + err);
  253. });
  254. }
  255. /* ---------------------------------------------------------------------------
  256. * Toggle search dialog.
  257. * --------------------------------------------------------------------------- */
  258. function toggleSearchDialog() {
  259. if ($('body').hasClass('searching')) {
  260. // Clear search query and hide search modal.
  261. $('[id=search-query]').blur();
  262. $('body').removeClass('searching compensate-for-scrollbar');
  263. // Remove search query params from URL as user has finished searching.
  264. removeQueryParamsFromUrl();
  265. // Prevent fixed positioned elements (e.g. navbar) moving due to scrollbars.
  266. $('#fancybox-style-noscroll').remove();
  267. } else {
  268. // Prevent fixed positioned elements (e.g. navbar) moving due to scrollbars.
  269. if (!$('#fancybox-style-noscroll').length && document.body.scrollHeight > window.innerHeight) {
  270. $('head').append(
  271. '<style id="fancybox-style-noscroll">.compensate-for-scrollbar{margin-right:' +
  272. (window.innerWidth - document.documentElement.clientWidth) +
  273. 'px;}</style>'
  274. );
  275. $('body').addClass('compensate-for-scrollbar');
  276. }
  277. // Show search modal.
  278. $('body').addClass('searching');
  279. $('.search-results').css({opacity: 0, visibility: 'visible'}).animate({opacity: 1}, 200);
  280. $('#search-query').focus();
  281. }
  282. }
  283. /* ---------------------------------------------------------------------------
  284. * Change Theme Mode (0: Day, 1: Night, 2: Auto).
  285. * --------------------------------------------------------------------------- */
  286. function canChangeTheme() {
  287. // If the theme changer component is present, then user is allowed to change the theme variation.
  288. return $('.js-dark-toggle').length;
  289. }
  290. function getThemeMode() {
  291. return parseInt(localStorage.getItem('dark_mode') || 2);
  292. }
  293. function changeThemeModeClick() {
  294. if (!canChangeTheme()) {
  295. return;
  296. }
  297. let $themeChanger = $('.js-dark-toggle i');
  298. let currentThemeMode = getThemeMode();
  299. let isDarkTheme;
  300. switch (currentThemeMode) {
  301. case 0:
  302. localStorage.setItem('dark_mode', '1');
  303. isDarkTheme = 1;
  304. console.info('User changed theme variation to Dark.');
  305. $themeChanger.removeClass('fa-moon fa-sun').addClass('fa-palette');
  306. break;
  307. case 1:
  308. localStorage.setItem('dark_mode', '2');
  309. if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
  310. // The visitor prefers dark themes and switching to the dark variation is allowed by admin.
  311. isDarkTheme = 1;
  312. } else if (window.matchMedia('(prefers-color-scheme: light)').matches) {
  313. // The visitor prefers light themes and switching to the dark variation is allowed by admin.
  314. isDarkTheme = 0;
  315. } else {
  316. isDarkTheme = isSiteThemeDark; // Use the site's default theme variation based on `light` in the theme file.
  317. }
  318. console.info('User changed theme variation to Auto.');
  319. $themeChanger.removeClass('fa-moon fa-palette').addClass('fa-sun');
  320. break;
  321. default:
  322. localStorage.setItem('dark_mode', '0');
  323. isDarkTheme = 0;
  324. console.info('User changed theme variation to Light.');
  325. $themeChanger.removeClass('fa-sun fa-palette').addClass('fa-moon');
  326. break;
  327. }
  328. renderThemeVariation(isDarkTheme);
  329. }
  330. function getThemeVariation() {
  331. if (!canChangeTheme()) {
  332. return isSiteThemeDark; // Use the site's default theme variation based on `light` in the theme file.
  333. }
  334. let currentThemeMode = getThemeMode();
  335. let isDarkTheme;
  336. switch (currentThemeMode) {
  337. case 0:
  338. isDarkTheme = 0;
  339. break;
  340. case 1:
  341. isDarkTheme = 1;
  342. break;
  343. default:
  344. if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
  345. // The visitor prefers dark themes and switching to the dark variation is allowed by admin.
  346. isDarkTheme = 1;
  347. } else if (window.matchMedia('(prefers-color-scheme: light)').matches) {
  348. // The visitor prefers light themes and switching to the dark variation is allowed by admin.
  349. isDarkTheme = 0;
  350. } else {
  351. isDarkTheme = isSiteThemeDark; // Use the site's default theme variation based on `light` in the theme file.
  352. }
  353. break;
  354. }
  355. return isDarkTheme;
  356. }
  357. /**
  358. * Render theme variation (day or night).
  359. *
  360. * @param {int} isDarkTheme - TODO: convert to boolean.
  361. * @param {boolean} init
  362. * @returns {undefined}
  363. */
  364. function renderThemeVariation(isDarkTheme, init = false) {
  365. // Is code highlighting enabled in site config?
  366. const codeHlEnabled = $('link[title=hl-light]').length > 0;
  367. const codeHlLight = $('link[title=hl-light]')[0];
  368. const codeHlDark = $('link[title=hl-dark]')[0];
  369. const diagramEnabled = $('script[title=mermaid]').length > 0;
  370. // Check if re-render required.
  371. if (!init) {
  372. // If request to render light when light variation already rendered, return.
  373. // If request to render dark when dark variation already rendered, return.
  374. if ((isDarkTheme === 0 && !$('body').hasClass('dark')) || (isDarkTheme === 1 && $('body').hasClass('dark'))) {
  375. return;
  376. }
  377. }
  378. if (isDarkTheme === 0) {
  379. if (!init) {
  380. // Only fade in the page when changing the theme variation.
  381. $('body').css({opacity: 0, visibility: 'visible'}).animate({opacity: 1}, 500);
  382. }
  383. $('body').removeClass('dark');
  384. if (codeHlEnabled) {
  385. codeHlLight.disabled = false;
  386. codeHlDark.disabled = true;
  387. }
  388. if (diagramEnabled) {
  389. if (init) {
  390. mermaid.initialize({theme: 'default', securityLevel: 'loose'});
  391. } else {
  392. // Have to reload to re-initialise Mermaid with the new theme and re-parse the Mermaid code blocks.
  393. location.reload();
  394. }
  395. }
  396. } else if (isDarkTheme === 1) {
  397. if (!init) {
  398. // Only fade in the page when changing the theme variation.
  399. $('body').css({opacity: 0, visibility: 'visible'}).animate({opacity: 1}, 500);
  400. }
  401. $('body').addClass('dark');
  402. if (codeHlEnabled) {
  403. codeHlLight.disabled = true;
  404. codeHlDark.disabled = false;
  405. }
  406. if (diagramEnabled) {
  407. if (init) {
  408. mermaid.initialize({theme: 'dark', securityLevel: 'loose'});
  409. } else {
  410. // Have to reload to re-initialise Mermaid with the new theme and re-parse the Mermaid code blocks.
  411. location.reload();
  412. }
  413. }
  414. }
  415. }
  416. function initThemeVariation() {
  417. // If theme changer component present, set its icon according to the theme mode (day, night, or auto).
  418. if (canChangeTheme) {
  419. let themeMode = getThemeMode();
  420. let $themeChanger = $('.js-dark-toggle i');
  421. switch (themeMode) {
  422. case 0:
  423. $themeChanger.removeClass('fa-sun fa-palette').addClass('fa-moon');
  424. console.info('Initialize theme variation to Light.');
  425. break;
  426. case 1:
  427. $themeChanger.removeClass('fa-moon fa-sun').addClass('fa-palette');
  428. console.info('Initialize theme variation to Dark.');
  429. break;
  430. default:
  431. $themeChanger.removeClass('fa-moon fa-palette').addClass('fa-sun');
  432. console.info('Initialize theme variation to Auto.');
  433. break;
  434. }
  435. }
  436. // Render the day or night theme.
  437. let isDarkTheme = getThemeVariation();
  438. renderThemeVariation(isDarkTheme, true);
  439. }
  440. /* ---------------------------------------------------------------------------
  441. * Normalize Bootstrap Carousel Slide Heights.
  442. * --------------------------------------------------------------------------- */
  443. function normalizeCarouselSlideHeights() {
  444. $('.carousel').each(function () {
  445. // Get carousel slides.
  446. let items = $('.carousel-item', this);
  447. // Reset all slide heights.
  448. items.css('min-height', 0);
  449. // Normalize all slide heights.
  450. let maxHeight = Math.max.apply(null, items.map(function () {
  451. return $(this).outerHeight()
  452. }).get());
  453. items.css('min-height', maxHeight + 'px');
  454. })
  455. }
  456. /* ---------------------------------------------------------------------------
  457. * Fix Hugo's Goldmark output and Mermaid code blocks.
  458. * --------------------------------------------------------------------------- */
  459. /**
  460. * Fix Hugo's Goldmark output.
  461. */
  462. function fixHugoOutput() {
  463. // Fix Goldmark table of contents.
  464. // - Must be performed prior to initializing ScrollSpy.
  465. $('#TableOfContents').addClass('nav flex-column');
  466. $('#TableOfContents li').addClass('nav-item');
  467. $('#TableOfContents li a').addClass('nav-link');
  468. // Fix Goldmark task lists (remove bullet points).
  469. $("input[type='checkbox'][disabled]").parents('ul').addClass('task-list');
  470. }
  471. /**
  472. * Fix Mermaid.js clash with Highlight.js.
  473. * Refactor Mermaid code blocks as divs to prevent Highlight parsing them and enable Mermaid to parse them.
  474. */
  475. function fixMermaid() {
  476. let mermaids = [];
  477. [].push.apply(mermaids, document.getElementsByClassName('language-mermaid'));
  478. for (let i = 0; i < mermaids.length; i++) {
  479. $(mermaids[i]).unwrap('pre'); // Remove <pre> wrapper.
  480. $(mermaids[i]).replaceWith(function () {
  481. // Convert <code> block to <div> and add `mermaid` class so that Mermaid will parse it.
  482. return $("<div />").append($(this).contents()).addClass('mermaid');
  483. });
  484. }
  485. }
  486. /* ---------------------------------------------------------------------------
  487. * On document ready.
  488. * --------------------------------------------------------------------------- */
  489. $(document).ready(function () {
  490. fixHugoOutput();
  491. fixMermaid();
  492. // Initialise code highlighting if enabled for this page.
  493. // Note: this block should be processed after the Mermaid code-->div conversion.
  494. if (code_highlighting) {
  495. hljs.initHighlighting();
  496. }
  497. // Initialize theme variation.
  498. initThemeVariation();
  499. // Change theme mode.
  500. $('.js-dark-toggle').click(function (e) {
  501. e.preventDefault();
  502. changeThemeModeClick();
  503. });
  504. // Live update of day/night mode on system preferences update (no refresh required).
  505. // Note: since we listen only for *dark* events, we won't detect other scheme changes such as light to no-preference.
  506. const darkModeMediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
  507. darkModeMediaQuery.addListener((e) => {
  508. if (!canChangeTheme()) {
  509. // Changing theme variation is not allowed by admin.
  510. return;
  511. }
  512. const darkModeOn = e.matches;
  513. console.log(`OS dark mode preference changed to ${darkModeOn ? '🌒 on' : '☀️ off'}.`);
  514. let currentThemeVariation = parseInt(localStorage.getItem('dark_mode') || 2);
  515. let isDarkTheme;
  516. if (currentThemeVariation === 2) {
  517. if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
  518. // The visitor prefers dark themes.
  519. isDarkTheme = 1;
  520. } else if (window.matchMedia('(prefers-color-scheme: light)').matches) {
  521. // The visitor prefers light themes.
  522. isDarkTheme = 0;
  523. } else {
  524. // The visitor does not have a day or night preference, so use the theme's default setting.
  525. isDarkTheme = isSiteThemeDark;
  526. }
  527. renderThemeVariation(isDarkTheme);
  528. }
  529. });
  530. });
  531. /* ---------------------------------------------------------------------------
  532. * On window loaded.
  533. * --------------------------------------------------------------------------- */
  534. $(window).on('load', function () {
  535. // Filter projects.
  536. $('.projects-container').each(function (index, container) {
  537. let $container = $(container);
  538. let $section = $container.closest('section');
  539. let layout;
  540. if ($section.find('.isotope').hasClass('js-layout-row')) {
  541. layout = 'fitRows';
  542. } else {
  543. layout = 'masonry';
  544. }
  545. $container.imagesLoaded(function () {
  546. // Initialize Isotope after all images have loaded.
  547. $container.isotope({
  548. itemSelector: '.isotope-item',
  549. layoutMode: layout,
  550. masonry: {
  551. gutter: 20
  552. },
  553. filter: $section.find('.default-project-filter').text()
  554. });
  555. // Filter items when filter link is clicked.
  556. $section.find('.project-filters a').click(function () {
  557. let selector = $(this).attr('data-filter');
  558. $container.isotope({filter: selector});
  559. $(this).removeClass('active').addClass('active').siblings().removeClass('active all');
  560. return false;
  561. });
  562. // If window hash is set, scroll to hash.
  563. // Placing this within `imagesLoaded` prevents scrolling to the wrong location due to dynamic image loading
  564. // affecting page layout and position of the target anchor ID.
  565. // Note: If there are multiple project widgets on a page, ideally only perform this once after images
  566. // from *all* project widgets have finished loading.
  567. if (window.location.hash) {
  568. scrollToAnchor();
  569. }
  570. });
  571. });
  572. // Enable publication filter for publication index page.
  573. if ($('.pub-filters-select')) {
  574. filter_publications();
  575. // Useful for changing hash manually (e.g. in development):
  576. // window.addEventListener('hashchange', filter_publications, false);
  577. }
  578. // Scroll to top of page.
  579. $('.back-to-top').click(function (event) {
  580. event.preventDefault();
  581. $('html, body').animate({
  582. 'scrollTop': 0
  583. }, 800, function () {
  584. window.location.hash = "";
  585. });
  586. });
  587. // Load citation modal on 'Cite' click.
  588. $('.js-cite-modal').click(function (e) {
  589. e.preventDefault();
  590. let filename = $(this).attr('data-filename');
  591. let modal = $('#modal');
  592. modal.find('.modal-body code').load(filename, function (response, status, xhr) {
  593. if (status == 'error') {
  594. let msg = "Error: ";
  595. $('#modal-error').html(msg + xhr.status + " " + xhr.statusText);
  596. } else {
  597. $('.js-download-cite').attr('href', filename);
  598. }
  599. });
  600. modal.modal('show');
  601. });
  602. // Copy citation text on 'Copy' click.
  603. $('.js-copy-cite').click(function (e) {
  604. e.preventDefault();
  605. // Get selection.
  606. let range = document.createRange();
  607. let code_node = document.querySelector('#modal .modal-body');
  608. range.selectNode(code_node);
  609. window.getSelection().addRange(range);
  610. try {
  611. // Execute the copy command.
  612. document.execCommand('copy');
  613. } catch (e) {
  614. console.log('Error: citation copy failed.');
  615. }
  616. // Remove selection.
  617. window.getSelection().removeRange(range);
  618. });
  619. // Initialise Google Maps if necessary.
  620. initMap();
  621. // Print latest version of GitHub projects.
  622. let githubReleaseSelector = '.js-github-release';
  623. if ($(githubReleaseSelector).length > 0)
  624. printLatestRelease(githubReleaseSelector, $(githubReleaseSelector).data('repo'));
  625. // On search icon click toggle search dialog.
  626. $('.js-search').click(function (e) {
  627. e.preventDefault();
  628. toggleSearchDialog();
  629. });
  630. $(document).on('keydown', function (e) {
  631. if (e.which == 27) {
  632. // `Esc` key pressed.
  633. if ($('body').hasClass('searching')) {
  634. toggleSearchDialog();
  635. }
  636. } else if (e.which == 191 && e.shiftKey == false && !$('input,textarea').is(':focus')) {
  637. // `/` key pressed outside of text input.
  638. e.preventDefault();
  639. toggleSearchDialog();
  640. }
  641. });
  642. });
  643. // Normalize Bootstrap carousel slide heights.
  644. $(window).on('load resize orientationchange', normalizeCarouselSlideHeights);
  645. // Automatic main menu dropdowns on mouse over.
  646. $('body').on('mouseenter mouseleave', '.dropdown', function (e) {
  647. var dropdown = $(e.target).closest('.dropdown');
  648. var menu = $('.dropdown-menu', dropdown);
  649. dropdown.addClass('show');
  650. menu.addClass('show');
  651. setTimeout(function () {
  652. dropdown[dropdown.is(':hover') ? 'addClass' : 'removeClass']('show');
  653. menu[dropdown.is(':hover') ? 'addClass' : 'removeClass']('show');
  654. }, 300);
  655. // Re-initialize Scrollspy with dynamic navbar height offset.
  656. fixScrollspy();
  657. if (window.location.hash) {
  658. // When accessing homepage from another page and `#top` hash is set, show top of page (no hash).
  659. if (window.location.hash == "#top") {
  660. window.location.hash = ""
  661. } else if (!$('.projects-container').length) {
  662. // If URL contains a hash and there are no dynamically loaded images on the page,
  663. // immediately scroll to target ID taking into account responsive offset.
  664. // Otherwise, wait for `imagesLoaded()` to complete before scrolling to hash to prevent scrolling to wrong
  665. // location.
  666. scrollToAnchor();
  667. }
  668. }
  669. // Call `fixScrollspy` when window is resized.
  670. let resizeTimer;
  671. $(window).resize(function () {
  672. clearTimeout(resizeTimer);
  673. resizeTimer = setTimeout(fixScrollspy, 200);
  674. });
  675. });
  676. })(jQuery);