|
| 1 | +import {debounce} from './util.js'; |
| 2 | + |
| 3 | +import { renderPhoto } from './render-photo.js'; |
| 4 | + |
| 5 | +const FILTER = { |
| 6 | + default:'filter-default', |
| 7 | + random: 'filter-random', |
| 8 | + discussed: 'filter-discussed' |
| 9 | +}; |
| 10 | + |
| 11 | +let currentFilter = FILTER.default; |
| 12 | + |
| 13 | +const filterPanel = document.querySelector('.img-filters'); |
| 14 | +const ACTIVE_BUTTON_CLASS = 'img-filters__button--active'; |
| 15 | + |
| 16 | +const debounceRender = debounce(renderPhoto); |
| 17 | + |
| 18 | +const applyFilter = (photos) => { |
| 19 | + let filteredPictures = []; |
| 20 | + if(currentFilter === FILTER.default) { |
| 21 | + filteredPictures = photos; |
| 22 | + } |
| 23 | + if(currentFilter === FILTER.random) { |
| 24 | + filteredPictures = photos.toSorted(() => 0.5 - Math.random()).slice(0, 10); |
| 25 | + } |
| 26 | + if(currentFilter === FILTER.discussed) { |
| 27 | + filteredPictures = photos.toSorted((a,b) => b.comments.length - a.comments.length); |
| 28 | + } |
| 29 | + //renderPhoto(filteredPictures); |
| 30 | + debounceRender(filteredPictures); |
| 31 | +}; |
| 32 | + |
| 33 | +const getHandleFilter = (photos) => (evt) => { |
| 34 | + const targetButton = evt.target; |
| 35 | + const activeButton = document.querySelector(`.${ACTIVE_BUTTON_CLASS}`); |
| 36 | + if (!targetButton.matches('button')) { |
| 37 | + return; |
| 38 | + } |
| 39 | + if (activeButton === targetButton) { |
| 40 | + return; |
| 41 | + } |
| 42 | + activeButton.classList.toggle(ACTIVE_BUTTON_CLASS); |
| 43 | + targetButton.classList.toggle(ACTIVE_BUTTON_CLASS); |
| 44 | + currentFilter = targetButton.getAttribute('id'); |
| 45 | + applyFilter(photos); |
| 46 | +}; |
| 47 | + |
| 48 | +export const initFilter = (photos) => { |
| 49 | + filterPanel.classList.remove('img-filters--inactive'); |
| 50 | + filterPanel.addEventListener('click', getHandleFilter(photos)); |
| 51 | +}; |
0 commit comments