academic.js 28 KB

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