MediaWiki:Script/Filter.js

Révision datée du 17 août 2023 à 15:02 par Dexter (discussion | contributions) (Page créée avec « function handleDropdowns(form) { var activeButton = null; function toggleDropdown(button, dropdownMenu) { if (button === activeButton) { dropdownMenu.classL... »)
(diff) ← Version précédente | Voir la version actuelle (diff) | Version suivante → (diff)

Note : après avoir enregistré vos modifications, il se peut que vous deviez forcer le rechargement complet du cache de votre navigateur pour voir les changements.

  • Firefox / Safari : maintenez la touche Maj (Shift) en cliquant sur le bouton Actualiser ou pressez Ctrl-F5 ou Ctrl-R (⌘-R sur un Mac)
  • Google Chrome : appuyez sur Ctrl-Maj-R (⌘-Shift-R sur un Mac)
  • Internet Explorer : maintenez la touche Ctrl en cliquant sur le bouton Actualiser ou pressez Ctrl-F5
  • Opera : allez dans Menu → Settings (Opera → Préférences sur un Mac) et ensuite à Confidentialité & sécurité → Effacer les données d’exploration → Images et fichiers en cache.
function handleDropdowns(form) {
  var activeButton = null;

  function toggleDropdown(button, dropdownMenu) {
    if (button === activeButton) {
      dropdownMenu.classList.add('tabber-noactive');
      activeButton = null;
    } else {
      if (activeButton) {
        activeButton.nextElementSibling.classList.add('tabber-noactive');
      }
      dropdownMenu.classList.remove('tabber-noactive');
      activeButton = button;
    }
  }

  
  function closeDropdowns() {
    if (activeButton) {
      activeButton.nextElementSibling.classList.add('tabber-noactive');
      activeButton = null;
    }
  }

  form.addEventListener('click', function(event) {

    var target = event.target;
    var button = target.closest('button');
    
    if (button) {
      
      var dropdownMenu = button.nextElementSibling;
      
      toggleDropdown(button, dropdownMenu);
      
    } else if (!target.closest('.dropdown-menu')) {
      closeDropdowns();
    }
  });

  document.addEventListener('click', function(event) {
    if (!form.contains(event.target)) {
      closeDropdowns();
    }
  });
}


function isObjectValuesIncludedInFilter(obj, filter) {
  return Object.keys(filter).every(function(prop) {
    return obj[prop].split(' ').some(function(val) {
      return filter[prop].indexOf(val) !== -1;
    });
  });
}


function isObjectValuesIncludedInFilterWithRange(obj, filter, rangeFilter) {
  return isObjectValuesIncludedInFilter(obj, filter) && Object.keys(rangeFilter).every(function(prop) {
    var propValue = Number(obj[prop]);
    return rangeFilter[prop]["min"] <= propValue && rangeFilter[prop]["max"] >= propValue;
  });
}


function filterItems(filter, listToFilter, rangeFilter) {
  if (rangeFilter === {}) {
    for (var i = 0; i < listToFilter.length; i++) {
      var item = listToFilter[i];
      if (isObjectValuesIncludedInFilter(item.dataset, filter)) {
        item.classList.remove("tabber-noactive");
      } else {
        item.classList.add("tabber-noactive");
      }
    }
  } else {
    for (var i = 0; i < listToFilter.length; i++) {
      var item = listToFilter[i];
      if (isObjectValuesIncludedInFilterWithRange(item.dataset, filter, rangeFilter)) {
        item.classList.remove("tabber-noactive");
      } else {
        item.classList.add("tabber-noactive");
      }
    }
  }
}


function createInitialRangeObject(form) {
  
  var initialRange = {}
  
  form.querySelectorAll('[id$="-range"]').forEach(function(e) {
    var minMax = {min: 0, max: 0}
    e.querySelectorAll('input').forEach(function(input){
      var extrem = input.id.split('-')[1];
      minMax[extrem] = Number(input[extrem]);
    });
    initialRange[e.id.split("-")[0]] = minMax;
  });
  
  return initialRange
}


function updateFilterObject(form, listToFilter, filter, rangeFilter, initialRange) {
  
  form.addEventListener("submit", function(e) {
    e.preventDefault();
  });
  
  form.addEventListener("change", function(e) {
    var target = e.target;
    var value = target.dataset.filter;
    var type = target.type;
    var key = target.parentElement.parentElement.id;
   
    if (type === "number") {

      var key = key.split("-range")[0];
      
      var extremum = target.id.split(key + "-")[1];
      var currentValue = Number(target.value);
      
      if (rangeFilter[key]) {
        
        rangeFilter[key][extremum] = currentValue;

      } else {
        
        var range = {"min": initialRange[key]["min"], "max": initialRange[key]["max"]};
        range[extremum] = currentValue;
        rangeFilter[key] = range;
      }
      
      if ((rangeFilter[key]["max"] === initialRange[key]["max"]) && (rangeFilter[key]["min"] === initialRange[key]["min"])) {
        delete rangeFilter[key];
      }
      
    } else if (type === "checkbox") {
      
      if (target.checked) {
        if (filter[key]) {
          filter[key].push(value);
        } else {
          filter[key] = [value];
        }
      } else {
        var index = filter[key].indexOf(value);
        if (index !== -1) {
          if (filter[key].length === 1) {
            delete filter[key];
          } else {
            filter[key].splice(index, 1);
          }
        }
      } 
    }
    
    filterItems(filter, listToFilter, rangeFilter);
  });
}


function keyboard(form) {
  
  var focusableElements = form.querySelectorAll('a[href], button, textarea, input[type="text"], input[type="radio"], input[type="checkbox"], input[type="number"], select');
  var buttons = form.querySelectorAll("button");
  
  form.addEventListener("keydown", function(e) {
    
    var target = e.target;

    if (target.tagName === "INPUT") {
      
      if (e.key === "Enter") {

        target.click();
        
      }
      
    } else if (target.tagName === "BUTTON") {
      
      if (e.key === "ArrowRight" || e.key === "ArrowLeft") {
        var currentElement = document.activeElement;
        var currentIndex = Array.prototype.indexOf.call(buttons, currentElement);
        var nextIndex = e.key === "ArrowRight" ? (currentIndex + 1) % buttons.length : (currentIndex - 1 + buttons.length) % buttons.length;
        buttons[nextIndex].focus();
      }
      
    }
    
    if (target.type !== "number") {
      if (e.key === "ArrowDown" || e.key === "ArrowUp") {
        var currentElement = document.activeElement;
        var currentIndex = Array.prototype.indexOf.call(focusableElements, currentElement);
        var nextIndex = e.key === "ArrowDown" ? (currentIndex + 1) % focusableElements.length : (currentIndex - 1 + focusableElements.length) % focusableElements.length;
        focusableElements[nextIndex].focus();
      }
    }
  });
}


function filterWithURL(form, url, listToFilter) {

  var params = new URLSearchParams(url.search);
  var filter = {}
  var initialRange = createInitialRangeObject(form);
  var rangeFilter = {}

  for (var [key, value] of params.entries()) {
    
    var input = form.querySelector("[id^='" + key + "'][data-filter='" + value + "']");
    
    if (input) {
      input.checked = true;
      filter[key] = params.getAll(key);
      
    } else {

      var checkbox = form.querySelector("#" + key);
      
      if (checkbox) {
        
        var [filterKey, extremum] = key.split("-");
            
        if (rangeFilter[filterKey]) {
        
          rangeFilter[filterKey][extremum] = Number(value);
        
        } else {

          var range = {"min": initialRange[filterKey]["min"], "max": initialRange[filterKey]["max"]};
          
          range[extremum] = Number(value);
          rangeFilter[filterKey] = range;
            
        }
        
        checkbox.value = value;
      }
    }
  }
  
  filterItems(filter, listToFilter, rangeFilter);
  
  return [filter, rangeFilter, initialRange]
}


(function(){
  
  var listToFilter = document.getElementById("list-to-filter").children;
  var form = document.getElementById("filter-form");
  var url = new URL(window.location.href);
  var [filter, rangeFilter, initialRange] = filterWithURL(form, url, listToFilter);

  keyboard(form);
  handleDropdowns(form);
  updateFilterObject(form, listToFilter, filter, rangeFilter, initialRange);
})();