academic.js 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797
  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, .js-scroll').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-theme-selector').length;
  289. }
  290. function getThemeMode() {
  291. return parseInt(localStorage.getItem('dark_mode') || 2);
  292. }
  293. function changeThemeModeClick(newMode) {
  294. console.info('Request to set theme.');
  295. if (!canChangeTheme()) {
  296. console.info('Cannot set theme - admin disabled theme selector.');
  297. return;
  298. }
  299. let isDarkTheme;
  300. switch (newMode) {
  301. case 0:
  302. localStorage.setItem('dark_mode', '1');
  303. isDarkTheme = true;
  304. console.info('User changed theme variation to Dark.');
  305. showActiveTheme(0);
  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 = true;
  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 = false;
  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. showActiveTheme(1);
  320. break;
  321. default:
  322. localStorage.setItem('dark_mode', '0');
  323. isDarkTheme = false;
  324. console.info('User changed theme variation to Light.');
  325. showActiveTheme(2);
  326. break;
  327. }
  328. renderThemeVariation(isDarkTheme);
  329. }
  330. function showActiveTheme(mode){
  331. switch (mode) {
  332. case 0:
  333. // Dark.
  334. $('.js-set-theme-light').removeClass('dropdown-item-active');
  335. $('.js-set-theme-dark').addClass('dropdown-item-active');
  336. $('.js-set-theme-auto').removeClass('dropdown-item-active');
  337. break;
  338. case 1:
  339. // Auto.
  340. $('.js-set-theme-light').removeClass('dropdown-item-active');
  341. $('.js-set-theme-dark').removeClass('dropdown-item-active');
  342. $('.js-set-theme-auto').addClass('dropdown-item-active');
  343. break;
  344. default:
  345. // Light.
  346. $('.js-set-theme-light').addClass('dropdown-item-active');
  347. $('.js-set-theme-dark').removeClass('dropdown-item-active');
  348. $('.js-set-theme-auto').removeClass('dropdown-item-active');
  349. break;
  350. }
  351. }
  352. function getThemeVariation() {
  353. if (!canChangeTheme()) {
  354. return isSiteThemeDark; // Use the site's default theme variation based on `light` in the theme file.
  355. }
  356. let currentThemeMode = getThemeMode();
  357. let isDarkTheme;
  358. switch (currentThemeMode) {
  359. case 0:
  360. isDarkTheme = false;
  361. break;
  362. case 1:
  363. isDarkTheme = true;
  364. break;
  365. default:
  366. if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
  367. // The visitor prefers dark themes and switching to the dark variation is allowed by admin.
  368. isDarkTheme = true;
  369. } else if (window.matchMedia('(prefers-color-scheme: light)').matches) {
  370. // The visitor prefers light themes and switching to the dark variation is allowed by admin.
  371. isDarkTheme = false;
  372. } else {
  373. isDarkTheme = isSiteThemeDark; // Use the site's default theme variation based on `light` in the theme file.
  374. }
  375. break;
  376. }
  377. return isDarkTheme;
  378. }
  379. /**
  380. * Render theme variation (day or night).
  381. *
  382. * @param {boolean} isDarkTheme
  383. * @param {boolean} init
  384. * @returns {undefined}
  385. */
  386. function renderThemeVariation(isDarkTheme, init = false) {
  387. // Is code highlighting enabled in site config?
  388. const codeHlEnabled = $('link[title=hl-light]').length > 0;
  389. const codeHlLight = $('link[title=hl-light]')[0];
  390. const codeHlDark = $('link[title=hl-dark]')[0];
  391. const diagramEnabled = $('script[title=mermaid]').length > 0;
  392. // Check if re-render required.
  393. if (!init) {
  394. // If request to render light when light variation already rendered, return.
  395. // If request to render dark when dark variation already rendered, return.
  396. if ((isDarkTheme === false && !$('body').hasClass('dark')) || (isDarkTheme === true && $('body').hasClass('dark'))) {
  397. return;
  398. }
  399. }
  400. if (isDarkTheme === false) {
  401. if (!init) {
  402. // Only fade in the page when changing the theme variation.
  403. $('body').css({opacity: 0, visibility: 'visible'}).animate({opacity: 1}, 500);
  404. }
  405. $('body').removeClass('dark');
  406. if (codeHlEnabled) {
  407. codeHlLight.disabled = false;
  408. codeHlDark.disabled = true;
  409. }
  410. if (diagramEnabled) {
  411. if (init) {
  412. mermaid.initialize({theme: 'default', securityLevel: 'loose'});
  413. } else {
  414. // Have to reload to re-initialise Mermaid with the new theme and re-parse the Mermaid code blocks.
  415. location.reload();
  416. }
  417. }
  418. } else if (isDarkTheme === true) {
  419. if (!init) {
  420. // Only fade in the page when changing the theme variation.
  421. $('body').css({opacity: 0, visibility: 'visible'}).animate({opacity: 1}, 500);
  422. }
  423. $('body').addClass('dark');
  424. if (codeHlEnabled) {
  425. codeHlLight.disabled = true;
  426. codeHlDark.disabled = false;
  427. }
  428. if (diagramEnabled) {
  429. if (init) {
  430. mermaid.initialize({theme: 'dark', securityLevel: 'loose'});
  431. } else {
  432. // Have to reload to re-initialise Mermaid with the new theme and re-parse the Mermaid code blocks.
  433. location.reload();
  434. }
  435. }
  436. }
  437. }
  438. function initThemeVariation() {
  439. // If theme changer component present, set its icon according to the theme mode (day, night, or auto).
  440. if (canChangeTheme) {
  441. let themeMode = getThemeMode();
  442. switch (themeMode) {
  443. case 0:
  444. showActiveTheme(2);
  445. console.info('Initialize theme variation to Light.');
  446. break;
  447. case 1:
  448. showActiveTheme(0);
  449. console.info('Initialize theme variation to Dark.');
  450. break;
  451. default:
  452. showActiveTheme(1);
  453. console.info('Initialize theme variation to Auto.');
  454. break;
  455. }
  456. }
  457. // Render the day or night theme.
  458. let isDarkTheme = getThemeVariation();
  459. renderThemeVariation(isDarkTheme, true);
  460. }
  461. /* ---------------------------------------------------------------------------
  462. * Normalize Bootstrap Carousel Slide Heights.
  463. * --------------------------------------------------------------------------- */
  464. function normalizeCarouselSlideHeights() {
  465. $('.carousel').each(function () {
  466. // Get carousel slides.
  467. let items = $('.carousel-item', this);
  468. // Reset all slide heights.
  469. items.css('min-height', 0);
  470. // Normalize all slide heights.
  471. let maxHeight = Math.max.apply(null, items.map(function () {
  472. return $(this).outerHeight()
  473. }).get());
  474. items.css('min-height', maxHeight + 'px');
  475. })
  476. }
  477. /* ---------------------------------------------------------------------------
  478. * Fix Hugo's Goldmark output and Mermaid code blocks.
  479. * --------------------------------------------------------------------------- */
  480. /**
  481. * Fix Hugo's Goldmark output.
  482. */
  483. function fixHugoOutput() {
  484. // Fix Goldmark table of contents.
  485. // - Must be performed prior to initializing ScrollSpy.
  486. $('#TableOfContents').addClass('nav flex-column');
  487. $('#TableOfContents li').addClass('nav-item');
  488. $('#TableOfContents li a').addClass('nav-link');
  489. // Fix Goldmark task lists (remove bullet points).
  490. $("input[type='checkbox'][disabled]").parents('ul').addClass('task-list');
  491. }
  492. /**
  493. * Fix Mermaid.js clash with Highlight.js.
  494. * Refactor Mermaid code blocks as divs to prevent Highlight parsing them and enable Mermaid to parse them.
  495. */
  496. function fixMermaid() {
  497. let mermaids = [];
  498. [].push.apply(mermaids, document.getElementsByClassName('language-mermaid'));
  499. for (let i = 0; i < mermaids.length; i++) {
  500. $(mermaids[i]).unwrap('pre'); // Remove <pre> wrapper.
  501. $(mermaids[i]).replaceWith(function () {
  502. // Convert <code> block to <div> and add `mermaid` class so that Mermaid will parse it.
  503. return $("<div />").append($(this).contents()).addClass('mermaid');
  504. });
  505. }
  506. }
  507. /* ---------------------------------------------------------------------------
  508. * On document ready.
  509. * --------------------------------------------------------------------------- */
  510. $(document).ready(function () {
  511. fixHugoOutput();
  512. fixMermaid();
  513. // Initialise code highlighting if enabled for this page.
  514. // Note: this block should be processed after the Mermaid code-->div conversion.
  515. if (code_highlighting) {
  516. hljs.initHighlighting();
  517. }
  518. // Initialize theme variation.
  519. initThemeVariation();
  520. // Change theme mode.
  521. $('.js-set-theme-light').click(function (e) {
  522. e.preventDefault();
  523. changeThemeModeClick(2);
  524. });
  525. $('.js-set-theme-dark').click(function (e) {
  526. e.preventDefault();
  527. changeThemeModeClick(0);
  528. });
  529. $('.js-set-theme-auto').click(function (e) {
  530. e.preventDefault();
  531. changeThemeModeClick(1);
  532. });
  533. // Live update of day/night mode on system preferences update (no refresh required).
  534. // Note: since we listen only for *dark* events, we won't detect other scheme changes such as light to no-preference.
  535. const darkModeMediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
  536. darkModeMediaQuery.addListener((e) => {
  537. if (!canChangeTheme()) {
  538. // Changing theme variation is not allowed by admin.
  539. return;
  540. }
  541. const darkModeOn = e.matches;
  542. console.log(`OS dark mode preference changed to ${darkModeOn ? '🌒 on' : '☀️ off'}.`);
  543. let currentThemeVariation = parseInt(localStorage.getItem('dark_mode') || 2);
  544. let isDarkTheme;
  545. if (currentThemeVariation === 2) {
  546. if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
  547. // The visitor prefers dark themes.
  548. isDarkTheme = true;
  549. } else if (window.matchMedia('(prefers-color-scheme: light)').matches) {
  550. // The visitor prefers light themes.
  551. isDarkTheme = false;
  552. } else {
  553. // The visitor does not have a day or night preference, so use the theme's default setting.
  554. isDarkTheme = isSiteThemeDark;
  555. }
  556. renderThemeVariation(isDarkTheme);
  557. }
  558. });
  559. });
  560. /* ---------------------------------------------------------------------------
  561. * On window loaded.
  562. * --------------------------------------------------------------------------- */
  563. $(window).on('load', function () {
  564. // Filter projects.
  565. $('.projects-container').each(function (index, container) {
  566. let $container = $(container);
  567. let $section = $container.closest('section');
  568. let layout;
  569. if ($section.find('.isotope').hasClass('js-layout-row')) {
  570. layout = 'fitRows';
  571. } else {
  572. layout = 'masonry';
  573. }
  574. $container.imagesLoaded(function () {
  575. // Initialize Isotope after all images have loaded.
  576. $container.isotope({
  577. itemSelector: '.isotope-item',
  578. layoutMode: layout,
  579. masonry: {
  580. gutter: 20
  581. },
  582. filter: $section.find('.default-project-filter').text()
  583. });
  584. // Filter items when filter link is clicked.
  585. $section.find('.project-filters a').click(function () {
  586. let selector = $(this).attr('data-filter');
  587. $container.isotope({filter: selector});
  588. $(this).removeClass('active').addClass('active').siblings().removeClass('active all');
  589. return false;
  590. });
  591. // If window hash is set, scroll to hash.
  592. // Placing this within `imagesLoaded` prevents scrolling to the wrong location due to dynamic image loading
  593. // affecting page layout and position of the target anchor ID.
  594. // Note: If there are multiple project widgets on a page, ideally only perform this once after images
  595. // from *all* project widgets have finished loading.
  596. if (window.location.hash) {
  597. scrollToAnchor();
  598. }
  599. });
  600. });
  601. // Enable publication filter for publication index page.
  602. if ($('.pub-filters-select')) {
  603. filter_publications();
  604. // Useful for changing hash manually (e.g. in development):
  605. // window.addEventListener('hashchange', filter_publications, false);
  606. }
  607. // Scroll to top of page.
  608. $('.back-to-top').click(function (event) {
  609. event.preventDefault();
  610. $('html, body').animate({
  611. 'scrollTop': 0
  612. }, 800, function () {
  613. window.location.hash = "";
  614. });
  615. });
  616. // Load citation modal on 'Cite' click.
  617. $('.js-cite-modal').click(function (e) {
  618. e.preventDefault();
  619. let filename = $(this).attr('data-filename');
  620. let modal = $('#modal');
  621. modal.find('.modal-body code').load(filename, function (response, status, xhr) {
  622. if (status == 'error') {
  623. let msg = "Error: ";
  624. $('#modal-error').html(msg + xhr.status + " " + xhr.statusText);
  625. } else {
  626. $('.js-download-cite').attr('href', filename);
  627. }
  628. });
  629. modal.modal('show');
  630. });
  631. // Copy citation text on 'Copy' click.
  632. $('.js-copy-cite').click(function (e) {
  633. e.preventDefault();
  634. // Get selection.
  635. let range = document.createRange();
  636. let code_node = document.querySelector('#modal .modal-body');
  637. range.selectNode(code_node);
  638. window.getSelection().addRange(range);
  639. try {
  640. // Execute the copy command.
  641. document.execCommand('copy');
  642. } catch (e) {
  643. console.log('Error: citation copy failed.');
  644. }
  645. // Remove selection.
  646. window.getSelection().removeRange(range);
  647. });
  648. // Initialise Google Maps if necessary.
  649. initMap();
  650. // Print latest version of GitHub projects.
  651. let githubReleaseSelector = '.js-github-release';
  652. if ($(githubReleaseSelector).length > 0)
  653. printLatestRelease(githubReleaseSelector, $(githubReleaseSelector).data('repo'));
  654. // On search icon click toggle search dialog.
  655. $('.js-search').click(function (e) {
  656. e.preventDefault();
  657. toggleSearchDialog();
  658. });
  659. $(document).on('keydown', function (e) {
  660. if (e.which == 27) {
  661. // `Esc` key pressed.
  662. if ($('body').hasClass('searching')) {
  663. toggleSearchDialog();
  664. }
  665. } else if (e.which == 191 && e.shiftKey == false && !$('input,textarea').is(':focus')) {
  666. // `/` key pressed outside of text input.
  667. e.preventDefault();
  668. toggleSearchDialog();
  669. }
  670. });
  671. });
  672. // Normalize Bootstrap carousel slide heights.
  673. $(window).on('load resize orientationchange', normalizeCarouselSlideHeights);
  674. // Automatic main menu dropdowns on mouse over.
  675. $('body').on('mouseenter mouseleave', '.dropdown', function (e) {
  676. var dropdown = $(e.target).closest('.dropdown');
  677. var menu = $('.dropdown-menu', dropdown);
  678. dropdown.addClass('show');
  679. menu.addClass('show');
  680. setTimeout(function () {
  681. dropdown[dropdown.is(':hover') ? 'addClass' : 'removeClass']('show');
  682. menu[dropdown.is(':hover') ? 'addClass' : 'removeClass']('show');
  683. }, 300);
  684. // Re-initialize Scrollspy with dynamic navbar height offset.
  685. fixScrollspy();
  686. if (window.location.hash) {
  687. // When accessing homepage from another page and `#top` hash is set, show top of page (no hash).
  688. if (window.location.hash == "#top") {
  689. window.location.hash = ""
  690. } else if (!$('.projects-container').length) {
  691. // If URL contains a hash and there are no dynamically loaded images on the page,
  692. // immediately scroll to target ID taking into account responsive offset.
  693. // Otherwise, wait for `imagesLoaded()` to complete before scrolling to hash to prevent scrolling to wrong
  694. // location.
  695. scrollToAnchor();
  696. }
  697. }
  698. // Call `fixScrollspy` when window is resized.
  699. let resizeTimer;
  700. $(window).resize(function () {
  701. clearTimeout(resizeTimer);
  702. resizeTimer = setTimeout(fixScrollspy, 200);
  703. });
  704. });
  705. })(jQuery);