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

Kobranch2 #10

Open
wants to merge 4 commits into
base: eventpage_content
Choose a base branch
from
Open
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
9 changes: 7 additions & 2 deletions public/components/EventContentPage/EventContentPage.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down
4 changes: 2 additions & 2 deletions public/components/EventCreateForm/EventCreateForm.js
Original file line number Diff line number Diff line change
Expand Up @@ -241,15 +241,15 @@ 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) => {
let needPlaceholder = (tag === 'input');
let needMaxMinTime = (type === 'time');
return {key, tag, text, className, type, needPlaceholder, needMaxMinTime};
});
console.log(items);
//console.log(items);

this.form.innerHTML += template({items});

Expand Down
3 changes: 2 additions & 1 deletion public/components/Feed/Feed.js
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -70,6 +70,7 @@ export class Feed {
headers: {
//"Content-Type": "application/json",
},
credentials: "include",
});

if (response.ok) {
Expand Down
1 change: 1 addition & 0 deletions public/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
<script src="/components/Login/Login.precompiled.js"></script>
<script src="/components/Nav/Nav.precompiled.js"></script>
<script src="/components/EventCreateForm/EventCreateForm.precompiled.js"></script>
<script src="/components/EditEventForm/EditEventForm.precompiled.js"></script>
<script type="module" src="/index.js"></script>
</body>
</html>
62 changes: 30 additions & 32 deletions public/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
*/
Expand All @@ -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();
Expand All @@ -113,8 +116,6 @@ async function initializeApp() {
root.appendChild(footer);
}

initializeApp();

/**
* Create the response element
*/
Expand Down Expand Up @@ -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);
Expand All @@ -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));
},
};

Expand All @@ -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];
Expand All @@ -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)) {
/**
Expand All @@ -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
Expand All @@ -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
*/
Expand Down
92 changes: 84 additions & 8 deletions public/modules/handleEventsActions.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 => {
Expand All @@ -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);

Expand All @@ -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
Expand Down
2 changes: 1 addition & 1 deletion public/modules/loginForm.js
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ export async function handleLoginSubmit(event, setUserLoggedIn, navigate) {
navigate("events");
}
} catch (error) {
document.getElementById('loginServerError').innerText = 'Неверный логин или пароль';
document.getElementById('loginServerError').innerText = error;
}
}

Expand Down