Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Правда или действие #9

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion index.html
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ <h2 class="pictures__title visually-hidden">Фотографии других
<section class="img-upload">
<div class="img-upload__wrapper">
<h2 class="img-upload__title visually-hidden">Загрузка фотографии</h2>
<form class="img-upload__form" id="upload-select-image" autocomplete="off">
<form class="img-upload__form" id="upload-select-image" autocomplete="off" method="POST" enctype="multipart/form-data" action="https://29.javascript.htmlacademy.pro/kekstagram">

<!-- Изначальное состояние поля для загрузки изображения -->
<fieldset class="img-upload__start">
Expand Down Expand Up @@ -227,5 +227,6 @@ <h2 class="success__title">Изображение успешно загруже
</section>
</template>
<script type = 'module' src="js/main.js"></script>
<script src="sha256-Pristine-d2ee511/dist/pristine.js" type="text/javascript"></script>
</body>
</html>
209 changes: 209 additions & 0 deletions js/form.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,209 @@
import { photos } from './main.js';
import { renderThumbnails } from './thumbnails.js';


const uploadForm = document.querySelector('.img-upload__form');
const hashtagInput = uploadForm.querySelector('.text__hashtags');
const descriptionInput = uploadForm.querySelector('.text__description');
const fileInput = uploadForm.querySelector('.img-upload__input');
const uploadOverlay = document.querySelector('.img-upload__overlay'); // Блок формы
const closeButton = uploadOverlay.querySelector('.img-upload__cancel'); // Крестик
const scaleSmaller = uploadOverlay.querySelector('.scale__control--smaller');
const scaleBigger = uploadOverlay.querySelector('.scale__control--bigger');
const scaleValue = uploadOverlay.querySelector('.scale__control--value');

let currentScale = 100;

// Инициализация Pristine
const pristine = new Pristine(uploadForm, {
classTo: 'img-upload__form',
errorTextParent: 'img-upload__form',
errorTextClass: 'form__error',
}, true);

// Проверка хэш-тегов
function validateHashtags(value) {
if (!value) {
return true; // Поле не обязательное
}
const hashtags = value.trim().toLowerCase().split(/\s+/);
const hashtagPattern = /^#[a-zа-яё0-9]{1,19}$/;

if (hashtags.length > 5) {
return false; // Максимум 5 хэштегов
}
return hashtags.every((tag) => hashtagPattern.test(tag)) &&
new Set(hashtags).size === hashtags.length; // Проверка дубликатов
}

pristine.addValidator(
hashtagInput,
validateHashtags,
'Хэш-теги должны начинаться с #, быть не длиннее 20 символов и без повторений. Максимум 5 хэш-тегов.'
);

// Валидация комментария
function validateDescription(value) {
return value.length <= 140;
}

pristine.addValidator(
descriptionInput,
validateDescription,
'Комментарий не должен превышать 140 символов.'
);

const previewImage = uploadOverlay.querySelector('.img-upload__preview img'); // Пример выбора превью
fileInput.addEventListener('change', () => {
const file = fileInput.files[0];
if (file) {
const imageUrl = URL.createObjectURL(file);
previewImage.src = imageUrl; // Обновляем изображение
uploadOverlay.classList.remove('hidden'); // Показываем форму
document.body.classList.add('modal-open'); // Добавляем класс modal-open

// Освобождение памяти после подгрузки
previewImage.onload = () => {
URL.revokeObjectURL(imageUrl);
};
}
});

// Функция для применения масштаба
function applyScale(scale) {
scaleValue.value = `${scale}%`;
const scaleFactor = scale / 100;
previewImage.style.transform = `scale(${scaleFactor})`;
}

// Уменьшение масштаба
scaleSmaller.addEventListener('click', () => {
if (currentScale > 25) {
currentScale -= 25;
applyScale(currentScale);
}
});

// Увеличение масштаба
scaleBigger.addEventListener('click', () => {
if (currentScale < 100) {
currentScale += 25;
applyScale(currentScale);
}
});


function resetForm() {
uploadForm.reset();
pristine.reset();
uploadOverlay.classList.add('hidden');
document.body.classList.remove('modal-open');
fileInput.value = ''; // Очищаем контрол загрузки файла
currentScale = 100; // Сбрасываем масштаб
applyScale(currentScale);
previewImage.className = ''; // Удаляем классы эффектов
}

// Закрытие формы по Esc
document.addEventListener('keydown', (evt) => {
if (evt.key === 'Escape' && document.activeElement !== hashtagInput && document.activeElement !== descriptionInput) {
resetForm();
}
});

// Закрытие формы по клику на крестик
closeButton.addEventListener('click', () => {
resetForm();
});

// Обработчик отправки формы
uploadForm.addEventListener('submit', (evt) => {
evt.preventDefault();
const isValid = pristine.validate();
if (isValid) {
const formData = new FormData(uploadForm);
const submitButton = uploadForm.querySelector('.img-upload__submit');
submitButton.disabled = true; // Блокируем кнопку

fetch('https://29.javascript.htmlacademy.pro/kekstagram', {
method: 'POST',
body: formData,
})
.then((response) => {
if (response.ok) {
// В обработчике отправки формы добавляем новую фотографию
const newPhoto = {
id: photos.length + 1,
url: URL.createObjectURL(fileInput.files[0]),
description: descriptionInput.value || 'Новое фото',
likes: 0,
comments: [] // Пустой массив, если нет комментариев
};
photos.push(newPhoto); // Добавляем фото в массив
renderThumbnails([newPhoto]); // Добавляем миниатюру

showSuccessMessage(); // Показ успешного сообщения
resetForm();
} else {
throw new Error('Ошибка отправки данных');
}
})
.catch(() => {
showErrorMessage(); // Показ сообщения об ошибке
})
.finally(() => {
submitButton.disabled = false; // Разблокируем кнопку
});
}
});


