added hints on map
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { useCallback, useState } from "react";
|
||||
import CloseIcon from "../components/icons/CloseIcon";
|
||||
import RulesModal from "./RulesModal";
|
||||
import { EMPTY_FORM, CATEGORIES } from "../config/feedConstants";
|
||||
@@ -7,10 +7,9 @@ import { usePostMutation } from "../hooks/usePostMutation";
|
||||
import { useImageUpload, ACCEPT, MAX_SIZE_MB } from "../hooks/useImageUpload";
|
||||
import { validatePostForm } from "../utils/validatePostForm";
|
||||
import { formatPhone } from "../utils/formatPhone";
|
||||
import { useYandexMap } from "../hooks/useYandexMap";
|
||||
import { useGeolocation, GEO_STATUS } from "../hooks/useGeolocation";
|
||||
import MapModal from "./MapModal";
|
||||
import ClearableField from "../components/ClearableField";
|
||||
import AddressAutocomplete from "../components/AddressAutocomplete";
|
||||
|
||||
/**
|
||||
* CreateUpdatePost — модальная форма создания и редактирования объявления.
|
||||
@@ -34,7 +33,7 @@ export default function CreateUpdatePost({ onClose, onSuccess, initialData, admi
|
||||
category: initialData.category || "",
|
||||
date: initialData.date || "",
|
||||
phone: initialData.phone || "",
|
||||
address: initialData.city || "",
|
||||
address: initialData.address || initialData.city || "",
|
||||
rulesAccepted: true,
|
||||
reward: initialData.reward ?? false,
|
||||
rewardText: initialData.rewardText
|
||||
@@ -67,37 +66,9 @@ export default function CreateUpdatePost({ onClose, onSuccess, initialData, admi
|
||||
? { latitude: initialData.latitude, longitude: initialData.longitude }
|
||||
: null;
|
||||
|
||||
const { mapRef, coords, address, addressRef, loading: mapLoading, loadError: mapLoadError, moveTo } = useYandexMap(
|
||||
mapModalOpen,
|
||||
initialCoords,
|
||||
isEdit ? (initialData.location || "") : ""
|
||||
);
|
||||
|
||||
const { coords: geoCoords, status: geoStatus, requestLocation: requestGeoLocation } =
|
||||
useGeolocation();
|
||||
// При открытии окна карты запрашиваем геолокацию; если пользователь дал
|
||||
// разрешение — автоматически центрируем карту и ставим маркер на его место.
|
||||
// При отказе/недоступности API ничего не делаем — остаётся дефолтный центр.
|
||||
useEffect(() => {
|
||||
if (mapModalOpen) {
|
||||
requestGeoLocation();
|
||||
}
|
||||
}, [mapModalOpen, requestGeoLocation]);
|
||||
|
||||
useEffect(() => {
|
||||
if (mapModalOpen && geoStatus === GEO_STATUS.SUCCESS && geoCoords) {
|
||||
moveTo(geoCoords.latitude, geoCoords.longitude);
|
||||
}
|
||||
}, [mapModalOpen, geoStatus, geoCoords, moveTo]);
|
||||
|
||||
useEffect(() => {
|
||||
if (address) {
|
||||
setForm(prev => ({ ...prev, address }));
|
||||
// Адрес пришёл — очищаем и ошибку поля, и "карта грузится",
|
||||
// иначе последняя может остаться висеть на экране навсегда.
|
||||
setErrors(prev => ({ ...prev, address: "", map: "" }));
|
||||
}
|
||||
}, [address]);
|
||||
// Точка на карте. Адрес лежит в form.address; точку задаёт выбор подсказки
|
||||
// в поле «Адрес» или выбор места в окне карты.
|
||||
const [coords, setCoords] = useState(initialCoords);
|
||||
|
||||
const loading = saving || compressing;
|
||||
|
||||
@@ -115,11 +86,6 @@ export default function CreateUpdatePost({ onClose, onSuccess, initialData, admi
|
||||
return;
|
||||
}
|
||||
|
||||
if (coords && !addressRef.current) {
|
||||
setErrors(prev => ({ ...prev, map: t('post.mapLoading') }));
|
||||
return;
|
||||
}
|
||||
|
||||
const data = new FormData();
|
||||
data.append("type", form.type.toUpperCase());
|
||||
data.append("title", form.title.trim());
|
||||
@@ -308,35 +274,37 @@ export default function CreateUpdatePost({ onClose, onSuccess, initialData, admi
|
||||
{errors.category && <p className="f-err-msg">{errors.category}</p>}
|
||||
</div>
|
||||
|
||||
{/* Место на карте */}
|
||||
{/* Адрес + карта: связаны в обе стороны, как на Яндекс Картах */}
|
||||
<div className="f-m-group">
|
||||
<label className="f-m-label">{t('post.mapLabel')}</label>
|
||||
<label className="f-m-label">{t('post.addressLabel')}</label>
|
||||
<AddressAutocomplete
|
||||
value={form.address}
|
||||
onChange={text => {
|
||||
// Адрес правят вручную — старая точка ему уже не соответствует
|
||||
set("address", text);
|
||||
setCoords(null);
|
||||
}}
|
||||
onSelect={({ address: picked, coords: [lat, lng] }) => {
|
||||
set("address", picked);
|
||||
setCoords({ latitude: lat, longitude: lng });
|
||||
}}
|
||||
getCenter={() => (coords ? [coords.latitude, coords.longitude] : null)}
|
||||
placeholder={t('post.addressPlaceholder')}
|
||||
invalid={!!errors.address}
|
||||
/>
|
||||
{errors.address && <p className="f-err-msg">{errors.address}</p>}
|
||||
|
||||
<button
|
||||
className="f-map-pick"
|
||||
className="f-map-pick f-map-open"
|
||||
type="button"
|
||||
onClick={() => setMapModalOpen(true)}
|
||||
>
|
||||
{form.address ? `📍 ${form.address}` : t('post.mapPickLabel')}
|
||||
📍 {t('post.openMap')}
|
||||
</button>
|
||||
{!coords && <p className="f-hint">{t('post.mapHint')}</p>}
|
||||
{mapLoadError && <p className="f-err-msg">{mapLoadError}</p>}
|
||||
{errors.map && <p className="f-err-msg">{errors.map}</p>}
|
||||
</div>
|
||||
|
||||
<div className="f-m-group">
|
||||
<label className="f-m-label">{t('post.addressLabel')}</label>
|
||||
<ClearableField onClear={() => set("address", "")} visible={!!form.address}>
|
||||
<input
|
||||
className={`f-m-field${errors.address ? " err" : ""}`}
|
||||
type="text"
|
||||
placeholder={t('post.addressPlaceholder')}
|
||||
value={form.address}
|
||||
onChange={e => set("address", e.target.value)}
|
||||
/>
|
||||
</ClearableField>
|
||||
{errors.address && <p className="f-err-msg">{errors.address}</p>}
|
||||
</div>
|
||||
|
||||
{/* Телефон */}
|
||||
<div className="f-m-group">
|
||||
<label className="f-m-label">{t('post.phoneLabel')}</label>
|
||||
@@ -440,12 +408,15 @@ export default function CreateUpdatePost({ onClose, onSuccess, initialData, admi
|
||||
|
||||
{mapModalOpen && (
|
||||
<MapModal
|
||||
mapRef={mapRef}
|
||||
address={address}
|
||||
mapLoading={mapLoading}
|
||||
geoStatus={geoStatus}
|
||||
initialCoords={coords}
|
||||
initialAddress={form.address}
|
||||
onClose={() => setMapModalOpen(false)}
|
||||
onSave={() => setMapModalOpen(false)}
|
||||
onPick={({ address: picked, coords: point }) => {
|
||||
set("address", picked);
|
||||
setCoords(point);
|
||||
setErrors(prev => ({ ...prev, map: "" }));
|
||||
setMapModalOpen(false);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
|
||||
@@ -1,20 +1,40 @@
|
||||
import { useEffect } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import CloseIcon from "../components/icons/CloseIcon";
|
||||
import { GEO_STATUS } from "../hooks/useGeolocation";
|
||||
import { useYandexMap, ADDRESS_ZOOM } from "../hooks/useYandexMap";
|
||||
import { useGeolocation, GEO_STATUS } from "../hooks/useGeolocation";
|
||||
|
||||
/**
|
||||
* MapModal — модальное окно с картой для выбора местоположения.
|
||||
* MapModal — модальное окно с картой для выбора места.
|
||||
*
|
||||
* @param {object} mapRef — ref, в который монтируется Яндекс.Карта
|
||||
* @param {string} address — текущий (выбранный) адрес
|
||||
* @param {boolean} mapLoading — идёт ли подгрузка адреса по координатам
|
||||
* @param {string} geoStatus — статус геолокации (GEO_STATUS.*)
|
||||
* @param {function} onClose — закрыть окно без сохранения
|
||||
* @param {function} onSave — сохранить выбранное местоположение
|
||||
* Клик по карте / перетаскивание метки определяет адрес; в форму он попадает
|
||||
* только по кнопке «Выбрать». Закрытие окна ничего не меняет.
|
||||
*
|
||||
* @param {{ latitude: number, longitude: number } | null} initialCoords — текущая точка формы
|
||||
* @param {string} initialAddress — текущий адрес формы
|
||||
* @param {function} onClose — закрыть окно без выбора
|
||||
* @param {function} onPick — выбрано место: ({ address, coords: { latitude, longitude } }) => void
|
||||
*/
|
||||
export default function MapModal({ mapRef, address, mapLoading, geoStatus, onClose, onSave }) {
|
||||
export default function MapModal({ initialCoords, initialAddress, onClose, onPick }) {
|
||||
const { t } = useTranslation();
|
||||
const { mapRef, coords, address, loading, loadError, addressError, moveTo } =
|
||||
useYandexMap(true, initialCoords, initialCoords ? initialAddress : "");
|
||||
|
||||
const { coords: geoCoords, status: geoStatus, requestLocation } = useGeolocation();
|
||||
|
||||
// Точки ещё нет — пробуем поставить метку на место пользователя.
|
||||
// При отказе/недоступности остаётся центр по умолчанию.
|
||||
useEffect(() => {
|
||||
if (!initialCoords) requestLocation();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [requestLocation]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!initialCoords && geoStatus === GEO_STATUS.SUCCESS && geoCoords) {
|
||||
moveTo(geoCoords.latitude, geoCoords.longitude, { zoom: ADDRESS_ZOOM });
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [geoStatus, geoCoords, moveTo]);
|
||||
|
||||
useEffect(() => {
|
||||
const prev = document.body.style.overflow;
|
||||
@@ -23,17 +43,17 @@ export default function MapModal({ mapRef, address, mapLoading, geoStatus, onClo
|
||||
}, []);
|
||||
|
||||
const geoHint =
|
||||
geoStatus === GEO_STATUS.SUCCESS ? t('post.geoSuccess')
|
||||
: geoStatus === GEO_STATUS.LOADING ? t('post.geoLoading')
|
||||
: geoStatus === GEO_STATUS.DENIED ? t('post.geoDenied')
|
||||
: geoStatus === GEO_STATUS.UNSUPPORTED ? t('post.geoUnsupported')
|
||||
: geoStatus === GEO_STATUS.TIMEOUT ? t('post.geoTimeout')
|
||||
: null;
|
||||
geoStatus === GEO_STATUS.LOADING ? t('post.geoLoading')
|
||||
: geoStatus === GEO_STATUS.DENIED ? t('post.geoDenied')
|
||||
: geoStatus === GEO_STATUS.UNSUPPORTED ? t('post.geoUnsupported')
|
||||
: geoStatus === GEO_STATUS.TIMEOUT ? t('post.geoTimeout')
|
||||
: null;
|
||||
|
||||
const canPick = !!coords && !!address && !loading;
|
||||
|
||||
return (
|
||||
<div className="f-modal-bg" onClick={e => e.target === e.currentTarget && onClose()}>
|
||||
<div className="f-modal f-map-modal">
|
||||
{/* Header */}
|
||||
<div className="f-modal-head">
|
||||
<span className="f-modal-title">{t('post.mapLabel')}</span>
|
||||
<button className="f-close-btn" type="button" onClick={onClose}>
|
||||
@@ -41,28 +61,31 @@ export default function MapModal({ mapRef, address, mapLoading, geoStatus, onClo
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Map */}
|
||||
<div className="f-map-frame f-map-modal-frame">
|
||||
<div className={`f-map-frame f-map-modal-frame${loading ? " loading" : ""}`}>
|
||||
<div ref={mapRef} className="f-map-inner" />
|
||||
</div>
|
||||
|
||||
{geoHint && (
|
||||
<div className="f-map-geo">{geoHint}</div>
|
||||
)}
|
||||
{!coords && geoHint && <div className="f-map-geo">{geoHint}</div>}
|
||||
{loadError && <p className="f-err-msg">{loadError}</p>}
|
||||
|
||||
{/* Selected address */}
|
||||
<div className="f-map-selected">
|
||||
<span className="f-map-selected-label">{t('post.selectedAddress')}</span>
|
||||
<span className="f-map-selected-value">
|
||||
{mapLoading ? t('post.mapLoading') : (address || t('post.mapEmpty'))}
|
||||
{loading ? t('post.mapLoading')
|
||||
: addressError ? t('post.addressNotDetected')
|
||||
: (coords && address) || t('post.mapEmpty')}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<button className="f-m-submit" type="button" onClick={onSave} disabled={mapLoading}>
|
||||
<div className="f-m-submit-row">{t('post.saveLocation')}</div>
|
||||
<button
|
||||
className="f-m-submit"
|
||||
type="button"
|
||||
disabled={!canPick}
|
||||
onClick={() => onPick({ address, coords })}
|
||||
>
|
||||
<div className="f-m-submit-row">{t('post.pickLocation')}</div>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user