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

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

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
8 changes: 4 additions & 4 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<script src="vendor/pristine/pristine.min.js"></script>
<script src="./js/functions.js"></script>
<script src="./js/main.js" type="module"></script>
<link rel="stylesheet" href="css/normalize.css">
Expand Down Expand Up @@ -32,11 +33,11 @@ <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" action="https://29.javascript.htmlacademy.pro/kekstagram" method="post" enctype="multipart/form-data" autocomplete="off" required >

<!-- Изначальное состояние поля для загрузки изображения -->
<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 Expand Up @@ -121,7 +122,7 @@ <h2 class="img-upload__title visually-hidden">Загрузка фотограф
<input class="text__hashtags" name="hashtags" placeholder="#ХэшТег">
</div>
<div class="img-upload__field-wrapper">
<textarea class="text__description" name="description" placeholder="Ваш комментарий..."></textarea>
<textarea class="text__description" name="description" maxlength="140" placeholder="Ваш комментарий..."></textarea>
</div>
</fieldset>

Expand Down Expand Up @@ -228,6 +229,5 @@ <h2 class="success__title">Изображение успешно загруже
</div>
</section>
</template>

</body>
</html>
8 changes: 7 additions & 1 deletion js/constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,10 @@ const DESCRIPTIONS = [
"В качалке с друзьями",
"Гламур"
];
export {POST_COUNT,NAMES,MESSAGES,DESCRIPTIONS};
const FILE_TYPES = [
"jpg",
"jpeg",
"png"
];
export {POST_COUNT,NAMES,MESSAGES,DESCRIPTIONS, FILE_TYPES};

175 changes: 175 additions & 0 deletions js/form-filling.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
import {isEscapeKey} from"./util.js";
const imgInput = document.querySelector(".img-upload__input");
const body = document.body;
const imgOverlay = document.querySelector(".img-upload__overlay");
const closeImg = document.querySelector(".img-upload__cancel");
const postForm = document.querySelector(".img-upload__form");
const formButton = document.querySelector(".img-upload__submit");
const pristine = new Pristine(postForm, {
classTo: "img-upload__text",
errorTextParent: "img-upload__text",
});
const regexp = /^#[^\s#]+$/i;

