|
| 1 | +import { isHashtagValid, error } from './hashtag-validator'; |
| 2 | +import { isEscapeKey } from './utils'; |
| 3 | + |
| 4 | +const uploadForm = document.querySelector('.img-upload__form'); |
| 5 | +const pageBody = document.body; |
| 6 | + |
| 7 | +const uploadFileControl = uploadForm.querySelector('#upload-file'); |
| 8 | +const photoEditorForm = uploadForm.querySelector('.img-upload__overlay'); |
| 9 | +const resetPhotoEditorFormButton = uploadForm.querySelector('.img-upload__cancel'); |
| 10 | + |
| 11 | +const hashtagInput = uploadForm.querySelector('.text__hashtags'); |
| 12 | +const commentInput = uploadForm.querySelector('.text__description'); |
| 13 | + |
| 14 | +function onResetFormButton(){ |
| 15 | + closePhotoEditorForm(); |
| 16 | +} |
| 17 | + |
| 18 | +function onDocumentKeyDown(evt) { |
| 19 | + if(isEscapeKey(evt)){ |
| 20 | + if(document.activeElement === hashtagInput || document.activeElement === commentInput){ |
| 21 | + evt.stopPropagation(); |
| 22 | + } else { |
| 23 | + uploadForm.reset(); |
| 24 | + closePhotoEditorForm(); |
| 25 | + } |
| 26 | + } |
| 27 | +} |
| 28 | + |
| 29 | +const pristine = new Pristine(uploadForm, { |
| 30 | + classTo: 'img-upload__field-wrapper', |
| 31 | + errorClass: 'img-upload__field-wrapper--error', |
| 32 | + errorTextParent: 'img-upload__field-wrapper', |
| 33 | +}); |
| 34 | + |
| 35 | +function closePhotoEditorForm(){ |
| 36 | + photoEditorForm.classList.add('hidden'); |
| 37 | + pageBody.classList.remove('modal-open'); |
| 38 | + resetPhotoEditorFormButton.removeEventListener('click', onResetFormButton); |
| 39 | + document.removeEventListener('keydown', onDocumentKeyDown); |
| 40 | + uploadFileControl.value = ''; |
| 41 | + pristine.reset(); |
| 42 | + |
| 43 | +} |
| 44 | + |
| 45 | +function initUploadModal() { |
| 46 | + uploadFileControl.addEventListener('change', () => { |
| 47 | + photoEditorForm.classList.remove('hidden'); |
| 48 | + pageBody.classList.add('modal-open'); |
| 49 | + resetPhotoEditorFormButton.addEventListener('click', onResetFormButton); |
| 50 | + document.addEventListener('keydown', onDocumentKeyDown); |
| 51 | + }); |
| 52 | +} |
| 53 | + |
| 54 | +function onHashtagInput() { |
| 55 | + isHashtagValid(hashtagInput.value); |
| 56 | +} |
| 57 | + |
| 58 | +function onFormSubmit(evt) { |
| 59 | + evt.preventDefault(); |
| 60 | + if(pristine.validate()) { |
| 61 | + hashtagInput.value = hashtagInput.value.trim().replaceAll(/\s+/g, ' '); |
| 62 | + uploadForm.submit(); |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +pristine.addValidator(hashtagInput, isHashtagValid, error, 2, false); |
| 67 | + |
| 68 | +hashtagInput.addEventListener('input', onHashtagInput); |
| 69 | + |
| 70 | +uploadForm.addEventListener('submit', onFormSubmit); |
| 71 | + |
| 72 | +export { initUploadModal }; |
0 commit comments