-
Notifications
You must be signed in to change notification settings - Fork 1
Правда или действие #10
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
Правда или действие #10
Conversation
js/photo_upload_form.js
Outdated
| } | ||
| } | ||
|
|
||
| function onDescriptionInput () { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
ожидаются стрелочные функции - надо проверить весь код
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
убрал фанкшен декларейшен
js/validation_description.js
Outdated
| const validateDescription = (value) => { | ||
| errorMessage = ''; | ||
|
|
||
| const inputText = value; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
с большей вероятностью, нет необходимости в новой константе - используем имеющуюся
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
убрал константу
js/validation_description.js
Outdated
| @@ -0,0 +1,33 @@ | |||
| const DESCRIPTION_SYMBOLS_MAX = 140; | |||
|
|
|||
| let errorMessage = ''; | |||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Скорее всего, в этой переменной нет необходимости - экспортировать ее нельзя, а функции валидации обычно детерминированные
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
убрал переменную, сделал обьект
js/validation_description.js
Outdated
| } | ||
| ]; | ||
|
|
||
| return rules.every((rule) => { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Можно вернуть код ошибки, если она есть или false (null), если ошибки нет
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
функция переделана
js/validation_description.js
Outdated
| }); | ||
| }; | ||
|
|
||
| const errorDescription = () => errorMessage; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
ошибку удобнее получить от функции валидации
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
исправлено на const getError = (field) => () => errors[field]
js/validation_description.js
Outdated
| const errorDescription = () => errorMessage; | ||
|
|
||
|
|
||
| export { validateDescription, errorDescription }; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
функции валидации удобнее размесить в одном модуле validate.js
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
обьединил модули
js/validation_description.js
Outdated
| return true; | ||
| } | ||
|
|
||
| const rules = [ |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Вот это можно обсудить, чтобы реализовать более оптимальное решение
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
обсудили, исправили
js/photo_upload_form.js
Outdated
| function onHashtagsInput () { | ||
| if (pristine.validate()) { | ||
| imgUploadSubmit.disabled = false; | ||
| } else { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
секция else избыточная
if (условие) {
// действие
return
}
// действие
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
исправил
js/photo_upload_form.js
Outdated
| } | ||
|
|
||
| const onDocumentKeydown = (event) => { | ||
| if (isEscapeKey(event)) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
сначала отсекаем ненужные кейсы
if (!isEscapeKey) {
return;
}
После упрощаем условие, отсекая else
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
поправил немного по другому, нужно проверить
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
через тернарный оператор
js/photo_upload_form.js
Outdated
| const onDocumentKeydown = (event) => { | ||
| if (isEscapeKey(event)) { | ||
| if (document.activeElement === inputHashtags || document.activeElement === inputDescription) { | ||
| event.stopPrepagation(); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Точно ли необходимо останавливать распространение? Если не убрать, на что может повлиять?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
сделал без stopPrepagation();
js/photo_upload_form.js
Outdated
| const body = document.querySelector('body'); | ||
| const overlayForm = document.querySelector('.img-upload__overlay'); | ||
| const closeBtnForm = overlayForm.querySelector('.img-upload__cancel'); | ||
| const UploadForm = document.querySelector('.img-upload__form'); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Именование констант и переменных начинается со строчных букв - camelCase.
С прописных именуются компоненты и классы - PascalCase
Неизменные константы пишем прописными - UPPER_CASE
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
исправил
js/photo_upload_form.js
Outdated
| const UploadForm = document.querySelector('.img-upload__form'); | ||
| const inputDescription = UploadForm.querySelector('.text__description'); | ||
| const inputHashtags = UploadForm.querySelector('.text__hashtags'); | ||
| const UploadSubmit = UploadForm.querySelector('.img-upload__submit'); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Именование констант и переменных начинается со строчных букв - camelCase.
С прописных именуются компоненты и классы - PascalCase
Неизменные константы пишем прописными - UPPER_CASE
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
исправил
js/photo_upload_form.js
Outdated
| if (pristine.validate()) { | ||
| UploadSubmit.disabled = false; | ||
| return; | ||
| } UploadSubmit.disabled = true; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Новая команда после условия - полезно разместить с новой строки
js/photo_upload_form.js
Outdated
| } UploadSubmit.disabled = true; | ||
| }; | ||
|
|
||
| const onDocumentKeydown = (event) => isEscapeKey(event) && (document.activeElement === inputHashtags || document.activeElement === inputDescription ? event.stopPropagation() : closeFormUpload());// eslint-disable-line |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Полезно отменять конкретное правило линтера. Если строка длинная, можно попробовать корректно перенести условия
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
В данной ситуации удобнее использовать условие if:
- от этой функции не ожидается возвращаемый результат - т.е., return в ней не требуется
- вызываемые в тернарном операторе функции тоже не возвращают какой-либо результат
В таких случаях:
if (условие) {
действиеА
return;
}
действиеБ
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Есть ли необходимость останавливать распространение события?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
исправил с if, но нужно обсудить
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
функция переписана без остановки события и без тернарного оператора
js/photo_upload_form.js
Outdated
|
|
||
| const onDocumentKeydown = (event) => isEscapeKey(event) && (document.activeElement === inputHashtags || document.activeElement === inputDescription ? event.stopPropagation() : closeFormUpload());// eslint-disable-line | ||
|
|
||
| const onClickCloseBtnForm = () => closeFormUpload();// eslint-disable-line |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Так же - полезно указать, какое правило отменяется. Сейчас неочевидна причина отмены
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Можем использовать closeFormeUpload без этой функции?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
тогда в функции closeFormeUpload, она будет использовать сама себя
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
теперь причина отмены понятна, функция сделана через if
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
closeFormUpload - мы не можем использовать без этой функции
при удалении обработчика мы используем onClickCloseBtnForm внутри closeFormUpload
js/photo_upload_form.js
Outdated
| const onDocumentKeydown = (event) => isEscapeKey(event) && (document.activeElement === inputHashtags || document.activeElement === inputDescription ? event.stopPropagation() : closeFormUpload());// eslint-disable-line | ||
|
|
||
| const onClickCloseBtnForm = () => closeFormUpload();// eslint-disable-line | ||
|
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Принято не оставлять в коде более одной пустой строки
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
оставил две строки только в тех местах, где логическое отделение блоков кода
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
исправлено
js/photo_upload_form.js
Outdated
|
|
||
| uploadFile.addEventListener('change', onClickFormUpload); | ||
|
|
||
| pristine.addValidator(inputHashtags, validateHashtags, getError('tags'), 1, false); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Имена полей (tags и description) и значения 1, 2 - это было бы полезно вынести в константы. Предлагаю это обсудить отдельно
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
приоритет валидации (1 и 2) убрал, не нашел смысловой нагрузки в нем.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
значения 1 и 2 убрал, они отвечали за приоритет валидации, однако в ТЗ не указан приоритет валидации
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
добавил константы, нужно обсудить
js/validation.js
Outdated
| }; | ||
|
|
||
| const validateHashtags = (value) => { | ||
|
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
много пустых строк - разряженный текст сложно читать:
- пустые строки отделяют функции - перед и после
- пустую строку часто оставляем перед
return - можем отделить крупные логические блоки
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
поправил
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
убрал избыточные пустые строки
js/validation.js
Outdated
|
|
||
|
|
||
| const validateDescription = (inputText) => { | ||
|
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Можем исключить пустую строку перед первым условием в функции
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
убрал пустую строку
js/validation.js
Outdated
| } | ||
| ]; | ||
|
|
||
| return rules.every((rule) => { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Избыточная конструкция. В данном случае она повторяет код другой функции и напрашивается вынесение этого решения в отдельную функцию.
Чтобы такого желания не было:
if (inputText.length > DESCRIPTION_SYMBOLS_MAX) {
действие
}
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
исправил
js/validation.js
Outdated
| return true; | ||
| } | ||
|
|
||
| const rules = [ |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Здесь список не требуется
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
исправил
js/validation.js
Outdated
| return true; | ||
| } | ||
|
|
||
| const inputArray = inputText.split(/\s+/); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Неполезно использовать венгерскую нотацию - не добавляем в названия сущностей их тип. Когда задаем вопрос "что это?", ключевым должно оказать название сущности, не тип
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
изменил нейминг на inputData
js/validation.js
Outdated
|
|
||
| return rules.every((rule) => { | ||
| const isInvalid = rule.check; | ||
| if (isInvalid) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Можем упростить и исключить константу
if (rule.check) {
...
return false;
}
return true;
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
упростил и исключил константу
js/validation.js
Outdated
| error: 'Хэштеги разделяются пробелами.' | ||
| }, | ||
| { | ||
| check: inputArray.some((item, num, arr) => arr.includes(item, num + 1)), |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
numполезно заменить наi- буквойiименуем индексarr- можем не использовать аргумент, так как в замыкании есть исходная коллекция
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
поправил замечание
🎓 Правда или действие