imgInput.addEventListener("change", (evt) => {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Почему нельзя все это сделать в одном событии? Сейчас неочевидна логика работы(

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Надеюсь правильно поняла, теперь у меня в слушателе для input вызываются слушатели на другие кнопки

evt.preventDefault();
imgOverlay.classList.remove("hidden");
body.classList.add("modal-open");
pristine.validate();
closeFormClick();
// eslint-disable-next-line no-shadow
postForm.addEventListener("submit",(evt) => {
evt.preventDefault();
formButton.disabled = true;
if(pristine.validate()){
openSuccess();
}else {
openError();
}
formButton.disabled = false;
});
});

function validateHashtags (value) {
const valueTrim = value.trim();
const hashtags = valueTrim.split(" ");
if (valueTrim === "") {
return true;
}
pristine.errorText = "введён невалидный хэш-тег";
return hashtags.every((hashtag) => regexp.test(hashtag));
}
function validateComment (value) {
if (value.trim() === "") {
return true;
}
return value.length <= 140;
}
const hastags = document.querySelector(".text__hashtags");
const postText = document.querySelector(".text__description");

function dublicateHashtags(value) {
const hashtags = value.trim().split(" ");
for (let i = 0; i < hashtags.length; i++){
const hashtag = hashtags[i].toLowerCase();
if (hashtags.slice(0, i).includes(hashtag)) {
pristine.errorText = "хэш-теги повторяются";
return false;
}
}
return true;
}

pristine.addValidator(

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Так как ты навешиваешь несколько валидаций на теги, может быть сразу несколько сообщений подряд. Лучше такого избегать. То есть использовать одну функции и сообщении по какому-то приоритету показывать
image

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Исправила

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍🏻

hastags,
(value) => {
if (!validateHashtags(value)) {
return false;
}
if (!dublicateHashtags(value)) {
return false;
}

return true;
},
() => pristine.errorText
);

pristine.addValidator(
postText,
validateComment,
"комментарий не может содрежать больше 140 символов"
);


function openSuccess (){
const successTemplate = document.querySelector("#success").content;
const successElement = successTemplate.cloneNode(true).querySelector(".success");
const successButton = successElement.querySelector(".success__button");
const successInner = successElement.querySelector(".success__inner");

document.body.append(successElement);
hastags.value = "";
postText.value = "";

successButton.addEventListener("click", closeSuccess);
document.addEventListener("keydown", closeSuccessEscape);
document.addEventListener("click", closeOutside);

function closeSuccess(){
successElement.remove();
document.removeEventListener("keydown",closeSuccessEscape);
document.removeEventListener("click",closeOutside);
imgOverlay.classList.add("hidden");
body.classList.remove("modal-open");
}

function closeSuccessEscape (evt){
if(isEscapeKey(evt)) {
evt.preventDefault();
closeSuccess();
}

}
function closeOutside(evt){
if (!successInner.contains(evt.target)){
closeSuccess();
}
}
}


function openError (){
const errorTemplate = document.querySelector("#error").content;
const errorElement = errorTemplate.cloneNode(true).querySelector(".error");
const errorButton = errorElement.querySelector(".error__button");
const errorInner = errorElement.querySelector(".error__inner");

document.body.append(errorElement);


errorButton.addEventListener("click", closeError);
document.addEventListener("keydown", closeErrorEscape);
document.addEventListener("click", closeOutside);
document.removeEventListener("click",closeForm);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Может без слушателя лучше, а внутрь других слушателей сложить?

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍🏻


function closeError(){
errorElement.remove();
document.removeEventListener("keydown",closeErrorEscape);
document.removeEventListener("click",closeOutside);
}

function closeErrorEscape (evt){
if(isEscapeKey(evt)) {
evt.preventDefault();
closeError();
imgOverlay.classList.remove("hidden");

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

В других обработчиках нет этого(

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

В других обработчиках нет этого, так как при нажатии на esc без этой строчки с убиранием класса hidden, у меня закрывалось и модальное окно с фотографией, а в других случаях такого не было

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍🏻

body.classList.add("modal-open");
}

}
function closeOutside(evt){
if (!errorInner.contains(evt.target)){
closeError();
}
}
}

function closeForm(){

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

На закрытие нужно обнулять состояния и скидывать загруженное фото. Сейчас странно работает. Если закрыть через кнопку, то можно загрузить тоже фото, если закрыть через esc, тоже фото нельзя загрузить - оно не сбрасывается из инпута скорее всего.

Плюс слушатели закрытия на закрытие нужно удалять

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Теперь удаляю форму и слушатель на закрытие

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍🏻

imgOverlay.classList.add("hidden");
body.classList.remove("modal-open");
postForm.reset();
document.removeEventListener(closeFormClick);
}

function closeFormClick (){
closeImg.addEventListener("click",closeForm);
document.addEventListener("keydown", (evt) => {
if (isEscapeKey(evt)) {
evt.preventDefault();
closeForm();
}
});
}


3 changes: 3 additions & 0 deletions js/main.js
Original file line number Diff line number Diff line change
@@ -1,2 +1,5 @@
import {renderPosts} from"./posts-rendering.js";
import "./form-filling.js";
import {loadPhoto} from "./photo-load.js";
renderPosts();
loadPhoto();
16 changes: 16 additions & 0 deletions js/photo-load.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import {FILE_TYPES} from "./constants.js";
function loadPhoto(){
const imgInput = document.querySelector(".img-upload__input");
const preview = document.querySelector(".img-upload__preview img");

imgInput.addEventListener("change", () => {
const file = imgInput.files[0];
const fileName = file.name.toLowerCase();
const matches = FILE_TYPES.some((it) => fileName.endsWith(it));
if(matches){
preview.src = URL.createObjectURL(file);
}
});
}

export{loadPhoto};
Loading