block-navigation.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /* eslint-disable */
  2. var jumpToCode = (function init() {
  3. // Classes of code we would like to highlight in the file view
  4. var missingCoverageClasses = ['.cbranch-no', '.cstat-no', '.fstat-no'];
  5. // Elements to highlight in the file listing view
  6. var fileListingElements = ['td.pct.low'];
  7. // We don't want to select elements that are direct descendants of another match
  8. var notSelector = ':not(' + missingCoverageClasses.join('):not(') + ') > '; // becomes `:not(a):not(b) > `
  9. // Selecter that finds elements on the page to which we can jump
  10. var selector =
  11. fileListingElements.join(', ') +
  12. ', ' +
  13. notSelector +
  14. missingCoverageClasses.join(', ' + notSelector); // becomes `:not(a):not(b) > a, :not(a):not(b) > b`
  15. // The NodeList of matching elements
  16. var missingCoverageElements = document.querySelectorAll(selector);
  17. var currentIndex;
  18. function toggleClass(index) {
  19. missingCoverageElements
  20. .item(currentIndex)
  21. .classList.remove('highlighted');
  22. missingCoverageElements.item(index).classList.add('highlighted');
  23. }
  24. function makeCurrent(index) {
  25. toggleClass(index);
  26. currentIndex = index;
  27. missingCoverageElements.item(index).scrollIntoView({
  28. behavior: 'smooth',
  29. block: 'center',
  30. inline: 'center'
  31. });
  32. }
  33. function goToPrevious() {
  34. var nextIndex = 0;
  35. if (typeof currentIndex !== 'number' || currentIndex === 0) {
  36. nextIndex = missingCoverageElements.length - 1;
  37. } else if (missingCoverageElements.length > 1) {
  38. nextIndex = currentIndex - 1;
  39. }
  40. makeCurrent(nextIndex);
  41. }
  42. function goToNext() {
  43. var nextIndex = 0;
  44. if (
  45. typeof currentIndex === 'number' &&
  46. currentIndex < missingCoverageElements.length - 1
  47. ) {
  48. nextIndex = currentIndex + 1;
  49. }
  50. makeCurrent(nextIndex);
  51. }
  52. return function jump(event) {
  53. if (
  54. document.getElementById('fileSearch') === document.activeElement &&
  55. document.activeElement != null
  56. ) {
  57. // if we're currently focused on the search input, we don't want to navigate
  58. return;
  59. }
  60. switch (event.which) {
  61. case 78: // n
  62. case 74: // j
  63. goToNext();
  64. break;
  65. case 66: // b
  66. case 75: // k
  67. case 80: // p
  68. goToPrevious();
  69. break;
  70. }
  71. };
  72. })();
  73. window.addEventListener('keydown', jumpToCode);