Skip to content

Commit

Permalink
fixed eventEdit
Browse files Browse the repository at this point in the history
  • Loading branch information
Ko71k committed Dec 5, 2024
1 parent bc89136 commit 2375af9
Show file tree
Hide file tree
Showing 4 changed files with 85 additions and 23 deletions.
1 change: 0 additions & 1 deletion dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ RUN npm install handlebars
COPY . .

# Запускаем команду Handlebars
RUN node ./node_modules/handlebars/bin/handlebars public/components/EditEventForm/EditEventForm.hbs -f public/components/EditEventForm/EditEventForm.precompiled.js || echo "Handlebars command failed"
RUN node ./node_modules/handlebars/bin/handlebars public/components/EventCreateForm/EventCreateForm.hbs -f public/components/EventCreateForm/EventCreateForm.precompiled.js || echo "Handlebars command failed"
RUN node ./node_modules/handlebars/bin/handlebars public/components/Login/Login.hbs -f public/components/Login/Login.precompiled.js || echo "Handlebars command failed"
RUN node ./node_modules/handlebars/bin/handlebars public/components/Nav/Nav.hbs -f public/components/Nav/Nav.precompiled.js || echo "Handlebars command failed"
Expand Down
66 changes: 62 additions & 4 deletions public/components/EventCreateForm/EventCreateForm.js
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ export class EventCreateForm {
},

