diff --git a/public/components/EventContentPage/EventContentPage.js b/public/components/EventContentPage/EventContentPage.js index d504948..6d37e84 100644 --- a/public/components/EventContentPage/EventContentPage.js +++ b/public/components/EventContentPage/EventContentPage.js @@ -111,9 +111,14 @@ export class EventContentPage { deleteButton.className = 'buttonDelete'; deleteButton.textContent = 'Удалить мероприятие'; deleteButton.addEventListener("click", async () => { - response = await api.delete(event, event); + const request = { + headers: { + }, + credentials: 'include', + }; + response = await api.delete(`/event/${event.id}`, request); console.log(response); - //navigate("/profile", event); + navigate('/events'); }); const editButton = document.createElement('button'); diff --git a/public/components/EventCreateForm/EventCreateForm.js b/public/components/EventCreateForm/EventCreateForm.js index cee5ad8..1d68a01 100644 --- a/public/components/EventCreateForm/EventCreateForm.js +++ b/public/components/EventCreateForm/EventCreateForm.js @@ -241,7 +241,7 @@ export class EventCreateForm { renderTemplate(selectElement) { const template = Handlebars.templates['EventCreateForm.hbs']; - + const config = this.config; let itemsArray = Object.entries(config); let items = itemsArray.map(([key, {tag, text, className, type}], index) => { @@ -249,7 +249,7 @@ export class EventCreateForm { let needMaxMinTime = (type === 'time'); return {key, tag, text, className, type, needPlaceholder, needMaxMinTime}; }); - console.log(items); + //console.log(items); this.form.innerHTML += template({items}); diff --git a/public/components/Feed/Feed.js b/public/components/Feed/Feed.js index 9485056..1eb937d 100644 --- a/public/components/Feed/Feed.js +++ b/public/components/Feed/Feed.js @@ -54,7 +54,7 @@ export class Feed { * * @type {Response} */ - console.log(apiPath); + //console.log(apiPath); const response = await fetch(`${endpoint}${apiPath}`, { /** * The HTTP method for the request. @@ -70,6 +70,7 @@ export class Feed { headers: { //"Content-Type": "application/json", }, + credentials: "include", }); if (response.ok) { diff --git a/public/index.html b/public/index.html index 71bdbec..d5ad8b6 100644 --- a/public/index.html +++ b/public/index.html @@ -16,6 +16,7 @@ + diff --git a/public/index.js b/public/index.js index c3efdb5..5795341 100644 --- a/public/index.js +++ b/public/index.js @@ -20,6 +20,7 @@ import { handleRegisterSubmit, handleRegisterCheck } from './modules/registerFor import { handleLoginSubmit, handleLoginCheck } from './modules/loginForm.js'; import { EventCreateForm } from "./components/EventCreateForm/EventCreateForm.js"; import { handleCreateEventSubmit, loadCategories } from './modules/handleEventsActions.js'; +import { EditEventForm } from "./components/EditEventForm/EditEventForm.js"; /** * Get the root element @@ -77,7 +78,9 @@ const navigate = (path) => { */ window.dispatchEvent(new PopStateEvent('popstate')); }; - +let header = new Header().renderHeader(userIsLoggedIn, logout, navigate); +root.appendChild(header); +initializeApp(); /** * Update the links container */ @@ -100,8 +103,8 @@ const newsFeed = document.createElement('main'); async function initializeApp() { // Добавление header - let header = new Header().renderHeader(userIsLoggedIn, logout, navigate); - root.appendChild(header); + // let header = new Header().renderHeader(userIsLoggedIn, logout, navigate); + // root.appendChild(header); // Добавление навигации const nav = await new Nav().renderNav(); @@ -113,8 +116,6 @@ async function initializeApp() { root.appendChild(footer); } -initializeApp(); - /** * Create the response element */ @@ -174,16 +175,6 @@ const routes = { let eventPage = await new EventContentPage('event').renderTemplate(id); newsFeed.appendChild(eventPage); }, - '/events/:id/edit': async(id) => { - newsFeed.innerHTML = ''; // Clear the modal window content - const categSelect = await loadCategories(); - const formCreate = new EventCreateForm().renderTemplate(categSelect); - console.log(formCreate); - newsFeed.appendChild(formCreate); - const createBtn = document.getElementById('eventSubmitBtn'); - createBtn.addEventListener('click', (event) => handleCreateEventSubmit(event, '/my_events', navigate)); - - }, '/events/my': async(id) => { newsFeed.innerHTML = ''; // Clear the modal window content let UserEventPage = await new UserEventsPage('userEvents').renderTemplate(id); @@ -206,25 +197,27 @@ const routes = { let feed = await new Search().renderSearch('/events', window.location.search.substring(1)); newsFeed.appendChild(feed); }, - '/add_event': async() => { + '/add_event': async(id) => { newsFeed.innerHTML = ''; // Clear the modal window content const categSelect = await loadCategories(); const formCreate = new EventCreateForm().renderTemplate(categSelect); - console.log(formCreate); + //console.log(formCreate); newsFeed.appendChild(formCreate); const createBtn = document.getElementById('eventSubmitBtn'); createBtn.addEventListener('click', (event) => handleCreateEventSubmit(event, '/my_events', navigate)); }, - '/edit_event': async() => { + '/edit_event': async(id) => { newsFeed.innerHTML = ''; // Clear the modal window content const categSelect = await loadCategories(); - const formCreate = new EventCreateForm().renderTemplate(categSelect); - console.log(formCreate); + const formId = 'editEventForm'; + const editEventForm = new EditEventForm(formId); + + const formCreate = editEventForm.renderTemplate(categSelect); newsFeed.appendChild(formCreate); - const createBtn = document.getElementById('eventSubmitBtn'); - createBtn.addEventListener('click', (event) => handleCreateEventSubmit(event, '/my_events', navigate)); - + await editEventForm.init(id); + const editBtn = document.getElementById('editSubmitBtn'); + editBtn.addEventListener('click', (event) => handleCreateEventEdit(event, '/my_events', navigate)); }, }; @@ -243,6 +236,7 @@ const defaultRoute = () => { /** * URL bar listener */ +//This segment is enacted on URL change window.addEventListener('popstate', () => { const path = window.location.pathname; const route = routes[path]; @@ -251,7 +245,12 @@ window.addEventListener('popstate', () => { * Call the events route function */ const id = path.split('/')[2]; - routes['/events/:id'](id); + if (path.split('/')[3] === "edit") { + routes['/edit_event'](id); + } else { + routes['/events/:id'](id); + } + //routes['/events/:id'](id); } else if (/\/events\/categories\/\d+/.test(path)) { /** @@ -274,6 +273,7 @@ const currentPath = window.location.pathname; /** * Check if the current path is the login or signup page */ +//This segment is enacted on refresh if (currentPath === '/login' || currentPath === '/signup' || currentPath == '/profile' || currentPath == '/search') { /** * Get the route for the current path @@ -295,14 +295,12 @@ if (currentPath === '/login' || currentPath === '/signup' || currentPath == '/pr * Call the events route function */ const id = currentPath.split('/')[2]; - routes['/events/:id'](id); // Вызываем обработчик с id -} else if (/\/events\/\d+(\/edit)?/.test(currentPath)) { - /** - * Call the events route function - */ - const id = currentPath.split('/')[2]; - routes['/events/:id/edit'](id); // Вызываем обработчик с id -} else if (/\/events\/categories\/\d+/.test(currentPath)) { + if (currentPath.split('/')[3] === "edit") { + routes['/edit_event'](id); + } else { + routes['/events/:id'](id); + } // Вызываем обработчик с id +} else if (/\/events\/categories\/\d+/.test(currentPath)) { /** * Call the events route function */ diff --git a/public/modules/handleEventsActions.js b/public/modules/handleEventsActions.js index 4700b93..d4c2f6c 100644 --- a/public/modules/handleEventsActions.js +++ b/public/modules/handleEventsActions.js @@ -60,14 +60,14 @@ const INCORRECT_EMAIL = 'Адрес email должен содержать нес export async function loadCategories() { const selectElement = document.createElement('select'); - console.log(selectElement); + //console.log(selectElement); try { const request = { headers: {} }; const response = await api.get('/categories', request); const categories = await response.json(); - console.log(categories); + //console.log(categories); // Заполнение выпадающего списка categories.forEach(category => { @@ -83,26 +83,100 @@ export async function loadCategories() { return selectElement; } -export async function handleDeleteEventSubmit(event, id, pageToCome) { + +export async function handleCreateEventEdit(event, pageToCome, navigate) { event.preventDefault(); + loadCategories(); + // Get form data + const title = removeDangerous(document.getElementById('eventNameEntry').value); + const description = removeDangerous(document.getElementById('eventDescriptionEntry').value); + const tags = removeDangerous(document.getElementById('eventTagsEntry').value).split(); + const dateStart = removeDangerous(document.getElementById('eventBeginEntry').value) + ':00Z'; + const dateEnd = removeDangerous(document.getElementById('eventEndEntry').value) + ':00Z'; + + const categoryId = Number(removeDangerous(document.getElementById('categoriesInput').value)); + + const image = document.getElementById('imageInput').files[0]; + console.log(title, description, tags, dateStart, dateEnd, image, categoryId); + /* + // Clear error messages + document.getElementById('registerUsernameError').innerText = ''; + document.getElementById('registerPasswordError').innerText = ''; + document.getElementById('registerEmailError').innerText = ''; + document.getElementById('registerServerError').innerText = ''; + + // Get form data + const username = removeDangerous(document.getElementById('registerUsernameEntry').value); + const email = removeDangerous(document.getElementById('registerEmailEntry').value); + const password = removeDangerous(document.getElementById('registerPasswordEntry').value); + // Initialize validation flag + let isValid = true; + + // Validate form data + if (!username) { + document.getElementById('registerUsernameError').innerText = EMPTY_FIELD; + isValid = false; + } + + if (!isValidUsername(username)) { + document.getElementById('registerUsernameError').innerText = INCORRECT_USERNAME; + isValid = false; + } + + if (!isValidEmail(email)) { + document.getElementById('registerEmailError').innerText = INCORRECT_EMAIL; + isValid = false; + } + + if (!isValidPassword(password)) { + document.getElementById('registerPasswordError').innerText = INCORRECT_PASSWORD; + isValid = false; + } + + // If form data is invalid, exit function + if (!isValid) { + return; + } + */ try { // Send request to backend + const userData = { + title: title, + description: description, + tags: tags, + event_start: dateStart, + event_end: dateEnd, + category_id: categoryId, + }; + + const json = JSON.stringify(userData); + const formData = new FormData(); + formData.append('json', json); + formData.append('image', image); + const body = formData; const request = { headers: { }, credentials: 'include', + + body: body, }; - console.log('ID', id); - const path = '/events'+'/'+id; - const response = await api.delete(path, request); + const path = '/events'; + const response = await api.put(path, request); + // If response is not OK, throw error if (!response.ok) { throw new Error(data.message); } - + + const data = await response.json(); + if (data.code) { + throw new Error(data.message); + } + // Navigate to page navigate(pageToCome); @@ -113,7 +187,9 @@ export async function handleDeleteEventSubmit(event, id, pageToCome) { //navigate(pageToCome); //debug } -export async function handleEditEventSubmit(event, pageToCome, navigate) { +export async function handleCreateEventSubmit(event, pageToCome, navigate) { + + event.preventDefault(); // Get form data diff --git a/public/modules/loginForm.js b/public/modules/loginForm.js index 6b2422f..ff6d37c 100644 --- a/public/modules/loginForm.js +++ b/public/modules/loginForm.js @@ -96,7 +96,7 @@ export async function handleLoginSubmit(event, setUserLoggedIn, navigate) { navigate("events"); } } catch (error) { - document.getElementById('loginServerError').innerText = 'Неверный логин или пароль'; + document.getElementById('loginServerError').innerText = error; } }