filters.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. window.FilterManager = (() => {
  2. class FilterManager {
  3. #updateFilter() {
  4. for (let i of MediaStorage.Instance.medias) {
  5. if (!i.ui)
  6. continue;
  7. if (this.match(i))
  8. i.ui.root.classList.remove("filtered");
  9. else
  10. i.ui.root.classList.add("filtered");
  11. }
  12. MediaStorage.Instance.onFilterUpdated();
  13. if (this.isFiltering())
  14. document.body.classList.add("filter-active");
  15. else
  16. document.body.classList.remove("filter-active");
  17. }
  18. setFilterValue(key, val) {
  19. this.#filters[key] = val;
  20. this.#updateFilter();
  21. }
  22. isFiltering() {
  23. for (let i in this.#filters) {
  24. if (this.#filters[i]?.length)
  25. return true;
  26. }
  27. return false;
  28. }
  29. // Returns false if image doesnt match
  30. #matchTags(mediaTags, tags) {
  31. for (let i of tags)
  32. if (mediaTags.find(x => x === i || x.startsWith(`${i}/`)))
  33. return true;
  34. return false;
  35. }
  36. match(mediaItem) {
  37. for (let i in this.#filters) {
  38. if (!this.#filters[i] || !this.#filters[i].length)
  39. continue;
  40. if (i === "Tags") {
  41. const mediaTags = mediaItem.allTags();
  42. if (this.#filters[i].indexOf(undefined) !== -1 && !mediaTags.length)
  43. continue;
  44. if (this.#matchTags(mediaTags, this.#filters[i].filter(i => !!i)))
  45. continue;
  46. return false;
  47. }
  48. if (this.#filters[i].indexOf(mediaItem.meta[i]?.value) === -1)
  49. return false;
  50. }
  51. return true;
  52. }
  53. #filters = {};
  54. }
  55. return new FilterManager();
  56. })();