filters.js 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. setChronologyRange(min, max) {
  23. let updated = false;
  24. if (this.#minDate != min) {
  25. this.#minDate = min;
  26. updated = true;
  27. }
  28. if (this.#maxDate != max) {
  29. this.#maxDate = max;
  30. updated = true;
  31. }
  32. updated && this.#updateFilter();
  33. }
  34. isFiltering() {
  35. if (window.chronology.isInitialized()) {
  36. let chronoRange = window.chronology.getRange();
  37. if (this.#minDate > chronoRange.min || this.#maxDate < chronoRange.max)
  38. return true;
  39. }
  40. for (let i in this.#filters) {
  41. if (this.#filters[i]?.length)
  42. return true;
  43. }
  44. return false;
  45. }
  46. // Returns false if image doesnt match
  47. #matchTags(mediaTags, tags) {
  48. for (let i of tags)
  49. if (mediaTags.find(x => x === i || x.startsWith(`${i}/`)))
  50. return true;
  51. return false;
  52. }
  53. match(mediaItem) {
  54. const dateTime = mediaItem.date.getTime();
  55. if (dateTime < this.#minDate || dateTime > this.#maxDate)
  56. return false;
  57. for (let i in this.#filters) {
  58. if (!this.#filters[i] || !this.#filters[i].length)
  59. continue;
  60. if (i === "Tags") {
  61. const mediaTags = mediaItem.allTags();
  62. if (this.#filters[i].indexOf(undefined) !== -1 && !mediaTags.length)
  63. continue;
  64. if (this.#matchTags(mediaTags, this.#filters[i].filter(i => !!i)))
  65. continue;
  66. return false;
  67. }
  68. if (this.#filters[i].indexOf(""+mediaItem.meta[i]?.value) === -1)
  69. return false;
  70. }
  71. return true;
  72. }
  73. #filters = {};
  74. #minDate = 0;
  75. #maxDate = Infinity;
  76. }
  77. return new FilterManager();
  78. })();