function showSuccessMessage() {
const successTemplate = document.querySelector('#success').content;
const successElement = successTemplate.cloneNode(true);
document.body.appendChild(successElement);

const closeButton = document.querySelector('.success__button');

Check failure on line 166 in js/form.js

View workflow job for this annotation

GitHub Actions / Check

'closeButton' is already declared in the upper scope on line 10 column 7
const successOverlay = document.querySelector('.success');

function closeSuccess() {
successOverlay.remove();
}

closeButton.addEventListener('click', closeSuccess);
document.addEventListener('keydown', (evt) => {
if (evt.key === 'Escape') {
closeSuccess();
}
});
document.addEventListener('click', (evt) => {
if (evt.target === successOverlay) {
closeSuccess();
}
});
}

function showErrorMessage() {
const errorTemplate = document.querySelector('#error').content;
const errorElement = errorTemplate.cloneNode(true);
document.body.appendChild(errorElement);

const closeButton = document.querySelector('.error__button');

Check failure on line 191 in js/form.js

View workflow job for this annotation

GitHub Actions / Check

'closeButton' is already declared in the upper scope on line 10 column 7
const errorOverlay = document.querySelector('.error');

function closeError() {
errorOverlay.remove();
}

closeButton.addEventListener('click', closeError);
document.addEventListener('keydown', (evt) => {
if (evt.key === 'Escape') {
closeError();
}
});
document.addEventListener('click', (evt) => {
if (evt.target === errorOverlay) {
closeError();
}
});
}
4 changes: 3 additions & 1 deletion js/main.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { generatePhotos } from './data.js';
import { renderThumbnails } from './thumbnails.js';
import './form.js';

const photos = generatePhotos(); // Генерация данных

export const photos = generatePhotos(); // Экспорт массива
renderThumbnails(photos); // Отрисовка миниатюр
18 changes: 11 additions & 7 deletions js/thumbnails.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { openBigPicture } from './big-picture.js';

const thumbnailTemplate = document.querySelector('#picture').content.querySelector('.picture');
const picturesContainer = document.querySelector('.pictures');

Check failure on line 4 in js/thumbnails.js

View workflow job for this annotation

GitHub Actions / Check

'picturesContainer' is assigned a value but never used

function createThumbnail(photoData) {

Check failure on line 6 in js/thumbnails.js

View workflow job for this annotation

GitHub Actions / Check

'createThumbnail' is defined but never used
const thumbnail = thumbnailTemplate.cloneNode(true);
const img = thumbnail.querySelector('.picture__img');
img.src = photoData.url;
Expand All @@ -13,20 +13,24 @@
thumbnail.querySelector('.picture__comments').textContent = photoData.comments.length;

// Открытие полноразмерного изображения при клике
thumbnail.addEventListener('click', function () {

Check failure on line 16 in js/thumbnails.js

View workflow job for this annotation

GitHub Actions / Check

Unexpected function expression
openBigPicture(photoData); // Открываем большое изображение
});

return thumbnail;
}

function renderThumbnails(data) {
const fragment = document.createDocumentFragment();
for (let i = 0; i < data.length; i++) {
const thumbnail = createThumbnail(data[i]);
fragment.appendChild(thumbnail);
}
picturesContainer.appendChild(fragment);
function renderThumbnails(photos) {
const container = document.querySelector('.pictures'); // Контейнер для миниатюр
const template = document.querySelector('#picture').content.querySelector('.picture'); // Шаблон миниатюры

photos.forEach((photo) => {
const photoElement = template.cloneNode(true);
photoElement.querySelector('.picture__img').src = photo.url;
photoElement.querySelector('.picture__likes').textContent = photo.likes;
photoElement.querySelector('.picture__comments').textContent = photo.comments.length;
container.appendChild(photoElement);
});
}

export { renderThumbnails };
9 changes: 9 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,5 +23,8 @@
"engines": {
"node": "18",
"npm": "9"
},
"dependencies": {
"pristinejs": "^1.1.0"
}
}
13 changes: 13 additions & 0 deletions sha256-Pristine-d2ee511/.babelrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"presets": [
[
"env",
{
"modules": false
}
]
],
"plugins": [
"external-helpers"
]
}
23 changes: 23 additions & 0 deletions sha256-Pristine-d2ee511/.github/workflows/run-tests.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
name: Run tests

on:
push:
branches:
- '*'
- '*/*'
- '**'
- '!gh-pages'
pull_request:
branches:
- master

jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v1
with:
node-version: 12
- run: npm ci
- run: npm test
6 changes: 6 additions & 0 deletions sha256-Pristine-d2ee511/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
.DS_Store
.idea/*
#package-lock.json
node_modules
_site
Gemfile.lock
6 changes: 6 additions & 0 deletions sha256-Pristine-d2ee511/.npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
.idea/*
package-lock.json
node_modules
_site
Gemfile.lock
_config.yml
21 changes: 21 additions & 0 deletions sha256-Pristine-d2ee511/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2017-present, Md Shamim Hasnath

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
Loading
Loading