|
| 1 | +import { renderThumbnails } from './render-thumbnails.js'; |
| 2 | +import { debounce } from './util.js'; |
| 3 | + |
| 4 | +const RANDOM_PHOTOS_COUNT = 10; |
| 5 | +const RERENDER_DELAY = 500; |
| 6 | +const ACTIVE_BUTTON_CLASS = 'img-filters__button--active'; |
| 7 | + |
| 8 | +const FilterId = { |
| 9 | + DEFAULT: 'filter-default', |
| 10 | + RANDOM: 'filter-random', |
| 11 | + DISCUSSED: 'filter-discussed', |
| 12 | +}; |
| 13 | + |
| 14 | +const filtersSection = document.querySelector('.img-filters'); |
| 15 | +const filtersForm = document.querySelector('.img-filters__form'); |
| 16 | + |
| 17 | +let currentFilter = FilterId.DEFAULT; |
| 18 | +let photos = []; |
| 19 | + |
| 20 | +const getRandomPhotos = (photosArray) => { |
| 21 | + const shuffled = [...photosArray].sort(() => Math.random() - 0.5); |
| 22 | + return shuffled.slice(0, RANDOM_PHOTOS_COUNT); |
| 23 | +}; |
| 24 | + |
| 25 | +const getDiscussedPhotos = (photosArray) => |
| 26 | + [...photosArray].sort((a, b) => b.comments.length - a.comments.length); |
| 27 | + |
| 28 | +const filterPhotos = () => { |
| 29 | + switch (currentFilter) { |
| 30 | + case FilterId.RANDOM: |
| 31 | + return getRandomPhotos(photos); |
| 32 | + case FilterId.DISCUSSED: |
| 33 | + return getDiscussedPhotos(photos); |
| 34 | + default: |
| 35 | + return [...photos]; |
| 36 | + } |
| 37 | +}; |
| 38 | + |
| 39 | +const updateActiveButton = (clickedButton) => { |
| 40 | + const activeButton = filtersForm.querySelector(`.${ACTIVE_BUTTON_CLASS}`); |
| 41 | + if (activeButton) { |
| 42 | + activeButton.classList.remove(ACTIVE_BUTTON_CLASS); |
| 43 | + } |
| 44 | + clickedButton.classList.add(ACTIVE_BUTTON_CLASS); |
| 45 | +}; |
| 46 | + |
| 47 | +const debouncedRenderThumbnails = debounce( |
| 48 | + () => renderThumbnails(filterPhotos()), |
| 49 | + RERENDER_DELAY |
| 50 | +); |
| 51 | + |
| 52 | +const onFilterButtonClick = (evt) => { |
| 53 | + const clickedButton = evt.target.closest('.img-filters__button'); |
| 54 | + |
| 55 | + if (!clickedButton) { |
| 56 | + return; |
| 57 | + } |
| 58 | + |
| 59 | + if (clickedButton.id === currentFilter) { |
| 60 | + return; |
| 61 | + } |
| 62 | + |
| 63 | + currentFilter = clickedButton.id; |
| 64 | + updateActiveButton(clickedButton); |
| 65 | + debouncedRenderThumbnails(); |
| 66 | +}; |
| 67 | + |
| 68 | +const showFilters = () => { |
| 69 | + filtersSection.classList.remove('img-filters--inactive'); |
| 70 | +}; |
| 71 | + |
| 72 | +const initFilters = (loadedPhotos) => { |
| 73 | + photos = loadedPhotos; |
| 74 | + showFilters(); |
| 75 | + filtersForm.addEventListener('click', onFilterButtonClick); |
| 76 | +}; |
| 77 | + |
| 78 | +export { initFilters }; |
0 commit comments