|
| 1 | +import { renderThumbnails } from './photos'; |
| 2 | +import { debounce } from './utils'; |
| 3 | + |
| 4 | +const RENDER_DELAY = 500; |
| 5 | + |
| 6 | +const imageFilters = document.querySelector('.img-filters'); |
| 7 | +const imageFiltersForm = imageFilters.querySelector('.img-filters__form'); |
| 8 | +let currentPictures = []; |
| 9 | + |
| 10 | +export const initFilters = (pictures) => { |
| 11 | + currentPictures = pictures; |
| 12 | + |
| 13 | + if (!imageFilters.classList.contains('img-filters--inactive')) { |
| 14 | + return; |
| 15 | + } |
| 16 | + |
| 17 | + imageFilters.classList.remove('img-filters--inactive'); |
| 18 | +}; |
| 19 | + |
| 20 | +const debouncedRenderThumbnails = debounce((pictures) => { |
| 21 | + document.querySelectorAll('.picture').forEach((element) => element.remove()); |
| 22 | + renderThumbnails(pictures); |
| 23 | +}, RENDER_DELAY); |
| 24 | + |
| 25 | +const getDefaultPictures = () => [...currentPictures]; |
| 26 | +const getRandomPictures = () => [...currentPictures].sort(() => Math.random() - 0.5).slice(0, 10); |
| 27 | +const getDiscussedPictures = () => [...currentPictures].sort((photoA, photoB) => photoB.comments.length - photoA.comments.length); |
| 28 | + |
| 29 | +imageFiltersForm.addEventListener('click', (evt) => { |
| 30 | + evt.preventDefault(); |
| 31 | + |
| 32 | + if (!evt.target.classList.contains('img-filters__button')) { |
| 33 | + return; |
| 34 | + } |
| 35 | + |
| 36 | + if (evt.target.classList.contains('img-filters__button--active')) { |
| 37 | + return; |
| 38 | + } |
| 39 | + |
| 40 | + const currentActiveButton = imageFiltersForm.querySelector('.img-filters__button--active'); |
| 41 | + if (currentActiveButton) { |
| 42 | + currentActiveButton.classList.remove('img-filters__button--active'); |
| 43 | + } |
| 44 | + |
| 45 | + evt.target.classList.add('img-filters__button--active'); |
| 46 | + |
| 47 | + let filteredPictures = []; |
| 48 | + |
| 49 | + switch (evt.target.id) { |
| 50 | + case 'filter-default': |
| 51 | + filteredPictures = getDefaultPictures(); |
| 52 | + break; |
| 53 | + |
| 54 | + case 'filter-random': |
| 55 | + filteredPictures = getRandomPictures(); |
| 56 | + break; |
| 57 | + |
| 58 | + case 'filter-discussed': |
| 59 | + filteredPictures = getDiscussedPictures(); |
| 60 | + break; |
| 61 | + |
| 62 | + } |
| 63 | + |
| 64 | + debouncedRenderThumbnails(filteredPictures); |
| 65 | +}); |
0 commit comments