Merge pull request #11 from SlimusMinus/add-yandex_card
added card on post and feed
This commit is contained in:
@@ -10,6 +10,8 @@
|
||||
content="Web site created using create-react-app"
|
||||
/>
|
||||
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
|
||||
<script src="https://api-maps.yandex.ru/2.1/?apikey=d4696cc8-6a1f-4356-9219-108ac474093b&lang=ru_RU" type="text/javascript"></script>
|
||||
|
||||
<!--
|
||||
manifest.json provides metadata used when your web app is installed on a
|
||||
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useState } from "react";
|
||||
import {useCallback, useEffect, useState} from "react";
|
||||
import PinIcon from "./icons/PinIcon";
|
||||
import CloseIcon from "./icons/CloseIcon";
|
||||
import { EMPTY_FORM, CATEGORIES } from "../config/feedConstants";
|
||||
@@ -6,6 +6,7 @@ import { usePostMutation } from "../hooks/usePostMutation";
|
||||
import { useImageUpload, ACCEPT } from "../hooks/useImageUpload";
|
||||
import { validatePostForm } from "../utils/validatePostForm";
|
||||
import { formatPhone } from "../utils/formatPhone";
|
||||
import { useYandexMap } from "../hooks/useYandexMap";
|
||||
import { API_URL } from "../config/authConstants";
|
||||
|
||||
const MAX_SIZE_MB = 5;
|
||||
@@ -31,6 +32,7 @@ export default function CreateUpdatePost({ onClose, onSuccess, initialData }) {
|
||||
category: initialData.category || "",
|
||||
date: initialData.date || "",
|
||||
phone: initialData.phone || "",
|
||||
address: initialData.city || ""
|
||||
}
|
||||
: EMPTY_FORM
|
||||
);
|
||||
@@ -57,6 +59,24 @@ export default function CreateUpdatePost({ onClose, onSuccess, initialData }) {
|
||||
// Единый хук для создания и обновления
|
||||
const { save, loading: saving, error: apiError } = usePostMutation();
|
||||
|
||||
// Внутри компонента, рядом с другими хуками
|
||||
const initialCoords = isEdit && initialData.latitude && initialData.longitude
|
||||
? { latitude: initialData.latitude, longitude: initialData.longitude }
|
||||
: null;
|
||||
|
||||
// CreateUpdatePost.jsx
|
||||
const { mapRef, coords, address, addressRef } = useYandexMap(
|
||||
true,
|
||||
initialCoords,
|
||||
isEdit ? (initialData.location || "") : ""
|
||||
);
|
||||
// После объявления хука useYandexMap:
|
||||
useEffect(() => {
|
||||
if (address) {
|
||||
setForm(prev => ({ ...prev, address }));
|
||||
setErrors(prev => ({ ...prev, address: "" }));
|
||||
}
|
||||
}, [address]);
|
||||
// Единый флаг загрузки — блокирует кнопку отправки
|
||||
const loading = saving || compressing;
|
||||
|
||||
@@ -74,6 +94,11 @@ export default function CreateUpdatePost({ onClose, onSuccess, initialData }) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (coords && !addressRef.current) {
|
||||
setErrors(prev => ({ ...prev, map: "Подождите, адрес загружается..." }));
|
||||
return;
|
||||
}
|
||||
|
||||
const data = new FormData();
|
||||
data.append("type", form.type);
|
||||
data.append("title", form.title.trim());
|
||||
@@ -83,6 +108,17 @@ export default function CreateUpdatePost({ onClose, onSuccess, initialData }) {
|
||||
if (form.date) data.append("date", form.date);
|
||||
if (imageFile) data.append("image", imageFile);
|
||||
|
||||
if (coords) {
|
||||
data.append("latitude", coords.latitude);
|
||||
data.append("longitude", coords.longitude);
|
||||
data.append("address", form.address.trim()); // ← из поля формы
|
||||
}
|
||||
|
||||
// Адрес без координат тоже отправляем:
|
||||
if (!coords && form.address.trim()) {
|
||||
data.append("address", form.address.trim());
|
||||
}
|
||||
|
||||
// save(id, data): id = null → POST (создание), id = string → PUT (обновление)
|
||||
const result = await save(isEdit ? initialData.id : null, data);
|
||||
if (result) {
|
||||
@@ -102,7 +138,7 @@ export default function CreateUpdatePost({ onClose, onSuccess, initialData }) {
|
||||
{isEdit ? "Редактировать объявление" : "Новое объявление"}
|
||||
</span>
|
||||
<button className="f-close-btn" onClick={onClose}>
|
||||
<CloseIcon />
|
||||
<CloseIcon/>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
@@ -117,7 +153,8 @@ export default function CreateUpdatePost({ onClose, onSuccess, initialData }) {
|
||||
Потеря
|
||||
</button>
|
||||
<button
|
||||
className={`f-type-opt${form.type === "found" ? " found" : ""}`}
|
||||
className={`f-type-opt${form.type === "found" ? " found"
|
||||
: ""}`}
|
||||
onClick={() => set("type", "found")}
|
||||
>
|
||||
Находка
|
||||
@@ -148,7 +185,8 @@ export default function CreateUpdatePost({ onClose, onSuccess, initialData }) {
|
||||
value={form.description}
|
||||
onChange={e => set("description", e.target.value)}
|
||||
/>
|
||||
{errors.description && <p className="f-err-msg">{errors.description}</p>}
|
||||
{errors.description && <p
|
||||
className="f-err-msg">{errors.description}</p>}
|
||||
</div>
|
||||
|
||||
{/* Фотография: превью + удаление или загрузчик */}
|
||||
@@ -156,24 +194,27 @@ export default function CreateUpdatePost({ onClose, onSuccess, initialData }) {
|
||||
<label className="f-m-label">Фотография</label>
|
||||
{displayImage ? (
|
||||
<div className="f-img-preview-wrap">
|
||||
<img src={displayImage} alt="preview" className="f-img-preview" />
|
||||
<img src={displayImage} alt="preview"
|
||||
className="f-img-preview"/>
|
||||
<button
|
||||
className="f-img-remove"
|
||||
onClick={removeImage}
|
||||
type="button"
|
||||
aria-label="Удалить фото"
|
||||
>
|
||||
<CloseIcon />
|
||||
<CloseIcon/>
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<label className="f-img-upload-label" aria-disabled={compressing}>
|
||||
<label className="f-img-upload-label"
|
||||
aria-disabled={compressing}>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept={ACCEPT}
|
||||
// На мобильных открываем камеру напрямую
|
||||
capture={/Mobi|Android|iPhone/i.test(navigator.userAgent) ? "environment" : undefined}
|
||||
capture={/Mobi|Android|iPhone/i.test(navigator.userAgent)
|
||||
? "environment" : undefined}
|
||||
onChange={handleFileChange}
|
||||
className="f-img-input"
|
||||
disabled={compressing}
|
||||
@@ -197,18 +238,38 @@ export default function CreateUpdatePost({ onClose, onSuccess, initialData }) {
|
||||
<option value="">Выбрать...</option>
|
||||
{CATEGORIES.map(c => <option key={c} value={c}>{c}</option>)}
|
||||
</select>
|
||||
{errors.category && <p className="f-err-msg">{errors.category}</p>}
|
||||
{errors.category && <p
|
||||
className="f-err-msg">{errors.category}</p>}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Карта — заглушка, будет в следующей версии */}
|
||||
{/* Карта */}
|
||||
<div className="f-m-group">
|
||||
<label className="f-m-label">Место на карте</label>
|
||||
<div className="f-map-pick">
|
||||
<PinIcon size={14} />
|
||||
Нажмите, чтобы отметить место
|
||||
<div style={{
|
||||
width: "100%",
|
||||
height: 260,
|
||||
borderRadius: 8,
|
||||
overflow: "hidden"
|
||||
}}>
|
||||
<div ref={mapRef} style={{width: "100%", height: "100%"}}/>
|
||||
</div>
|
||||
<p className="f-hint">Карта будет добавлена в следующей версии</p>
|
||||
|
||||
{!coords && <p className="f-hint">Нажмите на карту, чтобы отметить
|
||||
место</p>}
|
||||
{errors.map && <p className="f-err-msg">{errors.map}</p>}
|
||||
</div>
|
||||
|
||||
<div className="f-m-group">
|
||||
<label className="f-m-label">Адрес</label>
|
||||
<input
|
||||
className={`f-m-field${errors.address ? " err" : ""}`}
|
||||
type="text"
|
||||
placeholder="Например: Москва, ул. Ленина, 5"
|
||||
value={form.address}
|
||||
onChange={e => set("address", e.target.value)}
|
||||
/>
|
||||
{errors.address && <p className="f-err-msg">{errors.address}</p>}
|
||||
</div>
|
||||
|
||||
{/* Телефон с автоматической маской */}
|
||||
@@ -227,9 +288,10 @@ export default function CreateUpdatePost({ onClose, onSuccess, initialData }) {
|
||||
{/* Глобальная ошибка API (не связана с конкретным полем) */}
|
||||
{apiError && <p className="f-err-msg">{apiError}</p>}
|
||||
|
||||
<button className="f-m-submit" onClick={handleSubmit} disabled={loading}>
|
||||
<button className="f-m-submit" onClick={handleSubmit}
|
||||
disabled={loading}>
|
||||
<div className="f-m-submit-row">
|
||||
{loading && <div className="f-m-spinner" />}
|
||||
{loading && <div className="f-m-spinner"/>}
|
||||
{isEdit ? "Сохранить изменения" : "Разместить объявление"}
|
||||
</div>
|
||||
</button>
|
||||
|
||||
@@ -8,39 +8,39 @@ import { API_URL } from "../config/authConstants";
|
||||
export default function PostOnFeed({ ad, liked, onLike, onEdit }) {
|
||||
const imageUrl = ad.images?.[0] ? `${API_URL}${ad.images[0]}` : null;
|
||||
|
||||
// ✅ Формируем строку адреса из city + district
|
||||
const address = [ad.city, ad.district].filter(Boolean).join(", ");
|
||||
const createdAt = ad.createdAt
|
||||
? new Date(ad.createdAt).toLocaleDateString("ru-RU")
|
||||
: null;
|
||||
|
||||
return (
|
||||
<div className="f-card">
|
||||
<div className="f-card-inner">
|
||||
|
||||
{/* Левая колонка — картинка */}
|
||||
<div className="f-card-img">
|
||||
{imageUrl
|
||||
? <img src={imageUrl} alt={ad.title} />
|
||||
: <span className="f-card-emoji">{ad.emoji || "📋"}</span>
|
||||
}
|
||||
</div>
|
||||
|
||||
{/* Правая колонка — контент */}
|
||||
<div className="f-card-body">
|
||||
<div className="f-card-badges">
|
||||
{ad.category && <div className="f-cat-badge">{ad.category}</div>}
|
||||
<div className={`f-type-badge ${ad.type === "loss" ? "f-type-loss"
|
||||
: "f-type-found"}`}>
|
||||
<div className={`f-type-badge ${ad.type === "loss" ? "f-type-loss" : "f-type-found"}`}>
|
||||
{ad.type === "loss" ? "Потеря" : "Находка"}
|
||||
</div>
|
||||
</div>
|
||||
<div className="f-card-title">{ad.title}</div>
|
||||
<div className="f-card-desc">{ad.description}</div>
|
||||
<div className="f-card-meta">
|
||||
{ad.location && <div className="f-meta-pill">
|
||||
<PinIcon/> {ad.location}</div>}
|
||||
{ad.date && <div className="f-meta-pill"><CalendarIcon/> {ad.date}
|
||||
</div>}
|
||||
{/* ✅ address вместо ad.location */}
|
||||
{address && <div className="f-meta-pill"><PinIcon /> {address}</div>}
|
||||
{/* ✅ createdAt вместо ad.date */}
|
||||
{createdAt && <div className="f-meta-pill"><CalendarIcon /> {createdAt}</div>}
|
||||
</div>
|
||||
{ad.location && (
|
||||
<button className="f-card-map"
|
||||
onClick={e => e.stopPropagation()}>
|
||||
<MapIcon/> Показать на карте — {ad.location}
|
||||
{address && (
|
||||
<button className="f-card-map" onClick={e => e.stopPropagation()}>
|
||||
<MapIcon /> Показать на карте — {address}
|
||||
</button>
|
||||
)}
|
||||
<div className="f-card-foot">
|
||||
@@ -48,34 +48,25 @@ export default function PostOnFeed({ ad, liked, onLike, onEdit }) {
|
||||
{ad.phone && (
|
||||
<a className="f-card-phone" href={`tel:${ad.phone}`}
|
||||
onClick={e => e.stopPropagation()}>
|
||||
<PhoneIcon/> {ad.phone}
|
||||
<PhoneIcon /> {ad.phone}
|
||||
</a>
|
||||
)}
|
||||
</div>
|
||||
<div className="f-card-foot-right">
|
||||
{onEdit && (
|
||||
<button
|
||||
className="f-like-btn"
|
||||
onClick={e => {
|
||||
e.stopPropagation();
|
||||
onEdit(ad);
|
||||
}}
|
||||
>✏️</button>
|
||||
<button className="f-like-btn"
|
||||
onClick={e => { e.stopPropagation(); onEdit(ad); }}>
|
||||
✏️
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
className={`f-like-btn${liked ? " liked" : ""}`}
|
||||
onClick={e => {
|
||||
e.stopPropagation();
|
||||
onLike(ad.id);
|
||||
}}
|
||||
>
|
||||
<HeartIcon filled={liked}/>
|
||||
<button className={`f-like-btn${liked ? " liked" : ""}`}
|
||||
onClick={e => { e.stopPropagation(); onLike(ad.id); }}>
|
||||
<HeartIcon filled={liked} />
|
||||
{liked ? (ad.likes || 0) + 1 : (ad.likes || 0)}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -26,4 +26,5 @@ export const EMPTY_FORM = {
|
||||
location: "",
|
||||
phone: "",
|
||||
date: "",
|
||||
address: ""
|
||||
};
|
||||
102
src/hooks/useYandexMap.js
Normal file
102
src/hooks/useYandexMap.js
Normal file
@@ -0,0 +1,102 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
|
||||
export function useYandexMap(enabled, initialCoords = null, initialAddress = "") {
|
||||
const mapRef = useRef(null);
|
||||
const ymapRef = useRef(null);
|
||||
const placemarkRef = useRef(null);
|
||||
const initializedRef = useRef(false); // защита от двойного вызова StrictMode
|
||||
|
||||
const [coords, setCoords] = useState(initialCoords);
|
||||
const [address, setAddress] = useState(initialAddress ?? "");
|
||||
const addressRef = useRef(initialAddress ?? ""); // ← добавьте
|
||||
|
||||
|
||||
const resolveAddress = (lat, lng) => {
|
||||
fetch(
|
||||
`https://geocode-maps.yandex.ru/1.x/?apikey=c2d3c717-a109-4494-8863-7edbc32044e3&geocode=${lng},${lat}&format=json&lang=ru_RU`
|
||||
)
|
||||
.then(r => r.json())
|
||||
.then(data => {
|
||||
const found =
|
||||
data?.response?.GeoObjectCollection?.featureMember?.[0]
|
||||
?.GeoObject?.metaDataProperty?.GeocoderMetaData?.text;
|
||||
const resolved = found || `${lat.toFixed(5)}, ${lng.toFixed(5)}`;
|
||||
setAddress(resolved);
|
||||
addressRef.current = resolved;
|
||||
})
|
||||
.catch(() => {
|
||||
const fallback = `${lat.toFixed(5)}, ${lng.toFixed(5)}`;
|
||||
setAddress(fallback);
|
||||
addressRef.current = fallback;
|
||||
});
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled || !mapRef.current) return;
|
||||
if (initializedRef.current) return; // уже инициализировали
|
||||
initializedRef.current = true;
|
||||
|
||||
const init = () => {
|
||||
// Если карта уже создана — не создаём снова
|
||||
if (ymapRef.current) return;
|
||||
|
||||
const center = initialCoords
|
||||
? [initialCoords.latitude, initialCoords.longitude]
|
||||
: [55.751574, 37.573856];
|
||||
|
||||
const map = new window.ymaps.Map(mapRef.current, {
|
||||
center,
|
||||
zoom: 14,
|
||||
controls: ["zoomControl", "geolocationControl"],
|
||||
});
|
||||
ymapRef.current = map;
|
||||
|
||||
if (initialCoords) {
|
||||
const pm = new window.ymaps.Placemark(center, {}, { draggable: true });
|
||||
map.geoObjects.add(pm);
|
||||
placemarkRef.current = pm;
|
||||
resolveAddress(initialCoords.latitude, initialCoords.longitude);
|
||||
|
||||
pm.events.add("dragend", () => {
|
||||
const [lat, lng] = pm.geometry.getCoordinates();
|
||||
setCoords({ latitude: lat, longitude: lng });
|
||||
resolveAddress(lat, lng);
|
||||
});
|
||||
}
|
||||
|
||||
map.events.add("click", e => {
|
||||
const [lat, lng] = e.get("coords");
|
||||
setCoords({ latitude: lat, longitude: lng });
|
||||
resolveAddress(lat, lng);
|
||||
|
||||
if (placemarkRef.current) {
|
||||
placemarkRef.current.geometry.setCoordinates([lat, lng]);
|
||||
} else {
|
||||
const pm = new window.ymaps.Placemark([lat, lng], {}, { draggable: true });
|
||||
map.geoObjects.add(pm);
|
||||
placemarkRef.current = pm;
|
||||
|
||||
pm.events.add("dragend", () => {
|
||||
const [la, ln] = pm.geometry.getCoordinates();
|
||||
setCoords({ latitude: la, longitude: ln });
|
||||
resolveAddress(la, ln);
|
||||
});
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
if (window.ymaps?.ready) {
|
||||
window.ymaps.ready(init);
|
||||
}
|
||||
|
||||
return () => {
|
||||
// Уничтожаем карту только при размонтировании компонента
|
||||
ymapRef.current?.destroy();
|
||||
ymapRef.current = null;
|
||||
placemarkRef.current = null;
|
||||
initializedRef.current = false;
|
||||
};
|
||||
}, [enabled]);
|
||||
|
||||
return { mapRef, coords, address, addressRef };
|
||||
}
|
||||
Reference in New Issue
Block a user