Skip to content

Commit

Permalink
Перламутровые пуговицы
Browse files Browse the repository at this point in the history
  • Loading branch information
lenapokrovskaya committed Jan 20, 2025
1 parent 38514ec commit 402a626
Show file tree
Hide file tree
Showing 4 changed files with 76 additions and 1 deletion.
46 changes: 46 additions & 0 deletions js/filter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import {createFragment} from './thumbnails.js';
import {renderModal} from './modal.js';
import {getRandomArrayElement} from './util.js';
import {debounce} from './util.js';

const POST_COUNT = 10;
const RERENDER_DELAY = 500;

const imgFiltersForm = document.querySelector('.img-filters__form');
const buttonsElements = imgFiltersForm.querySelectorAll('.img-filters__button');

const getRandomPost = (postArray) =>
postArray.slice(0, POST_COUNT).map(() => getRandomArrayElement(postArray));

const updatePosts = (posts) => {
const pictureElements = document.querySelectorAll('.picture');
pictureElements.forEach((el) => el.remove());
createFragment(posts);
renderModal(posts);
};

const onChangefilterPosts = (data) => {
imgFiltersForm.addEventListener('click', (evt) => {
const targetButton = evt.target.closest('.img-filters__button');
if (targetButton) {
buttonsElements.forEach((el) => el.classList.remove('img-filters__button--active'));
targetButton.classList.add('img-filters__button--active');

switch (evt.target.id) {
case 'filter-default':
debounce(() => updatePosts(data), RERENDER_DELAY)();
break;

case 'filter-random':
debounce(() => updatePosts(getRandomPost(data), RERENDER_DELAY))();
break;

case 'filter-discussed':
debounce(() => updatePosts(data.toSorted((a, b) => b.comments.length - a.comments.length)), RERENDER_DELAY)();
break;
}
}
});
};

export {getRandomPost, onChangefilterPosts};
7 changes: 7 additions & 0 deletions js/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,23 @@ import {getData} from './api.js';
import {createFragment} from './thumbnails.js';
import {renderModal} from './modal.js';
import {showDataError} from './notifications.js';
import {onChangefilterPosts} from './filter.js';


const ERROR_DISPLAY_TIME = 5000;
const templateDataErrorElement = document.querySelector('#data-error').content.querySelector('.data-error');
const dataErrorElement = templateDataErrorElement.cloneNode(true);

const imgFiltersElement = document.querySelector('.img-filters');

openUploadForm();

getData()
.then((posts) => {
createFragment(posts);
renderModal(posts);
imgFiltersElement.classList.remove('img-filters--inactive');
onChangefilterPosts(posts);
})
.catch(() => {
showDataError(dataErrorElement);
Expand All @@ -23,4 +29,5 @@ getData()
}, ERROR_DISPLAY_TIME);
});


setUserFormSubmit(closeUploadForm);
1 change: 1 addition & 0 deletions js/thumbnails.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ const templateElement = document.querySelector('#picture').content.querySelector
const containerElement = document.querySelector('.pictures');
const fragmentElement = document.createDocumentFragment();


//Функция создания перевью
const createThumbnail = ({id, url, description, likes, comments}) => {
const thumbnailElement = templateElement.cloneNode(true);
Expand Down
23 changes: 22 additions & 1 deletion js/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,25 @@ const createUniqueRandomInteger = (min, max) => {
//Функция проверяющая клавиша esc или нет
const isEscapeKey = (evt) => evt.key === 'Escape';

export {getRandomInteger, createUniqueRandomInteger, isEscapeKey};
const getRandomArrayElement = (elements) =>
elements[getRandomInteger(0, elements.length - 1)];

function debounce (callback, timeoutDelay = 500) {
// Используем замыкания, чтобы id таймаута у нас навсегда приклеился
// к возвращаемой функции с setTimeout, тогда мы его сможем перезаписывать
let timeoutId;

return (...rest) => {
// Перед каждым новым вызовом удаляем предыдущий таймаут,
// чтобы они не накапливались
clearTimeout(timeoutId);

// Затем устанавливаем новый таймаут с вызовом колбэка на ту же задержку
timeoutId = setTimeout(() => callback.apply(this, rest), timeoutDelay);

// Таким образом цикл «поставить таймаут - удалить таймаут» будет выполняться,
// пока действие совершается чаще, чем переданная задержка timeoutDelay
};
}

export {getRandomInteger, createUniqueRandomInteger, isEscapeKey, getRandomArrayElement, debounce};

0 comments on commit 402a626

Please sign in to comment.