|
| 1 | +import { renderPictures } from './pictures-renderer.js'; |
| 2 | +import { debounce } from './util.js'; |
| 3 | + |
| 4 | +const RANDOM_COUNT = 10; |
| 5 | +const RERENDER_DELAY = 500; |
| 6 | +const BUTTON_ACTIVE_CLASS = 'img-filters__button--active'; |
| 7 | +const Filters = { |
| 8 | + 'filter-default': null, |
| 9 | + 'filter-random': (elements) => elements.toSorted(() => Math.random() - 0.5).slice(0, RANDOM_COUNT), |
| 10 | + 'filter-discussed': (elements) => elements.toSorted((a, b) => b.comments - a.comments), |
| 11 | +}; |
| 12 | +const debouncedRenderPictures = debounce(renderPictures, RERENDER_DELAY); |
| 13 | + |
| 14 | +const filters = document.querySelector('.img-filters'); |
| 15 | +const filtersForm = filters.querySelector('.img-filters__form'); |
| 16 | +const buttons = filtersForm.querySelectorAll('.img-filters__button'); |
| 17 | + |
| 18 | +const buttonClickHandler = (evt, gallery) => { |
| 19 | + evt.preventDefault(); |
| 20 | + const targetButton = evt.target; |
| 21 | + const activeButton = filtersForm.querySelector(`.${BUTTON_ACTIVE_CLASS}`); |
| 22 | + if(targetButton === activeButton) { |
| 23 | + return; |
| 24 | + } |
| 25 | + activeButton.classList.remove(BUTTON_ACTIVE_CLASS); |
| 26 | + targetButton.classList.add(BUTTON_ACTIVE_CLASS); |
| 27 | + const filter = Filters[targetButton.id]; |
| 28 | + debouncedRenderPictures(gallery, filter); |
| 29 | +}; |
| 30 | + |
| 31 | +const buttonsAttachHandlers = (gallery) => { |
| 32 | + buttons.forEach((button) => { |
| 33 | + button.addEventListener('click', (evt) => { |
| 34 | + buttonClickHandler(evt, gallery); |
| 35 | + }); |
| 36 | + }); |
| 37 | +}; |
| 38 | +const showFilters = (gallery) => { |
| 39 | + filters.classList.remove('img-filters--inactive'); |
| 40 | + buttonsAttachHandlers(gallery); |
| 41 | +}; |
| 42 | + |
| 43 | +export { showFilters, buttonsAttachHandlers }; |
0 commit comments