imageInput: {
text: '',
text: 'Изображение',
tag: 'input',
className: 'event-create-form__input event-create-form__input--file',
type: 'file',
Expand All @@ -119,7 +119,7 @@ export class EventCreateForm {
* Renders the form template
* @returns {HTMLFormElement} The rendered form
*/
renderTemplate(selectElement) {
renderTemplate(selectElement, eventData) {
const template = Handlebars.templates['EventCreateForm.hbs'];

const config = this.config;
Expand Down Expand Up @@ -162,8 +162,45 @@ export class EventCreateForm {
mapContainer.style.height = '400px'; // Высота карты
this.form.insertBefore(mapContainer, this.form.querySelector('.event-create-form__submit-btn'));

let mock_data = { latitude: 55.79720450649618, longitude: 37.53777629133753, zoom: 17, needMark: false };
if (eventData) {
const submitButton = this.form.querySelector('.event-create-form__submit-btn');
submitButton.innerHTML = 'Сохранить';
const mapping = {
title: 'eventNameEntry',
image: 'imageInput',
description: 'eventDescriptionEntry',
category_id: 'categories',
tag: 'eventTagEntry',
category_id: "categoriesInput",
};
const time = {
event_start: 'eventBeginEntry',
event_end: 'eventEndEntry',
};
for (const key in mapping) {
const inputElement = this.form.querySelector(`[id="${mapping[key]}"]`);
if (inputElement) {
if (mapping[key] === 'imageInput') {
inputElement.src = eventData[key];
} else
if (mapping[key] === 'eventTagEntry') {
inputElement.value = eventData[key].join(' ');
} else {
inputElement.value = eventData[key];
}
}
}
for (const key in time) {
const inputElement = this.form.querySelector(`[id="${time[key]}"]`);
if (inputElement) {
inputElement.value = formatDateTimeForInput(eventData[key]);
}
}
mock_data = { latitude: eventData.Latitude, longitude: eventData.Longitude, zoom: 17, needMark: true};
}

// Инициализация карты
const mock_data = { latitude: 55.79720450649618, longitude: 37.53777629133753, zoom: 17 };
ymaps.ready(() => this.initMap(mock_data));

return this.form;
Expand All @@ -173,6 +210,19 @@ export class EventCreateForm {
center: [mock_data.latitude, mock_data.longitude],
zoom: mock_data.zoom,
});
if (mock_data.needMark) {
const coords = myMap.getCenter();
this.currentPlacemark = new ymaps.Placemark(coords, {
hintContent: 'Новая метка',
}, {
iconLayout: 'default#image',
iconImageHref: '/static/images/location.png',
iconImageSize: [32, 32],
iconImageOffset: [-16, -32]
});
// Добавляем новую метку на карту
myMap.geoObjects.add(this.currentPlacemark);
}
// Обработчик события клика на карту
myMap.events.add('mousedown', (e) => {
const coords = e.get('coords');
Expand Down Expand Up @@ -201,8 +251,16 @@ export class EventCreateForm {
});
// Добавляем новую метку на карту
myMap.geoObjects.add(this.currentPlacemark);
console.log(selectedPoint);
});
}
}

function formatDateTimeForInput(dateTime) {
const date = new Date(dateTime);
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0'); // Months are 0-indexed
const day = String(date.getDate()).padStart(2, '0');
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
return `${year}-${month}-${day}T${hours}:${minutes}`;
}
16 changes: 6 additions & 10 deletions public/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,7 @@ import { checkSession } from './modules/session.js';
import { handleRegisterSubmit, handleRegisterCheck } from './modules/registerForm.js';
import { handleLoginSubmit, handleLoginCheck } from './modules/loginForm.js';
import { EventCreateForm } from "./components/EventCreateForm/EventCreateForm.js";
import { handleCreateEventSubmit, loadCategories, handleCreateEventEdit } from './modules/handleEventsActions.js';
import { EditEventForm } from "./components/EditEventForm/EditEventForm.js";
import { handleCreateEventSubmit, loadCategories, loadEvent, handleCreateEventEdit } from './modules/handleEventsActions.js';

/**
* Get the root element
Expand Down Expand Up @@ -217,7 +216,7 @@ const routes = {
let feed = await new Search().renderSearch('/search', window.location.search.substring(1));
newsFeed.appendChild(feed);
},
'/add_event': async(id) => {
'/add_event': async() => {
newsFeed.innerHTML = ''; // Clear the modal window content
const categSelect = await loadCategories();
const formCreate = new EventCreateForm().renderTemplate(categSelect);
Expand All @@ -229,14 +228,11 @@ const routes = {
'/edit_event': async(id) => {
newsFeed.innerHTML = ''; // Clear the modal window content
const categSelect = await loadCategories();
const formId = 'editEventForm';
const editEventForm = new EditEventForm(formId);

const formCreate = editEventForm.renderTemplate(categSelect);
const eventData = await loadEvent(id);
const formCreate = new EventCreateForm().renderTemplate(categSelect, eventData);
newsFeed.appendChild(formCreate);
await editEventForm.init(id);
const editBtn = document.getElementById('editSubmitBtn');
editBtn.addEventListener('click', (event) => handleCreateEventEdit(event, id, navigate));
const createBtn = document.getElementById('eventSubmitBtn');
createBtn.addEventListener('click', (event) => handleCreateEventEdit(event, id, navigate));
},
};

Expand Down
25 changes: 17 additions & 8 deletions public/modules/handleEventsActions.js
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,18 @@ export async function loadCategories() {
return selectElement;
}

export async function loadEvent(eventId) {
try {
const request = { headers: {} };
const response = await api.get(`/events/${eventId}`, request);
const eventData = await response.json();
return eventData;
} catch (error) {
console.error('Ошибка при загрузке мероприятия:', error);
}
return;
}

export async function handleCreateEventEdit(event, id, navigate) {
event.preventDefault();
loadCategories();
Expand All @@ -87,19 +99,21 @@ export async function handleCreateEventEdit(event, id, navigate) {
const dateEnd = removeDangerous(document.getElementById('eventEndEntry').value) + ':00Z';
const categoryId = Number(removeDangerous(document.getElementById('categoriesInput').value));

const latitude = removeDangerous(document.getElementById('latitude').value);
const longitude = removeDangerous(document.getElementById('longitude').value);
const image = document.getElementById('imageInput').files[0];

try {
// Send request to backend
const userData = {
title: '',
title: title,
description: description,
tag: tag,
event_start: dateStart,
event_end: dateEnd,
category_id: categoryId,
Latitude: +latitude,
Longitude: +longitude,
};

const json = JSON.stringify(userData);
const formData = new FormData();
formData.append('json', json);
Expand Down Expand Up @@ -147,7 +161,6 @@ export async function handleCreateEventSubmit(event, pageToCome, navigate) {

const latitude = removeDangerous(document.getElementById('latitude').value);
const longitude = removeDangerous(document.getElementById('longitude').value);
const zoom = removeDangerous(document.getElementById('zoom').value);

try {
// Send request to backend
Expand All @@ -160,9 +173,7 @@ export async function handleCreateEventSubmit(event, pageToCome, navigate) {
category_id: categoryId,
Latitude: +latitude,
Longitude: +longitude,
zoom: zoom,
};
console.log(userData);

const json = JSON.stringify(userData);
const formData = new FormData();
Expand All @@ -177,15 +188,13 @@ export async function handleCreateEventSubmit(event, pageToCome, navigate) {
body: body,
};
const path = '/events';
console.log(request);
const response = await api.post(path, request);

// If response is not OK, throw error
if (!response.ok) {
throw new Error(data.message);
}
const data = await response.json();
console.log(data);
if (data.code) {
throw new Error(data.message);
}
Expand Down

0 comments on commit 2375af9

Please sign in to comment.