From 2375af98d408fa6457d101b5bb259cdca346d177 Mon Sep 17 00:00:00 2001 From: Rassmagin Alexander Date: Thu, 5 Dec 2024 04:28:17 +0300 Subject: [PATCH] fixed eventEdit --- dockerfile | 1 - .../EventCreateForm/EventCreateForm.js | 66 +++++++++++++++++-- public/index.js | 16 ++--- public/modules/handleEventsActions.js | 25 ++++--- 4 files changed, 85 insertions(+), 23 deletions(-) diff --git a/dockerfile b/dockerfile index 0c3025d..9ddf9a2 100644 --- a/dockerfile +++ b/dockerfile @@ -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" diff --git a/public/components/EventCreateForm/EventCreateForm.js b/public/components/EventCreateForm/EventCreateForm.js index 69bb933..d8d9099 100644 --- a/public/components/EventCreateForm/EventCreateForm.js +++ b/public/components/EventCreateForm/EventCreateForm.js @@ -93,7 +93,7 @@ export class EventCreateForm { }, imageInput: { - text: '', + text: 'Изображение', tag: 'input', className: 'event-create-form__input event-create-form__input--file', type: 'file', @@ -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; @@ -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; @@ -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'); @@ -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}`; +} \ No newline at end of file diff --git a/public/index.js b/public/index.js index 61320d5..dbea4a4 100644 --- a/public/index.js +++ b/public/index.js @@ -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 @@ -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); @@ -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)); }, }; diff --git a/public/modules/handleEventsActions.js b/public/modules/handleEventsActions.js index 00d3932..20bf76a 100644 --- a/public/modules/handleEventsActions.js +++ b/public/modules/handleEventsActions.js @@ -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(); @@ -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); @@ -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 @@ -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(); @@ -177,7 +188,6 @@ 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 @@ -185,7 +195,6 @@ export async function handleCreateEventSubmit(event, pageToCome, navigate) { throw new Error(data.message); } const data = await response.json(); - console.log(data); if (data.code) { throw new Error(data.message); }