wowchemy.js 28 KB

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