wowchemy.js 28 KB

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