Skip to content

Commit

Permalink
Merge pull request #13 from lenapokrovskaya/module12-task1
Browse files Browse the repository at this point in the history
  • Loading branch information
keksobot authored Jan 20, 2025
2 parents 38514ec + a903481 commit 4c193cf
Show file tree
Hide file tree
Showing 6 changed files with 95 additions and 2 deletions.
2 changes: 1 addition & 1 deletion index.html
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ <h2 class="img-upload__title visually-hidden">Загрузка фотограф

<!-- Изначальное состояние поля для загрузки изображения -->
<fieldset class="img-upload__start">
<input type="file" id="upload-file" class="img-upload__input visually-hidden" name="filename" required>
<input type="file" id="upload-file" class="img-upload__input visually-hidden" name="filename" accept="image/png, image/jpeg" required>
<label for="upload-file" class="img-upload__label img-upload__control">Загрузить</label>
</fieldset>

Expand Down
18 changes: 18 additions & 0 deletions js/avatar.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
const FILE_TYPES = ['gif', 'jpg', 'jpeg', 'png'];

const avatarElement = document.querySelector('.img-upload__preview img');
const avatarPreviews = document.querySelectorAll('.effects__preview');
const uploadFileInputElement = document.querySelector('#upload-file');

uploadFileInputElement.addEventListener('change', () => {
const file = uploadFileInputElement.files[0];
//получаем имя файла через name и приводим к одному виду
const fileName = file.name.toLowerCase();
//Делаем проверку совпадает ли имя нашего файла с допустимыми
const matches = FILE_TYPES.some((item) => fileName.endsWith(item));

if(matches) {
avatarElement.src = URL.createObjectURL(file);
avatarPreviews.forEach((el) => el.style.setProperty('background-image', `url(${URL.createObjectURL(file)})`));
}
});
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 getRandomPosts = (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(getRandomPosts(data), RERENDER_DELAY))();
break;

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

export {getRandomPosts, 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';
import './avatar.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 4c193cf

Please sign in to comment.